KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > protocol > http > sampler > HTTPSampler2


1 // $Header: /home/cvs/jakarta-jmeter/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler2.java,v 1.8.2.9 2004/10/27 23:09:09 sebb Exp $
2
/*
3  * Copyright 2001-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.jmeter.protocol.http.sampler;
18
19 import java.io.File JavaDoc;
20 import java.io.FileInputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import java.net.MalformedURLException JavaDoc;
23 import java.net.URL JavaDoc;
24
25 import java.util.Date JavaDoc;
26
27 import org.apache.commons.httpclient.ConnectMethod;
28 import org.apache.commons.httpclient.DefaultMethodRetryHandler;
29 import org.apache.commons.httpclient.HostConfiguration;
30 import org.apache.commons.httpclient.HttpConnection;
31 import org.apache.commons.httpclient.HttpMethod;
32 import org.apache.commons.httpclient.HttpMethodBase;
33 import org.apache.commons.httpclient.HttpState;
34 import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
35 import org.apache.commons.httpclient.methods.GetMethod;
36 import org.apache.commons.httpclient.methods.PostMethod;
37 import org.apache.commons.httpclient.protocol.Protocol;
38 import org.apache.jmeter.config.Argument;
39 import org.apache.jmeter.config.Arguments;
40
41 import org.apache.jmeter.protocol.http.control.AuthManager;
42 import org.apache.jmeter.protocol.http.control.CookieManager;
43 import org.apache.jmeter.protocol.http.control.HeaderManager;
44
45 import org.apache.jmeter.testelement.property.CollectionProperty;
46 import org.apache.jmeter.testelement.property.PropertyIterator;
47 import org.apache.jmeter.util.JMeterUtils;
48
49 import org.apache.jorphan.logging.LoggingManager;
50
51 import org.apache.log.Logger;
52
53 /**
54  * A sampler which understands all the parts necessary to read statistics about
55  * HTTP requests, including cookies and authentication.
56  *
57  * @version $Revision: 1.8.2.9 $ Last updated $Date: 2004/10/27 23:09:09 $
58  */

59 public class HTTPSampler2 extends HTTPSamplerBase
60 {
61     transient private static Logger log= LoggingManager.getLoggerForClass();
62
63     static {
64         // Set the default to Avalon Logkit, if not already defined:
65
if (System.getProperty("org.apache.commons.logging.Log")==null)
66         {
67             System.setProperty("org.apache.commons.logging.Log"
68                     ,"org.apache.commons.logging.impl.LogKitLogger");
69         }
70     }
71
72     /*
73      * Connection is re-used if possible
74      */

75     private transient HttpConnection httpConn = null;
76
77     /*
78      * These variables are recreated every time
79      * Find a better way of passing them round
80      */

81     private transient HttpMethodBase httpMethod = null;
82     private transient HttpState httpState = null;
83
84     /**
85      * Constructor for the HTTPSampler2 object.
86      */

87     public HTTPSampler2()
88     {
89         setArguments(new Arguments());
90     }
91
92     /**
93      * Set request headers in preparation to opening a connection.
94      *
95      * @param conn <code>URLConnection</code> to set headers on
96      * @exception IOException if an I/O exception occurs
97      */

98     private void setPostHeaders(PostMethod post) throws IOException JavaDoc
99     {
100         // Probably nothing needed, because the PostMethod class takes care of it
101
// /*postWriter.*/
102
// setHeaders(post, this);
103
}
104
105     /**
106      * Send POST data from <code>Entry</code> to the open connection.
107      *
108      * @param connection <code>URLConnection</code> where POST data should
109      * be sent
110      * @exception IOException if an I/O exception occurs
111      */

112     private void sendPostData(HttpMethod connection) throws IOException JavaDoc
113     {
114         /*postWriter.*/
115         sendPostData((PostMethod)connection, this);
116     }
117
118     /**
119      * Send POST data from Entry to the open connection.
120      */

121     public void sendPostData(PostMethod post, HTTPSampler2 sampler)
122         throws IOException JavaDoc
123     {
124         PropertyIterator args = sampler.getArguments().iterator();
125         while (args.hasNext())
126         {
127             Argument arg = (Argument) args.next().getObjectValue();
128             post.addParameter(arg.getName(),arg.getValue());
129         }
130         // If filename was specified then send the post using multipart syntax
131
String JavaDoc filename = sampler.getFilename();
132         if ((filename != null) && (filename.trim().length() > 0))
133         {
134             File JavaDoc input = new File JavaDoc(filename);
135             if (input.length() < Integer.MAX_VALUE) {
136                 post.setRequestContentLength((int)input.length());
137             } else {
138                 post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
139             }
140             //TODO - is this correct?
141
post.setRequestHeader("Content-Disposition",
142                 "form-data; name=\""
143                 + encode(sampler.getFileField())
144                 + "\"; filename=\""
145                 + encode(filename)
146                 + "\"");
147             // Specify content type and encoding
148
post.setRequestHeader("Content-Type", sampler.getMimetype());
149             post.setRequestBody(new FileInputStream JavaDoc(input));
150         }
151     }
152
153     private String JavaDoc encode(String JavaDoc value)
154     {
155         StringBuffer JavaDoc newValue = new StringBuffer JavaDoc();
156         char[] chars = value.toCharArray();
157         for (int i = 0; i < chars.length; i++)
158         {
159             if (chars[i] == '\\')
160             {
161                 newValue.append("\\\\");
162             }
163             else
164             {
165                 newValue.append(chars[i]);
166             }
167         }
168         return newValue.toString();
169     }
170
171     /**
172      * Returns an <code>HttpConnection</code> fully ready to attempt
173      * connection. This means it sets the request method (GET or
174      * POST), headers, cookies, and authorization for the URL request.
175      * <p>
176      * The request infos are saved into the sample result if one is provided.
177      *
178      * @param u <code>URL</code> of the URL request
179      * @param method http/https
180      * @param res sample result to save request infos to
181      * @return <code>HttpConnection</code> ready for .connect
182      * @exception IOException if an I/O Exception occurs
183      */

184     private HttpConnection setupConnection(
185         URL JavaDoc u,
186         String JavaDoc method,
187         HTTPSampleResult res)
188         throws IOException JavaDoc
189     {
190     
191         String JavaDoc urlStr = u.toString();
192
193         org.apache.commons.httpclient.URI
194             uri = new org.apache.commons.httpclient.URI(urlStr);
195
196         String JavaDoc schema = uri.getScheme();
197         if ((schema == null) || (schema.equals("")))
198         {
199             schema = "http";
200         }
201         Protocol protocol = Protocol.getProtocol(schema);
202
203         String JavaDoc host = uri.getHost();
204         int port = uri.getPort();
205         
206         HostConfiguration hc = new HostConfiguration();
207         hc.setHost(host,port,protocol);
208         if (httpConn!= null && hc.hostEquals(httpConn))
209         {
210             //Same details, no need to reset
211
}
212         else
213         {
214             httpConn = new HttpConnection(hc);
215             //TODO check these
216
httpConn.setProxyHost(System.getProperty("http.proxyHost"));
217             httpConn.setProxyPort( Integer.parseInt(System.getProperty("http.proxyPort","80")));
218         }
219
220         if (method.equals(POST))
221         {
222             httpMethod = new PostMethod(urlStr);
223         }
224         else
225         {
226             httpMethod = new GetMethod(urlStr);
227             //httpMethod;
228
new DefaultMethodRetryHandler();
229         }
230
231         httpMethod.setHttp11(!JMeterUtils.getPropDefault("httpclient.version","1.1").equals("1.0"));
232
233         // Set the timeout (if non-zero)
234
httpConn.setSoTimeout(JMeterUtils.getPropDefault("httpclient.timeout",0));
235
236         httpState = new HttpState();
237         if (httpConn.isProxied() && httpConn.isSecure()) {
238             httpMethod = new ConnectMethod(httpMethod);
239         }
240         
241         // Allow HttpClient to handle the redirects:
242
httpMethod.setFollowRedirects(getPropertyAsBoolean(AUTO_REDIRECTS));
243         
244         // a well-behaved browser is supposed to send 'Connection: close'
245
// with the last request to an HTTP server. Instead, most browsers
246
// leave it to the server to close the connection after their
247
// timeout period. Leave it to the JMeter user to decide.
248
if (getUseKeepAlive())
249         {
250             httpMethod.setRequestHeader("Connection", "keep-alive");
251         }
252         else
253         {
254             httpMethod.setRequestHeader("Connection", "close");
255         }
256
257         String JavaDoc hdrs=setConnectionHeaders(httpMethod, u, getHeaderManager());
258         String JavaDoc cookies= setConnectionCookie(httpMethod, u, getCookieManager());
259
260         if (res != null)
261         {
262             StringBuffer JavaDoc sb= new StringBuffer JavaDoc();
263             if (method.equals(POST))
264             {
265                 String JavaDoc q = this.getQueryString();
266                 res.setQueryString(q);
267                 sb.append("Query data:\n");
268                 sb.append(q);
269                 sb.append('\n');
270             }
271             if (cookies != null)
272             {
273                 res.setCookies(cookies);
274                 sb.append("\nCookie Data:\n");
275                 sb.append(cookies);
276                 sb.append('\n');
277             }
278             res.setSamplerData(sb.toString());
279             //TODO rather than stuff all the information in here,
280
//pick it up from the individual fields later
281

282             res.setURL(u);
283             res.setHTTPMethod(method);
284             res.setRequestHeaders(hdrs);
285         }
286
287         setConnectionAuthorization(httpMethod, u, getAuthManager());
288
289         if (method.equals(POST))
290         {
291             setPostHeaders((PostMethod) httpMethod);
292         }
293         return httpConn;
294     }
295
296     /**
297      * Gets the ResponseHeaders
298      *
299      * @param method connection from which the headers are read
300      * @return string containing the headers, one per line
301      */

302     protected String JavaDoc getResponseHeaders(HttpMethod method)
303         throws IOException JavaDoc
304     {
305         StringBuffer JavaDoc headerBuf= new StringBuffer JavaDoc();
306         org.apache.commons.httpclient.Header rh[] = method.getResponseHeaders();
307         headerBuf.append(method.getStatusLine());//header[0] is not the status line...
308
headerBuf.append("\n");
309
310         for (int i= 0; i < rh.length; i++)
311         {
312             String JavaDoc key = rh[i].getName();
313             if (!key.equalsIgnoreCase("transfer-encoding"))//TODO - why is this not saved?
314
{
315                 headerBuf.append(key);
316                 headerBuf.append(": ");
317                 headerBuf.append(rh[i].getValue());
318                 headerBuf.append("\n");
319             }
320         }
321         return headerBuf.toString();
322     }
323
324     /**
325      * Extracts all the required cookies for that particular URL request and
326      * sets them in the <code>HttpMethod</code> passed in.
327      *
328      * @param method <code>HttpMethod</code> which represents the request
329      * @param u <code>URL</code> of the request
330      * @param cookieManager the <code>CookieManager</code> containing all the
331      * cookies for this <code>UrlConfig</code>
332      */

333     private String JavaDoc setConnectionCookie(
334         HttpMethod method,
335         URL JavaDoc u,
336         CookieManager cookieManager)
337     {
338         String JavaDoc cookieHeader= null;
339         if (cookieManager != null)
340         {
341             cookieHeader= cookieManager.getCookieHeaderForURL(u);
342             if (cookieHeader != null)
343             {
344                 method.setRequestHeader("Cookie", cookieHeader);
345             }
346         }
347         return cookieHeader;
348     }
349
350     /**
351      * Extracts all the required headers for that particular URL request and
352      * sets them in the <code>HttpMethod</code> passed in
353      *
354      *@param method <code>HttpMethod</code> which represents the request
355      *@param u <code>URL</code> of the URL request
356      *@param headerManager the <code>HeaderManager</code> containing all the
357      * cookies for this <code>UrlConfig</code>
358      * @return the headers as a string
359      */

360     private String JavaDoc setConnectionHeaders(
361         HttpMethod method,
362         URL JavaDoc u,
363         HeaderManager headerManager)
364     {
365         StringBuffer JavaDoc hdrs = new StringBuffer JavaDoc(100);
366         if (headerManager != null)
367         {
368             CollectionProperty headers= headerManager.getHeaders();
369             if (headers != null)
370             {
371                 PropertyIterator i= headers.iterator();
372                 while (i.hasNext())
373                 {
374                     org.apache.jmeter.protocol.http.control.Header header =
375                         (org.apache.jmeter.protocol.http.control.Header)i.next().getObjectValue();
376                     String JavaDoc n=header.getName();
377                     String JavaDoc v=header.getValue();
378                     method.setRequestHeader(n,v);
379                     hdrs.append(n);
380                     hdrs.append(": ");
381                     hdrs.append(v);
382                     hdrs.append("\n");
383                 }
384             }
385         }
386         return hdrs.toString();
387     }
388
389     /**
390      * Extracts all the required authorization for that particular URL request
391      * and sets it in the <code>HttpMethod</code> passed in.
392      *
393      * @param method <code>HttpMethod</code> which represents the request
394      * @param u <code>URL</code> of the URL request
395      * @param authManager the <code>AuthManager</code> containing all the
396      * cookies for this <code>UrlConfig</code>
397      */

398     private void setConnectionAuthorization(
399         HttpMethod method,
400         URL JavaDoc u,
401         AuthManager authManager)
402     {
403         if (authManager != null)
404         {
405             // Old method
406
String JavaDoc authHeader= authManager.getAuthHeaderForURL(u);
407             if (authHeader != null)
408             {
409                 method.setRequestHeader("Authorization", authHeader);
410             }
411
412             //TODO: replace with something like this:
413
// Authorization auth= authManager.getAuthForURL(u);
414
// if (auth != null)
415
// {
416
// // TODO - set up realm, thishost and domain
417
// httpState.setCredentials(
418
// null, // "realm"
419
// auth.getURL(),
420
// new NTCredentials(// Includes other types of Credentials
421
// auth.getUser(),
422
// auth.getPass(),
423
// null, // "thishost",
424
// null // "targetdomain"
425
// )
426
// );
427
// }
428
}
429     }
430
431     /**
432      * Samples the URL passed in and stores the result in
433      * <code>HTTPSampleResult</code>, following redirects and downloading
434      * page resources as appropriate.
435      * <p>
436      * When getting a redirect target, redirects are not followed and
437      * resources are not downloaded. The caller will take care of this.
438      *
439      * @param url URL to sample
440      * @param method HTTP method: GET, POST,...
441      * @param areFollowingRedirect whether we're getting a redirect target
442      * @param frameDepth Depth of this target in the frame structure.
443      * Used only to prevent infinite recursion.
444      * @return results of the sampling
445      */

446     protected HTTPSampleResult sample(
447         URL JavaDoc url,
448         String JavaDoc method,
449         boolean areFollowingRedirect,
450         int frameDepth)
451     {
452
453         String JavaDoc urlStr = url.toString();
454         
455         log.debug("Start : sample" + urlStr);
456         log.debug("method" + method);
457
458         httpMethod=null;
459         
460         HTTPSampleResult res= new HTTPSampleResult();
461         if(this.getPropertyAsBoolean(MONITOR)){
462             res.setMonitor(true);
463         } else {
464             res.setMonitor(false);
465         }
466         res.setSampleLabel(urlStr);
467         res.sampleStart(); // Count the retries as well in the time
468

469         try
470         {
471             HttpConnection connection = setupConnection(url, method, res);
472                 
473             if (method.equals(POST))
474             {
475                 sendPostData(httpMethod);
476             }
477
478             int statusCode = httpMethod.execute(httpState, connection);
479
480             // Request sent. Now get the response:
481
byte[] responseData= httpMethod.getResponseBody();
482
483             res.sampleEnd();
484             // Done with the sampling proper.
485

486             // Now collect the results into the HTTPSampleResult:
487

488             res.setSampleLabel(httpMethod.getURI().toString());// Pick up Actual path (after redirects)
489
res.setResponseData(responseData);
490
491             res.setResponseCode(Integer.toString(statusCode));
492             res.setSuccessful(200 <= statusCode && statusCode <= 399);
493
494             res.setResponseMessage(httpMethod.getStatusText());
495
496             String JavaDoc ct=null;
497             org.apache.commons.httpclient.Header h =
498                 httpMethod.getResponseHeader("Content-Type");
499             if (h!=null)// Can be missing, e.g. on redirect
500
{
501                 ct= h.getValue();
502                 res.setContentType(ct);// e.g. text/html; charset=ISO-8859-1
503
}
504             if (ct != null)
505             {
506                 // Extract charset and store as DataEncoding
507
// TODO do we need process http-equiv META tags, e.g.:
508
// <META http-equiv="content-type" content="text/html; charset=foobar">
509
// or can we leave that to the renderer ?
510
String JavaDoc de=ct.toLowerCase();
511                 final String JavaDoc cs="charset=";
512                 int cset= de.indexOf(cs);
513                 if (cset >= 0)
514                 {
515                     res.setDataEncoding(de.substring(cset+cs.length()));
516                 }
517                 if (ct.startsWith("image/"))
518                 {
519                     res.setDataType(HTTPSampleResult.BINARY);
520                 }
521                 else
522                 {
523                     res.setDataType(HTTPSampleResult.TEXT);
524                 }
525             }
526
527             res.setResponseHeaders(getResponseHeaders(httpMethod));
528             if (res.isRedirect())
529             {
530                 res.setRedirectLocation(httpMethod.getResponseHeader("Location").getValue());
531             }
532
533             // Store any cookies received in the cookie manager:
534
saveConnectionCookies(httpState, getCookieManager());
535
536             // Follow redirects and download page resources if appropriate:
537
if (!areFollowingRedirect)
538             {
539                 boolean didFollowRedirects= false;
540                 if (res.isRedirect())
541                 {
542                     log.debug("Location set to - " + res.getRedirectLocation());
543                     
544                     if (getFollowRedirects())
545                     {
546                         res= followRedirects(res, frameDepth);
547                         didFollowRedirects= true;
548                     }
549                 }
550
551                 if (isImageParser()
552                     && (HTTPSampleResult.TEXT).equals(res.getDataType())
553                     && res.isSuccessful())
554                 {
555                     if (frameDepth > MAX_FRAME_DEPTH)
556                     {
557                         res.addSubResult(
558                             errorResult(
559                                 new Exception JavaDoc("Maximum frame/iframe nesting depth exceeded."),
560                                 null,
561                                 0));
562                     }
563                     else
564                     {
565                         // If we followed redirects, we already have a container:
566
boolean createContainerResults= !didFollowRedirects;
567
568                         res=
569                             downloadPageResources(
570                                 res,
571                                 createContainerResults,
572                                 frameDepth);
573                     }
574                 }
575             }
576
577             log.debug("End : sample");
578             if (httpMethod != null) httpMethod.releaseConnection();
579             return res;
580         }
581         catch (IllegalArgumentException JavaDoc e)// e.g. some kinds of invalid URL
582
{
583             res.sampleEnd();
584             HTTPSampleResult err = errorResult(e, url.toString(), res.getTime());
585             err.setSampleLabel("Error: "+url.toString());
586             return err;
587         }
588         catch (IOException JavaDoc e)
589         {
590             res.sampleEnd();
591             HTTPSampleResult err = errorResult(e, url.toString(), res.getTime());
592             err.setSampleLabel("Error: "+url.toString());
593             return err;
594         }
595         finally
596         {
597             if (httpMethod != null) httpMethod.releaseConnection();
598         }
599     }
600
601     /**
602      * Iteratively download the redirect targets of a redirect response.
603      * <p>
604      * The returned result will contain one subsample for each request issued,
605      * including the original one that was passed in. It will be an
606      * HTTPSampleResult that should mostly look as if the final destination
607      * of the redirect chain had been obtained in a single shot.
608      *
609      * @param res result of the initial request - must be a redirect response
610      * @param frameDepth Depth of this target in the frame structure.
611      * Used only to prevent infinite recursion.
612      * @return "Container" result with one subsample per request issued
613      */

614     private HTTPSampleResult followRedirects(
615         HTTPSampleResult res,
616         int frameDepth)
617     {
618         HTTPSampleResult totalRes= new HTTPSampleResult(res);
619         HTTPSampleResult lastRes= res;
620
621         int redirect;
622         for (redirect= 0; redirect < MAX_REDIRECTS; redirect++)
623         {
624             String JavaDoc location= encodeSpaces(lastRes.getRedirectLocation());
625                 // Browsers seem to tolerate Location headers with spaces,
626
// replacing them automatically with %20. We want to emulate
627
// this behaviour.
628
try
629             {
630                 lastRes=
631                     sample(
632                         new URL JavaDoc(lastRes.getURL(), location),
633                         GET,
634                         true,
635                         frameDepth);
636             }
637             catch (MalformedURLException JavaDoc e)
638             {
639                 lastRes= errorResult(e, location, 0);
640             }
641             totalRes.addSubResult(lastRes);
642
643             if (!lastRes.isRedirect())
644             {
645                 break;
646             }
647         }
648         if (redirect >= MAX_REDIRECTS)
649         {
650             lastRes=
651                 errorResult(
652                     new IOException JavaDoc("Exceeeded maximum number of redirects: "+MAX_REDIRECTS),
653                     null,
654                     0);
655             totalRes.addSubResult(lastRes);
656         }
657
658         // Now populate the any totalRes fields that need to
659
// come from lastRes:
660
totalRes.setSampleLabel(
661             totalRes.getSampleLabel() + "->" + lastRes.getSampleLabel());
662         // The following three can be discussed: should they be from the
663
// first request or from the final one? I chose to do it this way
664
// because that's what browsers do: they show the final URL of the
665
// redirect chain in the location field.
666
totalRes.setURL(lastRes.getURL());
667         totalRes.setHTTPMethod(lastRes.getHTTPMethod());
668         totalRes.setRequestHeaders(lastRes.getRequestHeaders());
669
670         totalRes.setResponseData(lastRes.getResponseData());
671         totalRes.setResponseCode(lastRes.getResponseCode());
672         totalRes.setSuccessful(lastRes.isSuccessful());
673         totalRes.setResponseMessage(lastRes.getResponseMessage());
674         totalRes.setDataType(lastRes.getDataType());
675         totalRes.setResponseHeaders(lastRes.getResponseHeaders());
676         return totalRes;
677     }
678
679     /**
680      * From the <code>HttpState</code>, store all the "set-cookie"
681      * key-pair values in the cookieManager of the <code>UrlConfig</code>.
682      *
683      * @param state <code>HttpState</code> which represents the request
684      * @param u <code>URL</code> of the URL request
685      * @param cookieManager the <code>CookieManager</code> containing all the
686      * cookies for this <code>UrlConfig</code>
687      */

688     private void saveConnectionCookies(
689         HttpState state,
690         CookieManager cookieManager)
691     {
692         if (cookieManager != null)
693         {
694             org.apache.commons.httpclient.Cookie [] c = state.getCookies();
695             for (int i= 0; i < c.length ; i++)
696             {
697                    Date JavaDoc exp = c[i].getExpiryDate();// might be absent
698
cookieManager.add(
699                         new org.apache.jmeter.protocol.http.control.
700
                        Cookie(c[i].getName(),
701                                 c[i].getValue(),
702                                 c[i].getDomain(),
703                                 c[i].getPath(),
704                                 c[i].getSecure(),
705                                 exp != null ? exp.getTime()
706                                 : System.currentTimeMillis() + 1000 * 60 * 60 * 24 //cf CookieManager
707
)
708                         );
709             }
710         }
711     }
712
713     public void threadStarted()
714     {
715         log.info("Thread Started");
716     }
717     
718     public void threadFinished()
719     {
720         log.info("Thread Finished");
721         if (httpConn != null) httpConn.close();
722     }
723
724     //////////////////////////////////////////////////////////////////////////////////////////////////
725

726     public static class Test extends junit.framework.TestCase
727     {
728         public Test(String JavaDoc name)
729         {
730             super(name);
731         }
732
733         public void testArgumentWithoutEquals() throws Exception JavaDoc
734         {
735             HTTPSampler2 sampler= new HTTPSampler2();
736             sampler.setProtocol("http");
737             sampler.setMethod(GET);
738             sampler.setPath("/index.html?pear");
739             sampler.setDomain("www.apache.org");
740             assertEquals(
741                 "http://www.apache.org/index.html?pear",
742                 sampler.getUrl().toString());
743         }
744
745         public void testMakingUrl() throws Exception JavaDoc
746         {
747             HTTPSampler2 config= new HTTPSampler2();
748             config.setProtocol("http");
749             config.setMethod(GET);
750             config.addArgument("param1", "value1");
751             config.setPath("/index.html");
752             config.setDomain("www.apache.org");
753             assertEquals(
754                 "http://www.apache.org/index.html?param1=value1",
755                 config.getUrl().toString());
756         }
757         public void testMakingUrl2() throws Exception JavaDoc
758         {
759             HTTPSampler2 config= new HTTPSampler2();
760             config.setProtocol("http");
761             config.setMethod(GET);
762             config.addArgument("param1", "value1");
763             config.setPath("/index.html?p1=p2");
764             config.setDomain("www.apache.org");
765             assertEquals(
766                 "http://www.apache.org/index.html?param1=value1&p1=p2",
767                 config.getUrl().toString());
768         }
769         public void testMakingUrl3() throws Exception JavaDoc
770         {
771             HTTPSampler2 config= new HTTPSampler2();
772             config.setProtocol("http");
773             config.setMethod(POST);
774             config.addArgument("param1", "value1");
775             config.setPath("/index.html?p1=p2");
776             config.setDomain("www.apache.org");
777             assertEquals(
778                 "http://www.apache.org/index.html?p1=p2",
779                 config.getUrl().toString());
780         }
781
782         // test cases for making Url, and exercise method
783
// addArgument(String name,String value,String metadata)
784

785         public void testMakingUrl4() throws Exception JavaDoc
786         {
787             HTTPSampler2 config= new HTTPSampler2();
788             config.setProtocol("http");
789             config.setMethod(GET);
790             config.addArgument("param1", "value1", "=");
791             config.setPath("/index.html");
792             config.setDomain("www.apache.org");
793             assertEquals(
794                 "http://www.apache.org/index.html?param1=value1",
795                 config.getUrl().toString());
796         }
797         public void testMakingUrl5() throws Exception JavaDoc
798         {
799             HTTPSampler2 config= new HTTPSampler2();
800             config.setProtocol("http");
801             config.setMethod(GET);
802             config.addArgument("param1", "", "=");
803             config.setPath("/index.html");
804             config.setDomain("www.apache.org");
805             assertEquals(
806                 "http://www.apache.org/index.html?param1=",
807                 config.getUrl().toString());
808         }
809         public void testMakingUrl6() throws Exception JavaDoc
810         {
811             HTTPSampler2 config= new HTTPSampler2();
812             config.setProtocol("http");
813             config.setMethod(GET);
814             config.addArgument("param1", "", "");
815             config.setPath("/index.html");
816             config.setDomain("www.apache.org");
817             assertEquals(
818                 "http://www.apache.org/index.html?param1",
819                 config.getUrl().toString());
820         }
821
822         // test cases for making Url, and exercise method
823
// parseArguments(String queryString)
824

825         public void testMakingUrl7() throws Exception JavaDoc
826         {
827             HTTPSampler2 config= new HTTPSampler2();
828             config.setProtocol("http");
829             config.setMethod(GET);
830             config.parseArguments("param1=value1");
831             config.setPath("/index.html");
832             config.setDomain("www.apache.org");
833             assertEquals(
834                 "http://www.apache.org/index.html?param1=value1",
835                 config.getUrl().toString());
836         }
837
838         public void testMakingUrl8() throws Exception JavaDoc
839         {
840             HTTPSampler2 config= new HTTPSampler2();
841             config.setProtocol("http");
842             config.setMethod(GET);
843             config.parseArguments("param1=");
844             config.setPath("/index.html");
845             config.setDomain("www.apache.org");
846             assertEquals(
847                 "http://www.apache.org/index.html?param1=",
848                 config.getUrl().toString());
849         }
850
851         public void testMakingUrl9() throws Exception JavaDoc
852         {
853             HTTPSampler2 config= new HTTPSampler2();
854             config.setProtocol("http");
855             config.setMethod(GET);
856             config.parseArguments("param1");
857             config.setPath("/index.html");
858             config.setDomain("www.apache.org");
859             assertEquals(
860                 "http://www.apache.org/index.html?param1",
861                 config.getUrl().toString());
862         }
863
864         public void testMakingUrl10() throws Exception JavaDoc
865         {
866             HTTPSampler2 config= new HTTPSampler2();
867             config.setProtocol("http");
868             config.setMethod(GET);
869             config.parseArguments("");
870             config.setPath("/index.html");
871             config.setDomain("www.apache.org");
872             assertEquals(
873                 "http://www.apache.org/index.html",
874                 config.getUrl().toString());
875         }
876     }
877 }
878
Popular Tags