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

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

Complete rewriting of the api
The api now uses interfaces everywhere (for the dao, services and session manager). This allows the developer to use his own implementations if he wants.
Deletion of the singletons. There are now getters and setters. It allows to make dependency injection.
Use of sl4j in the api, instead of using log4j.

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