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

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

Modifications to try to have a better image quality on resizing

File size: 10.1 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        try {
164            return (Tools.checkOk(doc) ? 0 : 1);
165        } catch (FileAlreadyExistsException e) {
166            LOG.error(Tools.getStackTrace(e));
167            throw new JiwigoException(e);
168        }
169
170    }
171
172    /**
173     * Executes a method on the webservice and returns the result as a string
174     * @param methode the method to execute
175     * @param parametres the parameters of the method. Must be even : the name of the parameter followed by its value
176     * @return the result
177     * @throws ProxyAuthenticationException
178     * @throws JiwigoException
179     * @throws IOException
180     * @throws ClientProtocolException
181     */
182    public String executeReturnString(String methode, String... parametres) throws ProxyAuthenticationException,
183            JiwigoException, ClientProtocolException, IOException {
184        if (parametres.length % 2 != 0 && !(parametres == null)) {
185            LOG.error("parameters number should be even");
186            throw new IllegalArgumentException("parameters number should be even");
187        }
188        HttpPost method = new HttpPost(url);
189        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
190        nameValuePairs.add(new BasicNameValuePair("method", methode));
191        for (int i = 0; i < parametres.length; i += 2) {
192            nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
193        }
194        method.setEntity(new UrlEncodedFormEntity(nameValuePairs));
195        method.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
196        HttpResponse response = client.execute(method);
197        int statusCode = response.getStatusLine().getStatusCode();
198        InputStream inputStream = response.getEntity().getContent();
199        String toReturn = Tools.readInputStreamAsString(inputStream);
200        if (statusCode == 407) {
201            throw new ProxyAuthenticationException("Error while trying to auth on the proxy");
202        } else if (statusCode >= 400) {
203            throw new JiwigoException("Piwigo server returned an error code " + toReturn);
204        }
205
206        return toReturn;
207
208    }
209
210    /**
211     * Executes a method on the webservice and returns the result as a Dom document
212     * @param methode the method to execute
213     * @param parametres the parameters of the method. Must be even : the name of the parameter followed by its value
214     * @return the result
215     * @throws IOException
216     * @throws ProxyAuthenticationException
217     * @throws JiwigoException
218     */
219    public Document executeReturnDocument(String methode, String... parametres) throws JiwigoException {
220        try {
221            String returnedString = executeReturnString(methode, parametres);
222            return Tools.stringToDocument(returnedString);
223        } catch (ProxyAuthenticationException e) {
224            LOG.error(Tools.getStackTrace(e));
225            throw new JiwigoException(e);
226        } catch (SAXException e) {
227            LOG.error(Tools.getStackTrace(e));
228            throw new JiwigoException(e);
229        } catch (ParserConfigurationException e) {
230            LOG.error(Tools.getStackTrace(e));
231            throw new JiwigoException(e);
232        } catch (UnsupportedEncodingException e) {
233            LOG.error(Tools.getStackTrace(e));
234            throw new JiwigoException(e);
235        } catch (IOException e) {
236            LOG.error(Tools.getStackTrace(e));
237            throw new JiwigoException(e);
238        }
239    }
240
241    /**
242     * Executes a method on the webservice and returns the result as a Dom document
243     * @param methode the method to execute
244     * @return the result
245     * @throws JiwigoException
246     */
247    public Document executeReturnDocument(String methode) throws JiwigoException {
248        try {
249            return Tools.stringToDocument(executeReturnString(methode));
250        } catch (Exception e) {
251            LOG.error(Tools.getStackTrace(e));
252            throw new JiwigoException(e);
253        }
254    }
255
256    public InputStream getInputStreamFromUrl(String url) throws Exception {
257        InputStream content = null;
258        HttpGet httpGet = new HttpGet(url);
259        HttpResponse response = client.execute(httpGet);
260        content = response.getEntity().getContent();
261        return content;
262    }
263
264    /**
265     * @return the login
266     */
267    public String getLogin() {
268        return login;
269    }
270
271    /**
272     * @param login the login to set
273     */
274    public void setLogin(String login) {
275        this.login = login;
276    }
277
278    /**
279     * @return the url
280     */
281    public String getUrl() {
282        return url;
283    }
284
285    /**
286     * @param url the url to set
287     */
288    public void setUrl(String url) {
289        this.url = url;
290    }
291
292    /**
293     * @param usesProxy the usesProxy to set
294     */
295    public void setUsesProxy(boolean usesProxy) {
296        this.usesProxy = usesProxy;
297    }
298
299    /**
300     * @param urlProxy the urlProxy to set
301     */
302    public void setUrlProxy(String urlProxy) {
303        this.urlProxy = urlProxy;
304    }
305
306    /**
307     * @param portProxy the portProxy to set
308     */
309    public void setPortProxy(int portProxy) {
310        this.portProxy = portProxy;
311    }
312
313    /**
314     * @param loginProxy the loginProxy to set
315     */
316    public void setLoginProxy(String loginProxy) {
317        this.loginProxy = loginProxy;
318    }
319
320    /**
321     * @param passProxy the passProxy to set
322     */
323    public void setPassProxy(String passProxy) {
324        this.passProxy = passProxy;
325    }
326
327    public String getPassword() {
328        return password;
329    }
330
331    public void setPassword(String password) {
332        this.password = password;
333    }
334
335    public boolean isProxyError() {
336        return proxyError;
337    }
338
339    public void setProxyError(boolean proxyError) {
340        this.proxyError = proxyError;
341    }
342
343    public DefaultHttpClient getClient() {
344        return client;
345    }
346
347}
Note: See TracBrowser for help on using the repository browser.