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

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

First commit for jiwigo-ws-api

File size: 9.0 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.HttpException;
11import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
12import org.apache.commons.httpclient.UsernamePasswordCredentials;
13import org.apache.commons.httpclient.auth.AuthScope;
14import org.apache.commons.httpclient.methods.PostMethod;
15import org.apache.commons.lang.StringUtils;
16import org.jdom.Document;
17import org.jdom.JDOMException;
18
19import fr.mael.jiwigo.transverse.enumeration.MethodsEnum;
20import fr.mael.jiwigo.transverse.util.Outil;
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 motDePasse;
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 erreurProxy;
106
107    /**
108     * Constructor
109     * @param login the login
110     * @param motDePasse the password
111     * @param url the url of the site
112     */
113    public SessionManager(String login, String motDePasse, String url) {
114        this.login = login;
115        this.motDePasse = motDePasse;
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     * @return true if successful
128     */
129    public boolean processLogin() {
130        Document doc;
131        //configures the proxy
132        if (usesProxy) {
133            HostConfiguration config = client.getHostConfiguration();
134            config.setProxy(urlProxy, portProxy);
135            if (!StringUtils.isEmpty(loginProxy) && !StringUtils.isEmpty(passProxy)) {
136                Credentials credentials = new UsernamePasswordCredentials(loginProxy, passProxy);
137                AuthScope authScope = new AuthScope(urlProxy, portProxy);
138                client.getState().setProxyCredentials(authScope, credentials);
139            }
140        }
141        try {
142            doc = executerReturnDocument(MethodsEnum.LOGIN.getLabel(), "username", login, "password", motDePasse);
143            return Outil.checkOk(doc);
144        } catch (Exception e) {
145            LOG.error(Outil.getStackTrace(e));
146        }
147        return false;
148    }
149
150    /**
151     * Executes a method on the webservice and returns the result as a string
152     * @param methode the method to execute
153     * @param parametres the parameters of the method. Must be even : the name of the parameter followed by its value
154     * @return the result
155     * @throws UnsupportedEncodingException
156     */
157    public String executerReturnString(String methode, String... parametres) throws UnsupportedEncodingException {
158        if (parametres.length % 2 != 0 && !(parametres == null)) {
159            try {
160                throw new Exception("Le nombre de parametres doit etre pair");
161            } catch (Exception e) {
162                LOG.error(Outil.getStackTrace(e));
163                return null;
164            }
165        }
166        PostMethod method = new PostMethod(url);
167        method.addParameter("method", methode);
168        for (int i = 0; i < parametres.length; i += 2) {
169            System.out.println(parametres[i] + " -> " + parametres[i + 1]);
170            method.addParameter(parametres[i], parametres[i + 1]);
171
172        }
173        //begin bug:0001833
174        method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
175        //end
176
177        try {
178            client.executeMethod(method);
179            InputStream streamResponse = method.getResponseBodyAsStream();
180            //      System.out.println(Outil.readInputStreamAsString(streamResponse));
181            //      String toReturn = method.getResponseBodyAsString();
182            String toReturn = Outil.readInputStreamAsString(streamResponse);
183            LOG.debug(toReturn);
184            return toReturn;
185        } catch (HttpException e) {
186            // TODO Auto-generated catch block
187            LOG.error(Outil.getStackTrace(e));
188        } catch (IOException e) {
189            // TODO Auto-generated catch block
190            LOG.error(Outil.getStackTrace(e));
191        } catch (IllegalArgumentException e) {
192            LOG.error(Outil.getStackTrace(e));
193        } finally {
194            method.releaseConnection();
195        }
196        return null;
197
198    }
199
200    /**
201     * Executes a method on the webservice and returns the result as a Dom document
202     * @param methode the method to execute
203     * @param parametres the parameters of the method. Must be even : the name of the parameter followed by its value
204     * @return the result
205     * @throws IOException
206     */
207    public Document executerReturnDocument(String methode, String... parametres) throws IOException {
208        try {
209            return Outil.stringToDocument(executerReturnString(methode, parametres));
210        } catch (JDOMException e) {
211            // TODO Auto-generated catch block
212            LOG.error(Outil.getStackTrace(e));
213        }
214        return null;
215
216    }
217
218    /**
219     * Executes a method on the webservice and returns the result as a Dom document
220     * @param methode the method to execute
221     * @return the result
222     */
223    public Document executerReturnDocument(String methode) {
224        try {
225            return Outil.stringToDocument(executerReturnString(methode));
226        } catch (JDOMException e) {
227            // TODO Auto-generated catch block
228            LOG.error(Outil.getStackTrace(e));
229        } catch (IOException e) {
230            // TODO Auto-generated catch block
231            LOG.error(Outil.getStackTrace(e));
232        }
233        return null;
234
235    }
236
237    /**
238     * @return the login
239     */
240    public String getLogin() {
241        return login;
242    }
243
244    /**
245     * @param login the login to set
246     */
247    public void setLogin(String login) {
248        this.login = login;
249    }
250
251    /**
252     * @return the motDePasse
253     */
254    public String getMotDePasse() {
255        return motDePasse;
256    }
257
258    /**
259     * @param motDePasse the motDePasse to set
260     */
261    public void setMotDePasse(String motDePasse) {
262        this.motDePasse = motDePasse;
263    }
264
265    /**
266     * @return the url
267     */
268    public String getUrl() {
269        return url;
270    }
271
272    /**
273     * @param url the url to set
274     */
275    public void setUrl(String url) {
276        this.url = url;
277    }
278
279    /**
280     * @param usesProxy the usesProxy to set
281     */
282    public void setUsesProxy(boolean usesProxy) {
283        this.usesProxy = usesProxy;
284    }
285
286    /**
287     * @param urlProxy the urlProxy to set
288     */
289    public void setUrlProxy(String urlProxy) {
290        this.urlProxy = urlProxy;
291    }
292
293    /**
294     * @param portProxy the portProxy to set
295     */
296    public void setPortProxy(int portProxy) {
297        this.portProxy = portProxy;
298    }
299
300    /**
301     * @param loginProxy the loginProxy to set
302     */
303    public void setLoginProxy(String loginProxy) {
304        this.loginProxy = loginProxy;
305    }
306
307    /**
308     * @param passProxy the passProxy to set
309     */
310    public void setPassProxy(String passProxy) {
311        this.passProxy = passProxy;
312    }
313
314    /**
315     * @return the erreurProxy
316     */
317    public boolean isErreurProxy() {
318        return erreurProxy;
319    }
320
321}
Note: See TracBrowser for help on using the repository browser.