source: extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/transverse/session/impl/SessionManagerImpl.java @ 10714

Last change on this file since 10714 was 10714, checked in by mlg, 13 years ago

Adds support for method pwg.categories.delete
(allows to delete a category).

File size: 10.2 KB
Line 
1package fr.mael.jiwigo.transverse.session.impl;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.io.UnsupportedEncodingException;
6import java.util.ArrayList;
7import java.util.List;
8
9import javax.xml.parsers.ParserConfigurationException;
10
11import org.apache.commons.lang.StringUtils;
12import org.apache.http.HttpHost;
13import org.apache.http.HttpResponse;
14import org.apache.http.NameValuePair;
15import org.apache.http.auth.AuthScope;
16import org.apache.http.auth.UsernamePasswordCredentials;
17import org.apache.http.client.ClientProtocolException;
18import org.apache.http.client.entity.UrlEncodedFormEntity;
19import org.apache.http.client.methods.HttpGet;
20import org.apache.http.client.methods.HttpPost;
21import org.apache.http.conn.params.ConnRoutePNames;
22import org.apache.http.impl.client.DefaultHttpClient;
23import org.apache.http.message.BasicNameValuePair;
24import org.slf4j.Logger;
25import org.slf4j.LoggerFactory;
26import org.w3c.dom.Document;
27import org.xml.sax.SAXException;
28
29import fr.mael.jiwigo.transverse.enumeration.MethodsEnum;
30import fr.mael.jiwigo.transverse.exception.FileAlreadyExistsException;
31import fr.mael.jiwigo.transverse.exception.JiwigoException;
32import fr.mael.jiwigo.transverse.exception.ProxyAuthenticationException;
33import fr.mael.jiwigo.transverse.session.SessionManager;
34import fr.mael.jiwigo.transverse.util.Tools;
35
36/*
37 *  jiwigo-ws-api Piwigo webservice access Api
38 *  Copyright (c) 2010-2011 Mael mael@le-guevel.com
39 *                All Rights Reserved
40 *
41 *  This library is free software. It comes without any warranty, to
42 *  the extent permitted by applicable law. You can redistribute it
43 *  and/or modify it under the terms of the Do What The Fuck You Want
44 *  To Public License, Version 2, as published by Sam Hocevar. See
45 *  http://sam.zoy.org/wtfpl/COPYING for more details.
46 */
47/**
48
49 * @author mael
50 * Gestionnaire de connexion
51 */
52public class SessionManagerImpl implements SessionManager {
53
54    /**
55     * Logger
56     */
57    private final Logger LOG = LoggerFactory.getLogger(SessionManagerImpl.class);
58    /**
59     * the entered login
60     */
61    private String login;
62    /**
63     * the entered password
64     */
65    private String password;
66    /**
67     * the url of the site
68     */
69    private String url;
70    /**
71     * the http client
72     */
73    private DefaultHttpClient client;
74
75    /**
76     * defines if the user uses a proxy
77     */
78    private boolean usesProxy;
79
80    /**
81     * url of the proxy
82     */
83    private String urlProxy;
84
85    /**
86     * port of the proxy
87     */
88    private int portProxy;
89
90    /**
91     * login for the proxy
92     */
93    private String loginProxy;
94
95    /**
96     * pass for the proxy
97     */
98    private String passProxy;
99
100    /**
101     * true : an error was found for the proxy
102     */
103    private boolean proxyError;
104
105    public SessionManagerImpl() {
106        client = new DefaultHttpClient();
107    }
108
109    /**
110     * Constructor
111     * @param login the login
112     * @param password the password
113     * @param url the url of the site
114     * @param userAgent the user agent to use
115     */
116    public SessionManagerImpl(String login, String password, String url, String userAgent) {
117        this.login = login;
118        this.password = password;
119        this.url = url + "/ws.php";
120        //      MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
121        //      client = new HttpClient(connectionManager);
122        //      ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(null, null);
123        client = new DefaultHttpClient();
124        //Using of a Linux user agent. cause... it's better 8)
125        client.getParams().setParameter("http.useragent", userAgent);
126
127    }
128
129    /**
130     * Fonction used to set the user agent of the http client
131     * @param userAgent
132     */
133    public void setUserAgent(String userAgent) {
134        client.getParams().setParameter("http.useragent", userAgent);
135    }
136
137    /**
138     * Connection method
139     *
140     * @return 0 if Ok, 1 if not Ok (reason not specified), 2 if proxy error
141     * @throws JiwigoException
142     *
143     *
144     */
145    public int processLogin() throws JiwigoException {
146        Document doc;
147        //configures the proxy
148        if (usesProxy) {
149            //      HostConfiguration config = client.getHostConfiguration();
150            //      config.setProxy(urlProxy, portProxy);
151            if (!StringUtils.isEmpty(loginProxy) && !StringUtils.isEmpty(passProxy)) {
152                //              Credentials credentials = new UsernamePasswordCredentials(loginProxy, passProxy);
153                //              AuthScope authScope = new AuthScope(urlProxy, portProxy);
154                //              client.getState().setProxyCredentials(authScope, credentials);
155                HttpHost proxy = new HttpHost(urlProxy, portProxy);
156                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
157                client.getCredentialsProvider().setCredentials(new AuthScope(urlProxy, portProxy),
158                        new UsernamePasswordCredentials(loginProxy, passProxy));
159
160            }
161        }
162        doc = executeReturnDocument(MethodsEnum.LOGIN.getLabel(), "username", login, "password", password);
163        if (LOG.isDebugEnabled()) {
164            LOG.debug("XML connection : " + Tools.documentToString(doc));
165        }
166        try {
167            return (Tools.checkOk(doc) ? 0 : 1);
168        } catch (FileAlreadyExistsException e) {
169            LOG.error(Tools.getStackTrace(e));
170            throw new JiwigoException(e);
171        }
172
173    }
174
175    /**
176     * Executes a method on the webservice and returns the result as a string
177     * @param methode the method to execute
178     * @param parametres the parameters of the method. Must be even : the name of the parameter followed by its value
179     * @return the result
180     * @throws ProxyAuthenticationException
181     * @throws JiwigoException
182     * @throws IOException
183     * @throws ClientProtocolException
184     */
185    public String executeReturnString(String methode, String... parametres) throws ProxyAuthenticationException,
186            JiwigoException, ClientProtocolException, IOException {
187        if (parametres.length % 2 != 0 && !(parametres == null)) {
188            LOG.error("parameters number should be even");
189            throw new IllegalArgumentException("parameters number should be even");
190        }
191        HttpPost method = new HttpPost(url);
192        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
193        nameValuePairs.add(new BasicNameValuePair("method", methode));
194        for (int i = 0; i < parametres.length; i += 2) {
195            nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
196        }
197        method.setEntity(new UrlEncodedFormEntity(nameValuePairs));
198        method.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
199        HttpResponse response = client.execute(method);
200        int statusCode = response.getStatusLine().getStatusCode();
201        InputStream inputStream = response.getEntity().getContent();
202        String toReturn = Tools.readInputStreamAsString(inputStream);
203        if (statusCode == 407) {
204            throw new ProxyAuthenticationException("Error while trying to auth on the proxy");
205        } else if (statusCode >= 400) {
206            throw new JiwigoException("Piwigo server returned an error code " + toReturn);
207        }
208
209        return toReturn;
210
211    }
212
213    /**
214     * Executes a method on the webservice and returns the result as a Dom document
215     * @param methode the method to execute
216     * @param parametres the parameters of the method. Must be even : the name of the parameter followed by its value
217     * @return the result
218     * @throws IOException
219     * @throws ProxyAuthenticationException
220     * @throws JiwigoException
221     */
222    public Document executeReturnDocument(String methode, String... parametres) throws JiwigoException {
223        try {
224            String returnedString = executeReturnString(methode, parametres);
225            return Tools.stringToDocument(returnedString);
226        } catch (ProxyAuthenticationException e) {
227            LOG.error(Tools.getStackTrace(e));
228            throw new JiwigoException(e);
229        } catch (SAXException e) {
230            LOG.error(Tools.getStackTrace(e));
231            throw new JiwigoException(e);
232        } catch (ParserConfigurationException e) {
233            LOG.error(Tools.getStackTrace(e));
234            throw new JiwigoException(e);
235        } catch (UnsupportedEncodingException e) {
236            LOG.error(Tools.getStackTrace(e));
237            throw new JiwigoException(e);
238        } catch (IOException e) {
239            LOG.error(Tools.getStackTrace(e));
240            throw new JiwigoException(e);
241        }
242    }
243
244    /**
245     * Executes a method on the webservice and returns the result as a Dom document
246     * @param methode the method to execute
247     * @return the result
248     * @throws JiwigoException
249     */
250    public Document executeReturnDocument(String methode) throws JiwigoException {
251        try {
252            return Tools.stringToDocument(executeReturnString(methode));
253        } catch (Exception e) {
254            LOG.error(Tools.getStackTrace(e));
255            throw new JiwigoException(e);
256        }
257    }
258
259    public InputStream getInputStreamFromUrl(String url) throws Exception {
260        InputStream content = null;
261        HttpGet httpGet = new HttpGet(url);
262        HttpResponse response = client.execute(httpGet);
263        content = response.getEntity().getContent();
264        return content;
265    }
266
267    /**
268     * @return the login
269     */
270    public String getLogin() {
271        return login;
272    }
273
274    /**
275     * @param login the login to set
276     */
277    public void setLogin(String login) {
278        this.login = login;
279    }
280
281    /**
282     * @return the url
283     */
284    public String getUrl() {
285        return url;
286    }
287
288    /**
289     * @param url the url to set
290     */
291    public void setUrl(String url) {
292        this.url = url;
293    }
294
295    /**
296     * @param usesProxy the usesProxy to set
297     */
298    public void setUsesProxy(boolean usesProxy) {
299        this.usesProxy = usesProxy;
300    }
301
302    /**
303     * @param urlProxy the urlProxy to set
304     */
305    public void setUrlProxy(String urlProxy) {
306        this.urlProxy = urlProxy;
307    }
308
309    /**
310     * @param portProxy the portProxy to set
311     */
312    public void setPortProxy(int portProxy) {
313        this.portProxy = portProxy;
314    }
315
316    /**
317     * @param loginProxy the loginProxy to set
318     */
319    public void setLoginProxy(String loginProxy) {
320        this.loginProxy = loginProxy;
321    }
322
323    /**
324     * @param passProxy the passProxy to set
325     */
326    public void setPassProxy(String passProxy) {
327        this.passProxy = passProxy;
328    }
329
330    public String getPassword() {
331        return password;
332    }
333
334    public void setPassword(String password) {
335        this.password = password;
336    }
337
338    public boolean isProxyError() {
339        return proxyError;
340    }
341
342    public void setProxyError(boolean proxyError) {
343        this.proxyError = proxyError;
344    }
345
346    public DefaultHttpClient getClient() {
347        return client;
348    }
349
350}
Note: See TracBrowser for help on using the repository browser.