source: extensions/jiwigo/trunk/src/main/java/fr/mael/jiwigo/transverse/session/SessionManager.java @ 8838

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

Images can be sent from the file new file browser.

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