source: extensions/jiwigo-ws-api/src/main/java/fr/mael/jiwigo/transverse/session/SessionManager.java @ 9430

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

Modifications to handle proxy error.
Two types of error are handled : proxy address error and proxy authentication error.
Connecting to jiwigo via a proxy seems to work (tried with my own server... gonna have to try with an external server).
version is 0.13.1.1

File size: 9.3 KB
Line 
1package fr.mael.jiwigo.transverse.session;
2
3import java.io.IOException;
4import java.io.InputStream;
5import java.io.UnsupportedEncodingException;
6
7import org.apache.commons.httpclient.Credentials;
8import org.apache.commons.httpclient.HostConfiguration;
9import org.apache.commons.httpclient.HttpClient;
10import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
11import org.apache.commons.httpclient.UsernamePasswordCredentials;
12import org.apache.commons.httpclient.auth.AuthScope;
13import org.apache.commons.httpclient.methods.PostMethod;
14import org.apache.commons.lang.StringUtils;
15import org.jdom.Document;
16import org.jdom.JDOMException;
17
18import fr.mael.jiwigo.transverse.enumeration.MethodsEnum;
19import fr.mael.jiwigo.transverse.exception.ProxyAuthenticationException;
20import fr.mael.jiwigo.transverse.util.Tools;
21
22/*
23Copyright (c) 2010, Mael
24All rights reserved.
25
26Redistribution and use in source and binary forms, with or without
27modification, are permitted provided that the following conditions are met:
28 * Redistributions of source code must retain the above copyright
29   notice, this list of conditions and the following disclaimer.
30 * Redistributions in binary form must reproduce the above copyright
31   notice, this list of conditions and the following disclaimer in the
32   documentation and/or other materials provided with the distribution.
33 * Neither the name of jiwigo nor the
34   names of its contributors may be used to endorse or promote products
35   derived from this software without specific prior written permission.
36
37THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
38ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
39WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40DISCLAIMED. IN NO EVENT SHALL Mael BE LIABLE FOR ANY
41DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
42(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
45(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
46SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
47*/
48/**
49
50 * @author mael
51 * Gestionnaire de connexion
52 */
53public class SessionManager {
54
55    /**
56     * Logger
57     */
58    public static final org.apache.commons.logging.Log LOG = org.apache.commons.logging.LogFactory
59            .getLog(SessionManager.class);
60    /**
61     * the entered login
62     */
63    private String login;
64    /**
65     * the entered password
66     */
67    private String password;
68    /**
69     * the url of the site
70     */
71    private String url;
72    /**
73     * the http client
74     */
75    private HttpClient client;
76
77    /**
78     * defines if the user uses a proxy
79     */
80    private boolean usesProxy;
81
82    /**
83     * url of the proxy
84     */
85    private String urlProxy;
86
87    /**
88     * port of the proxy
89     */
90    private int portProxy;
91
92    /**
93     * login for the proxy
94     */
95    private String loginProxy;
96
97    /**
98     * pass for the proxy
99     */
100    private String passProxy;
101
102    /**
103     * true : an error was found for the proxy
104     */
105    private boolean proxyError;
106
107    /**
108     * Constructor
109     * @param login the login
110     * @param password the password
111     * @param url the url of the site
112     */
113    public SessionManager(String login, String password, String url) {
114        this.login = login;
115        this.password = password;
116        this.url = url + "/ws.php";
117        MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
118        client = new HttpClient(connectionManager);
119        //Using of a Linux user agent. cause... it's better 8)
120        client.getParams().setParameter("http.useragent",
121                "Mozilla/5.0 (X11; U; Linux i686; fr; rv:1.9.1.1) Gecko/20090715 Firefox/3.5.1");
122
123    }
124
125    /**
126     * Connection method
127     *
128     * @return 0 if Ok, 1 if not Ok (reason not specified), 2 if proxy error
129     *
130     *
131     */
132    public int processLogin() {
133        Document doc;
134        //configures the proxy
135        if (usesProxy) {
136            HostConfiguration config = client.getHostConfiguration();
137            config.setProxy(urlProxy, portProxy);
138            if (!StringUtils.isEmpty(loginProxy) && !StringUtils.isEmpty(passProxy)) {
139                Credentials credentials = new UsernamePasswordCredentials(loginProxy, passProxy);
140                AuthScope authScope = new AuthScope(urlProxy, portProxy);
141                client.getState().setProxyCredentials(authScope, credentials);
142            }
143        }
144        //      try {
145        try {
146            doc = executeReturnDocument(MethodsEnum.LOGIN.getLabel(), "username", login, "password", password);
147            return (Tools.checkOk(doc) ? 0 : 1);
148        } catch (IOException e) {
149            LOG.debug(Tools.getStackTrace(e));
150            return 1;
151        } catch (ProxyAuthenticationException e) {
152            LOG.debug(Tools.getStackTrace(e));
153            return 2;
154        } catch (Exception e) {
155            LOG.debug(Tools.getStackTrace(e));
156            return 1;
157        }
158
159    }
160
161    /**
162     * Executes a method on the webservice and returns the result as a string
163     * @param methode the method to execute
164     * @param parametres the parameters of the method. Must be even : the name of the parameter followed by its value
165     * @return the result
166     * @throws UnsupportedEncodingException
167     * @throws ProxyAuthenticationException
168     */
169    public String executeReturnString(String methode, String... parametres) throws UnsupportedEncodingException,
170            ProxyAuthenticationException {
171        if (parametres.length % 2 != 0 && !(parametres == null)) {
172            try {
173                throw new Exception("Le nombre de parametres doit etre pair");
174            } catch (Exception e) {
175                LOG.error(Tools.getStackTrace(e));
176                return null;
177            }
178        }
179        PostMethod method = new PostMethod(url);
180        method.addParameter("method", methode);
181        for (int i = 0; i < parametres.length; i += 2) {
182            //      System.out.println(parametres[i] + " -> " + parametres[i + 1]);
183            method.addParameter(parametres[i], parametres[i + 1]);
184
185        }
186        //begin bug:0001833
187        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
188        //end
189        try {
190            int test = client.executeMethod(method);
191            if (test == 407) {
192                throw new ProxyAuthenticationException("Proxy configuration exception. Check username and password");
193            }
194            InputStream streamResponse = method.getResponseBodyAsStream();
195            //      System.out.println(Outil.readInputStreamAsString(streamResponse));
196            //      String toReturn = method.getResponseBodyAsString();
197            String toReturn = Tools.readInputStreamAsString(streamResponse);
198            LOG.debug(toReturn);
199            return toReturn;
200        } catch (IOException e) {
201
202        }
203        return null;
204
205    }
206
207    /**
208     * Executes a method on the webservice and returns the result as a Dom document
209     * @param methode the method to execute
210     * @param parametres the parameters of the method. Must be even : the name of the parameter followed by its value
211     * @return the result
212     * @throws IOException
213     * @throws ProxyAuthenticationException
214     */
215    public Document executeReturnDocument(String methode, String... parametres) throws IOException,
216            ProxyAuthenticationException {
217        try {
218            String returnedString = executeReturnString(methode, parametres);
219            return Tools.stringToDocument(returnedString);
220        } catch (JDOMException e) {
221            // TODO Auto-generated catch block
222            LOG.error(Tools.getStackTrace(e));
223        }
224        return null;
225
226    }
227
228    /**
229     * Executes a method on the webservice and returns the result as a Dom document
230     * @param methode the method to execute
231     * @return the result
232     * @throws ProxyAuthenticationException
233     */
234    public Document executeReturnDocument(String methode) throws ProxyAuthenticationException {
235        try {
236            return Tools.stringToDocument(executeReturnString(methode));
237        } catch (JDOMException e) {
238            // TODO Auto-generated catch block
239            LOG.error(Tools.getStackTrace(e));
240        } catch (IOException e) {
241            // TODO Auto-generated catch block
242            LOG.error(Tools.getStackTrace(e));
243        }
244        return null;
245
246    }
247
248    /**
249     * @return the login
250     */
251    public String getLogin() {
252        return login;
253    }
254
255    /**
256     * @param login the login to set
257     */
258    public void setLogin(String login) {
259        this.login = login;
260    }
261
262    /**
263     * @return the url
264     */
265    public String getUrl() {
266        return url;
267    }
268
269    /**
270     * @param url the url to set
271     */
272    public void setUrl(String url) {
273        this.url = url;
274    }
275
276    /**
277     * @param usesProxy the usesProxy to set
278     */
279    public void setUsesProxy(boolean usesProxy) {
280        this.usesProxy = usesProxy;
281    }
282
283    /**
284     * @param urlProxy the urlProxy to set
285     */
286    public void setUrlProxy(String urlProxy) {
287        this.urlProxy = urlProxy;
288    }
289
290    /**
291     * @param portProxy the portProxy to set
292     */
293    public void setPortProxy(int portProxy) {
294        this.portProxy = portProxy;
295    }
296
297    /**
298     * @param loginProxy the loginProxy to set
299     */
300    public void setLoginProxy(String loginProxy) {
301        this.loginProxy = loginProxy;
302    }
303
304    /**
305     * @param passProxy the passProxy to set
306     */
307    public void setPassProxy(String passProxy) {
308        this.passProxy = passProxy;
309    }
310
311    public String getPassword() {
312        return password;
313    }
314
315    public void setPassword(String password) {
316        this.password = password;
317    }
318
319    public boolean isProxyError() {
320        return proxyError;
321    }
322
323    public void setProxyError(boolean proxyError) {
324        this.proxyError = proxyError;
325    }
326
327}
Note: See TracBrowser for help on using the repository browser.