KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > clif > isac > plugins > httpinjector10 > actions > HttpInjectorSamples


1 /*
2  * CLIF is a Load Injection Framework
3  * Copyright (C) 2004 France Telecom R&D
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18  *
19  * CLIF
20  *
21  * Contact: clif@objectweb.org
22  */

23 package org.objectweb.clif.isac.plugins.httpinjector10.actions;
24
25 import java.io.File JavaDoc;
26 import java.io.FileInputStream JavaDoc;
27 import java.io.FileNotFoundException JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.net.MalformedURLException JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.Hashtable JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34 import org.htmlparser.Parser;
35 import org.htmlparser.Node;
36 import org.htmlparser.tags.ImageTag;
37 import org.htmlparser.tags.FrameTag;
38 import org.htmlparser.util.ParserException;
39 import org.apache.commons.httpclient.Header;
40 import org.apache.commons.httpclient.HttpMethod;
41 import org.apache.commons.httpclient.HttpRecoverableException;
42 import org.apache.commons.httpclient.NameValuePair;
43 import org.apache.commons.httpclient.UsernamePasswordCredentials;
44 import org.apache.commons.httpclient.URI;
45 import org.apache.commons.httpclient.methods.DeleteMethod;
46 import org.apache.commons.httpclient.methods.GetMethod;
47 import org.apache.commons.httpclient.methods.HeadMethod;
48 import org.apache.commons.httpclient.methods.MultipartPostMethod;
49 import org.apache.commons.httpclient.methods.OptionsMethod;
50 import org.apache.commons.httpclient.methods.PostMethod;
51 import org.apache.commons.httpclient.methods.PutMethod;
52 import org.objectweb.clif.isac.plugins.httpinjector10.SessionObject;
53 import org.objectweb.clif.isac.plugins.httpinjector10.tools.HostConfigurationUtils;
54 import org.objectweb.clif.isac.plugins.httpinjector10.tools.HttpStateUtils;
55 import org.objectweb.clif.isac.plugins.httpinjector10.tools.ParametersConstantes;
56 import org.objectweb.clif.scenario.util.isac.engine.IsacScenarioEngine;
57 import org.objectweb.clif.storage.api.ActionEvent;
58 import org.objectweb.clif.util.ClifClassLoader;
59 import org.objectweb.util.monolog.api.BasicLevel;
60 import org.objectweb.util.monolog.api.Logger;
61
62
63 /**
64  * This class implements the HttpInjector sample methods
65  *
66  * @author JC Meillaud
67  * @author A Peyrard
68  */

69 public class HttpInjectorSamples {
70
71     // logger
72
static protected Logger log = IsacScenarioEngine.logger
73             .getLogger(HttpInjectorSamples.class.getName());
74     static protected Logger urlLog = IsacScenarioEngine.logger
75             .getLogger(HttpInjectorSamples.class.getName() + ".urls");
76
77     public static final int MAXATTEMPT = 3;
78
79     private static final int ERRORSTATUSCODE = -1;
80
81     private static final String JavaDoc NULL = "null";
82
83     private static final String JavaDoc MALFORMEDURI = "Malformed URI =";
84     private static final String JavaDoc UNDEFINEDURI = "Undefined URI";
85
86     private static final String JavaDoc HTTP = "http:";
87     private static final String JavaDoc HTTPS = "https";
88     private static final String JavaDoc DEFAULTPROTOCOL = "http://";
89
90     static public final String JavaDoc TYPE_GET = "HTTP Get";
91     static public final String JavaDoc TYPE_POST = "HTTP Post";
92     static public final String JavaDoc TYPE_MULTIPOST = "HTTP Multiple Post";
93     static public final String JavaDoc TYPE_HEAD = "HTTP Head";
94     static public final String JavaDoc TYPE_OPTIONS = "HTTP Options";
95     static public final String JavaDoc TYPE_PUT = "HTTP Put";
96     static public final String JavaDoc TYPE_DELETE = "HTTP Delete";
97
98
99     /**
100      * doGet Method : The GET method means retrieve whatever information is
101      * identified by the requested URL. Also refer to the tutorial .
102      *
103      * @param sessionObject
104      * The sessionObject who's handle the httpClient
105      * @param report
106      * The ActionReport to update
107      * @param params
108      * An Hashtable containing all the useful variable
109      * @return the ActionReport updated
110      */

111     public static ActionEvent doGet(SessionObject sessionObject,
112             ActionEvent report, Hashtable JavaDoc params) {
113         log.log(BasicLevel.DEBUG, "-> [Enter] doGet");
114         report.type = TYPE_GET;
115         if (params.containsKey(ParametersConstantes.URI)) {
116             String JavaDoc uri = completeUri((String JavaDoc) params
117                     .get(ParametersConstantes.URI), params);
118
119             String JavaDoc parameters = (String JavaDoc) params
120                     .get(ParametersConstantes.PARAMETERS);
121             String JavaDoc redirect = (String JavaDoc) params
122                     .get(ParametersConstantes.REDIRECT);
123             log.log(BasicLevel.DEBUG, "[url=" + uri + ";parameters=["
124                     + parameters + "];redirect=" + redirect + "]");
125             GetMethod method = new GetMethod(uri);
126             //method.setDoAuthentication();
127
if (parameters != null && !parameters.equals("")) {
128                 Hashtable JavaDoc InputsParameters = setInputParameters(params.get(
129                         ParametersConstantes.PARAMETERS).toString());
130                 method.setQueryString(buildQueryString(InputsParameters, sessionObject));
131             }
132             sessionObject.getHttpClient().setState(
133                     HttpStateUtils.setHttpState(sessionObject, params));
134             if (params.containsKey(ParametersConstantes.USERNAME)
135                     && params.containsKey(ParametersConstantes.PASSWORD)) {
136                 setCredentials(sessionObject, params);
137             }
138             method.setStrictMode(false);
139             try {
140                 // set the HostConfiguration
141
sessionObject.getHttpClient().setHostConfiguration(
142                         HostConfigurationUtils.setHostConfiguration(
143                                 sessionObject, params));
144                 report.setDate(System.currentTimeMillis());
145                 if (redirect != null) {
146                     if (redirect.equals(ParametersConstantes.ENABLED)) {
147
148                         log.log(BasicLevel.DEBUG, "set FollowRedirect ON");
149                         method.setFollowRedirects(true);
150                     } else {
151                         log.log(BasicLevel.DEBUG, "set FollowRedirect OFF");
152                         method.setFollowRedirects(false);
153                     }
154                 }
155                 //execute the method
156
executeMethod(sessionObject, report, method);
157                 report.comment = uri;
158             } catch (MalformedURLException JavaDoc e) {
159                 report.comment = MALFORMEDURI + uri;
160                 report.successful = false;
161                 log.log(BasicLevel.DEBUG, MALFORMEDURI + uri);
162             }
163         } else {
164             report.comment = UNDEFINEDURI;
165             report.successful = false;
166             log.log(BasicLevel.DEBUG, UNDEFINEDURI);
167         }
168         log.log(BasicLevel.DEBUG, "<- [Exit] doGet\n");
169         return report;
170     }
171
172     /**
173      * doPost Method : The POST method is used to request that the origin server
174      * accept the data enclosed in the request as a new child of the request
175      * URL. POST is designed to allow a uniform method to cover a variety of
176      * functions such as appending to a database, providing data to a
177      * data-handling process or posting to a message board.
178      *
179      * @param sessionObject
180      * The sessionObject who's handle the httpClient
181      * @param report
182      * The ActionReport to update
183      * @param params
184      * An Hashtable containing all the useful variable
185      * @return the ActionReport updated
186      */

187     public static ActionEvent doPost(SessionObject sessionObject,
188             ActionEvent report, Hashtable JavaDoc params) {
189         log.log(BasicLevel.DEBUG, "-> [Enter] doPost");
190         report.type = TYPE_POST;
191         if (params.containsKey(ParametersConstantes.URI)) {
192             String JavaDoc uri = completeUri((String JavaDoc) params
193                     .get(ParametersConstantes.URI), params);
194             String JavaDoc parameters = (String JavaDoc) params
195                     .get(ParametersConstantes.PARAMETERS);
196             String JavaDoc redirect = (String JavaDoc) params
197                     .get(ParametersConstantes.REDIRECT);
198             String JavaDoc file = (String JavaDoc) params.get(ParametersConstantes.FILE);
199             log.log(BasicLevel.DEBUG, "[url=" + uri + ";parameters=["
200                     + parameters + "];redirect=" + redirect + "]");
201             // the Post method
202
PostMethod method = new PostMethod(uri);
203             if (file != null && !file.equals("")) {
204                 InputStream JavaDoc fileInputStream = ClifClassLoader.getClassLoader().getResourceAsStream(file);
205                 if (fileInputStream != null) {
206                     method.setRequestBody(fileInputStream);
207                 }
208                 String JavaDoc fileType = (String JavaDoc) params
209                         .get(ParametersConstantes.FILETYPE);
210                 if (fileType != null && !fileType.equals("")) {
211                     method.setRequestHeader(ParametersConstantes.CONTENTTYPE,
212                             fileType);
213                 }
214             }
215
216             if (parameters != null && !parameters.equals("")) {
217                 Hashtable JavaDoc InputsParameters = setInputParameters(parameters);
218                 method.setRequestBody(buildQueryString(InputsParameters,sessionObject));
219             }
220             // set the HttpState
221
sessionObject.getHttpClient().setState(
222                     HttpStateUtils.setHttpState(sessionObject, params));
223             if (params.containsKey(ParametersConstantes.USERNAME)
224                     && params.containsKey(ParametersConstantes.PASSWORD)) {
225                 setCredentials(sessionObject, params);
226             }
227             method.setStrictMode(false);
228             try {
229                 // set the HostConfiguration
230
sessionObject.getHttpClient().setHostConfiguration(
231                         HostConfigurationUtils.setHostConfiguration(
232                                 sessionObject, params));
233                 if (redirect != null) {
234                     if (redirect.equals(ParametersConstantes.ENABLED)) {
235
236                         log.log(BasicLevel.DEBUG, "set FollowRedirect ON");
237                         method.setFollowRedirects(true);
238                     } else {
239                         log.log(BasicLevel.DEBUG, "set FollowRedirect OFF");
240                         method.setFollowRedirects(false);
241                     }
242                 }
243                 report.setDate(System.currentTimeMillis());
244                 // execute the method
245
executeMethod(sessionObject, report, method);
246                 report.comment = uri;
247             } catch (MalformedURLException JavaDoc e) {
248                 report.comment = MALFORMEDURI + uri;
249                 report.successful = false;
250                 log.log(BasicLevel.DEBUG, MALFORMEDURI + uri);
251             }
252         } else {
253             report.comment = UNDEFINEDURI;
254             report.successful = false;
255             log.log(BasicLevel.DEBUG, UNDEFINEDURI);
256         }
257         log.log(BasicLevel.DEBUG, "<- [Exit] doPost\n");
258         return report;
259
260     }
261
262     /**
263      * doMultiPost Method : The multipart post method is identical to the POST
264      * method, except that the request body is separated into multiple parts.
265      * This method is generally used when uploading files to the server.
266      *
267      * @param sessionObject
268      * The sessionObject who's handle the httpClient
269      * @param report
270      * The ActionReport to update
271      * @param params
272      * An Hashtable containing all the useful variable
273      * @return the ActionReport updated
274      */

275     public static ActionEvent doMultiPost(SessionObject sessionObject,
276             ActionEvent report, Hashtable JavaDoc params) {
277         log.log(BasicLevel.DEBUG, "-> [Enter] doMultiPost\n");
278         report.type = TYPE_MULTIPOST;
279         if (params.containsKey(ParametersConstantes.URI)) {
280             String JavaDoc uri = completeUri((String JavaDoc) params
281                     .get(ParametersConstantes.URI), params);
282             String JavaDoc parameters = (String JavaDoc) params
283                     .get(ParametersConstantes.PARAMETERS);
284             String JavaDoc redirect = (String JavaDoc) params
285                     .get(ParametersConstantes.REDIRECT);
286             String JavaDoc files = (String JavaDoc) params.get(ParametersConstantes.FILES);
287             log.log(BasicLevel.DEBUG, "[url=" + uri + ";parameters=["
288                     + parameters + "];redirect=" + redirect + "]");
289             MultipartPostMethod method = new MultipartPostMethod(uri);
290             if (files != null && !files.equals("")) {
291                 StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(files, ";");
292                 while (st.hasMoreTokens()) {
293                     String JavaDoc file = st.nextToken();
294                     File JavaDoc f = new File JavaDoc(file);
295                     try {
296                         method.addParameter(f.getName(), f);
297                     } catch (FileNotFoundException JavaDoc e) {
298                         e.printStackTrace();
299                     }
300                 }
301             }
302
303             if (parameters != null && !parameters.equals("")) {
304                 Hashtable JavaDoc InputsParameters = setInputParameters(parameters);
305                 method.setQueryString(buildQueryString(InputsParameters,sessionObject));
306             }
307             // set the HttpState
308
sessionObject.getHttpClient().setState(
309                     HttpStateUtils.setHttpState(sessionObject, params));
310             if (params.containsKey(ParametersConstantes.USERNAME)
311                     && params.containsKey(ParametersConstantes.PASSWORD)) {
312                 setCredentials(sessionObject, params);
313             }
314             method.setStrictMode(false);
315
316             try {
317                 // set the HostConfiguration
318
sessionObject.getHttpClient().setHostConfiguration(
319                         HostConfigurationUtils.setHostConfiguration(
320                                 sessionObject, params));
321                 if (redirect != null) {
322                     if (redirect.equals(ParametersConstantes.ENABLED)) {
323
324                         log.log(BasicLevel.DEBUG, "set FollowRedirect ON");
325                         method.setFollowRedirects(true);
326                     } else {
327                         log.log(BasicLevel.DEBUG, "set FollowRedirect OFF");
328                         method.setFollowRedirects(false);
329                     }
330                 }
331                 report.setDate(System.currentTimeMillis());
332                 // execute the method
333
executeMethod(sessionObject, report, method);
334                 report.comment = uri;
335             } catch (MalformedURLException JavaDoc e) {
336                 report.comment = MALFORMEDURI + uri;
337                 report.successful = false;
338                 log.log(BasicLevel.DEBUG, MALFORMEDURI + uri);
339             }
340             log.log(BasicLevel.DEBUG, "<- [Exit] doMultiPost\n");
341         } else {
342             report.comment = UNDEFINEDURI;
343             report.successful = false;
344             log.log(BasicLevel.DEBUG, UNDEFINEDURI);
345         }
346         return report;
347
348     }
349
350     /**
351      * doHead Method : The HEAD method is identical to GET except that the
352      * server must not return a message-body in the response. This method can be
353      * used for obtaining metainformation about the document implied by the
354      * request without transferring the document itself.
355      *
356      * @param sessionObject
357      * The sessionObject who's handle the httpClient
358      * @param report
359      * The ActionReport to update
360      * @param params
361      * An Hashtable containing all the useful variable
362      * @return the ActionReport updated
363      */

364     public static ActionEvent doHead(SessionObject sessionObject,
365             ActionEvent report, Hashtable JavaDoc params) {
366         log.log(BasicLevel.DEBUG, "-> [Enter] doHead");
367         report.type = TYPE_HEAD;
368         if (params.containsKey(ParametersConstantes.URI)) {
369             String JavaDoc uri = completeUri((String JavaDoc) params
370                     .get(ParametersConstantes.URI), params);
371             String JavaDoc parameters = (String JavaDoc) params
372                     .get(ParametersConstantes.PARAMETERS);
373             String JavaDoc redirect = (String JavaDoc) params
374                     .get(ParametersConstantes.REDIRECT);
375             log.log(BasicLevel.DEBUG, "[url=" + uri + ";parameters=["
376                     + parameters + "];redirect=" + redirect + "]");
377             // the Post method
378
HeadMethod method = new HeadMethod(uri);
379
380             if (parameters != null && !parameters.equals("")) {
381                 Hashtable JavaDoc InputsParameters = setInputParameters(parameters);
382                 method.setQueryString(buildQueryString(InputsParameters,sessionObject));
383             }
384             // set the HttpState
385
sessionObject.getHttpClient().setState(
386                     HttpStateUtils.setHttpState(sessionObject, params));
387             if (params.containsKey(ParametersConstantes.USERNAME)
388                     && params.containsKey(ParametersConstantes.PASSWORD)) {
389                 setCredentials(sessionObject, params);
390             }
391             method.setStrictMode(false);
392
393             try {
394                 // set the HostConfiguration
395
sessionObject.getHttpClient().setHostConfiguration(
396                         HostConfigurationUtils.setHostConfiguration(
397                                 sessionObject, params));
398                 if (redirect != null) {
399                     if (redirect.equals(ParametersConstantes.ENABLED)) {
400
401                         log.log(BasicLevel.DEBUG, "set FollowRedirect ON");
402                         method.setFollowRedirects(true);
403                     } else {
404                         log.log(BasicLevel.DEBUG, "set FollowRedirect OFF");
405                         method.setFollowRedirects(false);
406                     }
407                 }
408                 report.setDate(System.currentTimeMillis());
409                 // execute the method
410
executeMethod(sessionObject, report, method);
411                 report.comment = uri;
412             } catch (MalformedURLException JavaDoc e) {
413                 report.comment = MALFORMEDURI + uri;
414                 report.successful = false;
415                 log.log(BasicLevel.DEBUG, MALFORMEDURI + uri);
416             }
417             log.log(BasicLevel.DEBUG, "<- [Exit] doHead\n");
418         } else {
419             report.comment = UNDEFINEDURI;
420             report.successful = false;
421             log.log(BasicLevel.DEBUG, UNDEFINEDURI);
422         }
423         return report;
424
425     }
426
427     /**
428      * doOptions Method : The OPTIONS method represents a request for
429      * information about the communication options available.
430      *
431      * @param sessionObject
432      * The sessionObject who's handle the httpClient
433      * @param report
434      * The ActionReport to update
435      * @param params
436      * An Hashtable containing all the useful variable
437      * @return the ActionReport updated
438      */

439     public static ActionEvent doOptions(SessionObject sessionObject,
440             ActionEvent report, Hashtable JavaDoc params) {
441         log.log(BasicLevel.DEBUG, "-> [Enter] doOptions");
442         report.type = TYPE_OPTIONS;
443         if (params.containsKey(ParametersConstantes.URI)) {
444             String JavaDoc uri = completeUri((String JavaDoc) params
445                     .get(ParametersConstantes.URI), params);
446             String JavaDoc parameters = (String JavaDoc) params
447                     .get(ParametersConstantes.PARAMETERS);
448             String JavaDoc redirect = (String JavaDoc) params
449                     .get(ParametersConstantes.REDIRECT);
450             log.log(BasicLevel.DEBUG, "[url=" + uri + ";parameters=["
451                     + parameters + "];redirect=" + redirect + "]");
452             // the Post method
453
OptionsMethod method = new OptionsMethod(uri);
454
455             if (parameters != null && !parameters.equals("")) {
456                 Hashtable JavaDoc InputsParameters = setInputParameters(parameters);
457                 method.setQueryString(buildQueryString(InputsParameters,sessionObject));
458             }
459             // set the HttpState
460
sessionObject.getHttpClient().setState(
461                     HttpStateUtils.setHttpState(sessionObject, params));
462             if (params.containsKey(ParametersConstantes.USERNAME)
463                     && params.containsKey(ParametersConstantes.PASSWORD)) {
464                 setCredentials(sessionObject, params);
465             }
466             method.setStrictMode(false);
467
468             try {
469                 // set the HostConfiguration
470
sessionObject.getHttpClient().setHostConfiguration(
471                         HostConfigurationUtils.setHostConfiguration(
472                                 sessionObject, params));
473                 if (redirect != null) {
474                     if (redirect.equals(ParametersConstantes.ENABLED)) {
475
476                         log.log(BasicLevel.DEBUG, "set FollowRedirect ON");
477                         method.setFollowRedirects(true);
478                     } else {
479                         log.log(BasicLevel.DEBUG, "set FollowRedirect OFF");
480                         method.setFollowRedirects(false);
481                     }
482                 }
483                 report.setDate(System.currentTimeMillis());
484                 // execute the method
485
executeMethod(sessionObject, report, method);
486                 report.comment = uri;
487             } catch (MalformedURLException JavaDoc e) {
488                 report.comment = MALFORMEDURI + uri;
489                 report.successful = false;
490                 log.log(BasicLevel.DEBUG, MALFORMEDURI + uri);
491             }
492         } else {
493             report.comment = UNDEFINEDURI;
494             report.successful = false;
495             log.log(BasicLevel.DEBUG, UNDEFINEDURI);
496         }
497         log.log(BasicLevel.DEBUG, "<- [Exit] doOptions\n");
498
499         return report;
500
501     }
502
503     /**
504      * doPut Method : The PUT method requests that the enclosed document be
505      * stored under the supplied URL. This method is generally disabled on
506      * publicly available servers because it is generally undesireable to allow
507      * clients to put new files on the server or to replace existing files.
508      *
509      * @param sessionObject
510      * The sessionObject who's handle the httpClient
511      * @param report
512      * The ActionReport to update
513      * @param params
514      * An Hashtable containing all the useful variable
515      * @return the ActionReport updated
516      */

517     public static ActionEvent doPut(SessionObject sessionObject,
518             ActionEvent report, Hashtable JavaDoc params) {
519         log.log(BasicLevel.DEBUG, "-> [Enter] doPut");
520         report.type = TYPE_PUT;
521         if (params.containsKey(ParametersConstantes.URI)) {
522             String JavaDoc uri = completeUri((String JavaDoc) params
523                     .get(ParametersConstantes.URI), params);
524             String JavaDoc parameters = (String JavaDoc) params
525                     .get(ParametersConstantes.PARAMETERS);
526             String JavaDoc redirect = (String JavaDoc) params
527                     .get(ParametersConstantes.REDIRECT);
528             String JavaDoc file = (String JavaDoc) params.get(ParametersConstantes.FILE);
529             log.log(BasicLevel.DEBUG, "[url=" + uri + ";parameters=["
530                     + parameters + "];redirect=" + redirect + "]");
531             PutMethod method = new PutMethod(uri);
532             if (file != null && !file.equals("")) {
533                 FileInputStream JavaDoc fileInputStream =
534                     (FileInputStream JavaDoc) (ClifClassLoader.getClassLoader().getResourceAsStream(file));
535                 if (fileInputStream != null) {
536                     method.setRequestBody(fileInputStream);
537                 }
538                 String JavaDoc fileType = (String JavaDoc) params
539                         .get(ParametersConstantes.FILETYPE);
540                 if (fileType != null && !fileType.equals("")) {
541                     method.setRequestHeader(ParametersConstantes.CONTENTTYPE,
542                             fileType);
543                 }
544             }
545             //method.setDoAuthentication();
546
if (parameters != null && !parameters.equals("")) {
547                 Hashtable JavaDoc InputsParameters = setInputParameters(params.get(
548                         ParametersConstantes.PARAMETERS).toString());
549                 method.setQueryString(buildQueryString(InputsParameters,sessionObject));
550             }
551             sessionObject.getHttpClient().setState(
552                     HttpStateUtils.setHttpState(sessionObject, params));
553             if (params.containsKey(ParametersConstantes.USERNAME)
554                     && params.containsKey(ParametersConstantes.PASSWORD)) {
555                 setCredentials(sessionObject, params);
556             }
557             method.setStrictMode(false);
558
559             try {
560                 // set the HostConfiguration
561
sessionObject.getHttpClient().setHostConfiguration(
562                         HostConfigurationUtils.setHostConfiguration(
563                                 sessionObject, params));
564                 if (redirect != null) {
565                     if (redirect.equals(ParametersConstantes.ENABLED)) {
566
567                         log.log(BasicLevel.DEBUG, "set FollowRedirect ON");
568                         method.setFollowRedirects(true);
569                     } else {
570                         log.log(BasicLevel.DEBUG, "set FollowRedirect OFF");
571                         method.setFollowRedirects(false);
572                     }
573                 }
574                 report.setDate(System.currentTimeMillis());
575                 // execute the method
576
executeMethod(sessionObject, report, method);
577                 report.comment = uri;
578             } catch (MalformedURLException JavaDoc e) {
579                 report.comment = MALFORMEDURI + uri;
580                 report.successful = false;
581                 log.log(BasicLevel.DEBUG, MALFORMEDURI + uri);
582             }
583         } else {
584             report.comment = UNDEFINEDURI;
585             report.successful = false;
586             log.log(BasicLevel.DEBUG, UNDEFINEDURI);
587         }
588         log.log(BasicLevel.DEBUG, "<- [Exit] doPut\n");
589         return report;
590     }
591
592     /**
593      * doDelete Method : The DELETE method requests that the server delete the
594      * resource identified by the request URL. This method is generally disabled
595      * on publicly available servers because it is generally undesireable to
596      * allow clients to delete files on the server.
597      *
598      * @param sessionObject
599      * The sessionObject who's handle the httpClient
600      * @param report
601      * The ActionReport to update
602      * @param params
603      * An Hashtable containing all the useful variable
604      * @return the ActionReport updated
605      */

606     public static ActionEvent doDelete(SessionObject sessionObject,
607             ActionEvent report, Hashtable JavaDoc params) {
608         log.log(BasicLevel.DEBUG, "-> [Enter] doDelete");
609         report.type = TYPE_DELETE;
610         if (params.containsKey(ParametersConstantes.URI)) {
611             String JavaDoc uri = completeUri((String JavaDoc) params
612                     .get(ParametersConstantes.URI), params);
613             String JavaDoc parameters = (String JavaDoc) params
614                     .get(ParametersConstantes.PARAMETERS);
615             String JavaDoc redirect = (String JavaDoc) params
616                     .get(ParametersConstantes.REDIRECT);
617             log.log(BasicLevel.DEBUG, "[url=" + uri + ";parameters=["
618                     + parameters + "];redirect=" + redirect + "]");
619             DeleteMethod method = new DeleteMethod(uri);
620             //method.setDoAuthentication();
621
if (parameters != null && !parameters.equals("")) {
622                 Hashtable JavaDoc InputsParameters = setInputParameters(params.get(
623                         ParametersConstantes.PARAMETERS).toString());
624                 method.setQueryString(buildQueryString(InputsParameters,sessionObject));
625             }
626             sessionObject.getHttpClient().setState(
627                     HttpStateUtils.setHttpState(sessionObject, params));
628             if (params.containsKey(ParametersConstantes.USERNAME)
629                     && params.containsKey(ParametersConstantes.PASSWORD)) {
630                 setCredentials(sessionObject, params);
631             }
632             method.setStrictMode(false);
633
634             try {
635                 // set the HostConfiguration
636
sessionObject.getHttpClient().setHostConfiguration(
637                         HostConfigurationUtils.setHostConfiguration(
638                                 sessionObject, params));
639                 if (redirect != null) {
640                     if (redirect.equals(ParametersConstantes.ENABLED)) {
641
642                         log.log(BasicLevel.DEBUG, "set FollowRedirect ON");
643                         method.setFollowRedirects(true);
644                     } else {
645                         log.log(BasicLevel.DEBUG, "set FollowRedirect OFF");
646                         method.setFollowRedirects(false);
647                     }
648                 }
649                 report.setDate(System.currentTimeMillis());
650                 // execute the method
651
executeMethod(sessionObject, report, method);
652                 report.comment = uri;
653             } catch (MalformedURLException JavaDoc e) {
654                 report.comment = MALFORMEDURI + uri;
655                 report.successful = false;
656                 log.log(BasicLevel.DEBUG, MALFORMEDURI + uri);
657             }
658         } else {
659             report.comment = UNDEFINEDURI;
660             report.successful = false;
661             log.log(BasicLevel.DEBUG, UNDEFINEDURI);
662         }
663         log.log(BasicLevel.DEBUG, "<- [Exit] doDelete\n");
664         return report;
665     }
666
667     /**
668      * Method which execute a previously initialised HttpMethod
669      *
670      * @param sessionObject
671      * The sessionObject who's handle the httpClient
672      * @param report
673      * The ActionReport to update
674      * @param httpMethod
675      * the HttpMethod to execute
676      */

677     private static void executeMethod(
678         SessionObject sessionObject,
679         ActionEvent report,
680         HttpMethod httpMethod)
681     {
682         //execute the method
683
Header[] headers = null;
684         String JavaDoc responseBody = null;
685         int statusCode = ERRORSTATUSCODE;
686         report.setDate(System.currentTimeMillis());
687         for (
688             int attempt = 0 ;
689             statusCode == ERRORSTATUSCODE && attempt < MAXATTEMPT ;
690             attempt++)
691         {
692             try
693             {
694                 //httpMethod.setFollowRedirects(true);
695

696                 statusCode = sessionObject.getHttpClient().executeMethod(
697                         httpMethod);
698
699                 // XXX DEBUG
700
// String redirectLocation=null;
701
// Header locationHeader =
702
// httpMethod.getResponseHeader("location");
703
// if (locationHeader != null) {
704
// redirectLocation = locationHeader.getValue();
705
// }
706
// System.out.println("YEAH" + redirectLocation);
707
// httpMethod.setPath(redirectLocation);
708
// System.out.println("YEAH" + redirectLocation);
709
// statusCode = sessionObject.getHttpClient().executeMethod(
710
// httpMethod);
711
// System.out.println("YEAH" + redirectLocation);
712

713                 responseBody = httpMethod.getResponseBodyAsString();
714                 //Header location = httpMethod.getResponseHeader("location");
715
urlLog.log(BasicLevel.INFO, httpMethod.getURI());
716                 // if (location != null) {
717
// System.out.println("location : "+location.getValue());
718
// } else {
719
// System.out.println("no location");
720
//}
721
headers = httpMethod.getResponseHeaders();
722                 log.log(
723                     BasicLevel.DEBUG,
724                     "Status Code: " + statusCode + "\nResponse Body:\n" + responseBody);
725                 report.successful = true;
726                 report.duration = (int) (System.currentTimeMillis() - report.getDate());
727                 report.duration += inDepthLoad(
728                     sessionObject,
729                     responseBody,
730                     httpMethod.getURI());
731             }
732             catch (HttpRecoverableException e)
733             {
734                 log.log(BasicLevel.WARN, e);
735                 report.successful = false;
736             }
737             catch (IOException JavaDoc e)
738             {
739                 log.log(BasicLevel.WARN, e);
740                 report.successful = false;
741             }
742             finally
743             {
744                 httpMethod.releaseConnection();
745             }
746         }
747         // save some info
748
if (statusCode != ERRORSTATUSCODE)
749         {
750             sessionObject.setLastStatusCode(statusCode);
751             sessionObject.setLastHeader(headers);
752             sessionObject.setLastResponseBody(responseBody);
753         }
754         else
755         {
756             sessionObject.setLastStatusCode(ERRORSTATUSCODE);
757             sessionObject.setLastHeader(null);
758             sessionObject.setLastResponseBody(null);
759         }
760         report.result = statusCode + " - " + httpMethod.getStatusText();
761     }
762
763     /**
764      * Function to set the Credentials for a particular host and realm
765      *
766      * @param sessionObject
767      * The sessionObject
768      * @param params
769      * Hashtable containing all the variable
770      */

771     private static void setCredentials(SessionObject sessionObject,
772             Hashtable JavaDoc params) {
773         log.log(BasicLevel.DEBUG, "-> [Enter] setCredentials");
774         // the hostAuth and realm values can be set to null
775
String JavaDoc hostAuth = (String JavaDoc) params.get(ParametersConstantes.HOSTAUTH);
776         hostAuth = (hostAuth != null && hostAuth.equals(NULL))
777                 ? null
778                 : hostAuth;
779         String JavaDoc realm = (String JavaDoc) params.get(ParametersConstantes.REALM);
780         realm = (realm != null && realm.equals(NULL)) ? null : realm;
781         String JavaDoc userName = (String JavaDoc) params.get(ParametersConstantes.USERNAME);
782         String JavaDoc password = (String JavaDoc) params.get(ParametersConstantes.PASSWORD);
783         if (userName != null && !userName.equals("")) {
784
785             sessionObject.getHttpClient().getState().setCredentials(realm,
786                     hostAuth,
787                     new UsernamePasswordCredentials(userName, password));
788
789         } else {
790             //maybe check if there is default credentials
791
}
792         log.log(BasicLevel.DEBUG, "<- [Exit] setCredentials");
793     }
794
795     /**
796      * Function to deserialize a String onto a Hashtable
797      *
798      * @param inputParameters
799      * The serialized String which defines the input
800      * @return the Hashtable of the deserialized variables
801      */

802     private static Hashtable JavaDoc setInputParameters(String JavaDoc inputParameters) {
803         log.log(BasicLevel.DEBUG, "-> [Enter] setInputParameter");
804         Hashtable JavaDoc result = new Hashtable JavaDoc();
805         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(inputParameters, ";");
806         while (st.hasMoreTokens()) {
807             String JavaDoc inputParameter = st.nextToken();
808             log.log(BasicLevel.DEBUG, "element : " + inputParameter);
809             StringTokenizer JavaDoc st2 = new StringTokenizer JavaDoc(inputParameter, "=");
810             if (st2.countTokens() == 2) {
811                 String JavaDoc inputParamName = st2.nextToken();
812                 String JavaDoc inputParamValue = st2.nextToken();
813                 log.log(BasicLevel.DEBUG, "inputParamName : [" + inputParamName
814                         + "] ;inputParamValue : [" + inputParamValue + "]");
815                 if (!inputParamName.equals("") && !inputParamValue.equals(""))
816                     result.put(inputParamName, inputParamValue);
817             } else if (st2.countTokens() == 1) {
818                 String JavaDoc inputParamName = st2.nextToken();
819                 log.log(BasicLevel.DEBUG, "inputParamName : [" + inputParamName
820                         + "] ;inputParamValue : [vide]");
821                 if (!inputParamName.equals(""))
822                     result.put(inputParamName, "");
823             }
824         }
825         log.log(BasicLevel.DEBUG, "<- [Exit] setInputParameter");
826         return result;
827     }
828
829     // private static String buildGetRequest(Hashtable inputParameters) {
830
// log.log(BasicLevel.DEBUG, "-> [Enter] buildGetRequest");
831
// String result = "";
832
// Enumeration e = inputParameters.elements();
833
// while (e.hasMoreElements()) {
834
// String elem = e.nextElement().toString();
835
// result.concat(elem + "=" + inputParameters.get(elem));
836
// if (e.hasMoreElements()) {
837
// result.concat(ParametersConstantes.SEPARATOR);
838
// }
839
// }
840
// log.log(BasicLevel.DEBUG, "<- [Exit] buildGetRequest");
841
// return result;
842
// }
843

844     /**
845      * Method to build an array of name/value pairs and then return this array,
846      * that will be set into the query string
847      *
848      * @param inputParameters
849      * a Hashtable containing all the parameters
850      * @return An array of name/value paris
851      */

852     private static NameValuePair[] buildQueryString(Hashtable JavaDoc inputParameters, SessionObject so) {
853         log.log(BasicLevel.DEBUG, "-> [Enter] buildQueryString");
854         int size = inputParameters.keySet().size();
855         NameValuePair[] data = new NameValuePair[size];
856         Enumeration JavaDoc e = inputParameters.keys();
857         int i = 0;
858
859         while (e.hasMoreElements()) {
860             String JavaDoc elem = e.nextElement().toString();
861             // XXX Presentation
862
NameValuePair nameValuePair = null ;
863             if (inputParameters.get(elem).toString().equals("$USERNAME")) {
864                 nameValuePair = new NameValuePair(elem,so.getUserName());
865             }
866             else {
867                 nameValuePair = new NameValuePair(elem,
868                                 inputParameters.get(elem).toString());
869             }
870             log.log(BasicLevel.DEBUG, "Input Parameter n°" + i + " :"
871                     + nameValuePair);
872             data[i] = nameValuePair;
873             i++;
874         }
875         log.log(BasicLevel.DEBUG, "<- [Exit] buildQueryString : " + data);
876         return data;
877     }
878
879
880     private static String JavaDoc completeUri(String JavaDoc uri, Hashtable JavaDoc params) {
881         String JavaDoc scheme = uri.substring(0, 5);
882         if (!scheme.equals(HTTP) && !scheme.equals(HTTPS)) {
883             uri = DEFAULTPROTOCOL + uri;
884             log.log(BasicLevel.DEBUG,
885                     "There is no Protocol defined, trying with default HTTP on the host : "
886                             + uri);
887             //update the good value in the params Hashtable
888
params.put(ParametersConstantes.URI, uri);
889         }
890         return uri;
891     }
892
893
894     /**
895      * Loads frames (recursively) and images included in a given HTML body
896      * @param session the session object
897      * @param body the HTML text
898      * @param baseURI the URI of this HTML text (necessary to resolve relative pathes)
899      */

900     static private long inDepthLoad(SessionObject session, String JavaDoc body, URI baseURI)
901         throws IOException JavaDoc
902     {
903         long duration;
904         boolean isFrameSet = true;
905         try
906         {
907             Parser parser = Parser.createParser(body);
908             Node[] nodes = parser.extractAllNodesThatAre(FrameTag.class);
909             if (nodes.length == 0)
910             {
911                 isFrameSet = false;
912                 parser.reset();
913                 nodes = parser.extractAllNodesThatAre(ImageTag.class);
914             }
915             GetMethod[] gets = new GetMethod[nodes.length];
916             String JavaDoc rootPath = baseURI.getPath().substring(
917                 0,
918                 1 + baseURI.getPath().lastIndexOf('/'));
919             for (int i=0 ; i<nodes.length ; ++i)
920             {
921                 String JavaDoc path;
922                 if (isFrameSet)
923                 {
924                     path = ((FrameTag)nodes[i]).getFrameLocation();
925                 }
926                 else
927                 {
928                     path = ((ImageTag)nodes[i]).extractImageLocn();
929                 }
930                 if (path.startsWith("http:")
931                     || path.startsWith("https:")
932                     || path.startsWith("ftp:")
933                     || path.startsWith("file:"))
934                 {
935                     gets[i] = new GetMethod(path);
936                 }
937                 else
938                 {
939                     gets[i] = new GetMethod(baseURI.toString());
940                     if (path.startsWith("/"))
941                     {
942                         gets[i].setPath(path);
943                     }
944                     else
945                     {
946                         gets[i].setPath(rootPath + path);
947                     }
948                 }
949             }
950             duration = 0;
951             for (int i=0 ; i<gets.length ; ++i)
952             {
953                 long startTime = System.currentTimeMillis();
954                 session.getHttpClient().executeMethod(gets[i]);
955                 duration += System.currentTimeMillis() - startTime;
956                 urlLog.log(BasicLevel.INFO, gets[i].getURI());
957                 if (isFrameSet)
958                 {
959                     String JavaDoc frameBody = gets[i].getResponseBodyAsString();
960                     URI frameURI = gets[i].getURI();
961                     gets[i].releaseConnection();
962                     duration += inDepthLoad(
963                         session,
964                         frameBody,
965                         frameURI);
966                 }
967                 else
968                 {
969                     gets[i].releaseConnection();
970                 }
971             }
972         }
973         catch (ParserException ex)
974         {
975             log.log(BasicLevel.WARN, "Cannot parse HTML body for " + session, ex);
976             duration = 0;
977         }
978         return duration;
979     }
980 }
981
Popular Tags