KickJava   Java API By Example, From Geeks To Geeks.

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


1 // $Header: /home/cvs/jakarta-jmeter/src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSampler.java,v 1.91.2.5 2004/10/03 14:23:30 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.BufferedInputStream JavaDoc;
20 import java.io.ByteArrayOutputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22
23 import java.net.BindException JavaDoc;
24 import java.net.HttpURLConnection JavaDoc;
25 import java.net.MalformedURLException JavaDoc;
26 import java.net.URL JavaDoc;
27 import java.net.URLConnection JavaDoc;
28
29 import java.util.zip.GZIPInputStream JavaDoc;
30
31 import org.apache.jmeter.config.Arguments;
32
33 import org.apache.jmeter.protocol.http.control.AuthManager;
34 import org.apache.jmeter.protocol.http.control.CookieManager;
35 import org.apache.jmeter.protocol.http.control.Header;
36 import org.apache.jmeter.protocol.http.control.HeaderManager;
37
38 import org.apache.jmeter.testelement.property.CollectionProperty;
39 import org.apache.jmeter.testelement.property.PropertyIterator;
40
41 import org.apache.jmeter.util.JMeterUtils;
42 import org.apache.jmeter.util.SSLManager;
43
44 import org.apache.jorphan.logging.LoggingManager;
45
46 import org.apache.log.Logger;
47
48 /**
49  * A sampler which understands all the parts necessary to read statistics about
50  * HTTP requests, including cookies and authentication.
51  *
52  * @version $Revision: 1.91.2.5 $ Last updated $Date: 2004/10/03 14:23:30 $
53  */

54 public class HTTPSampler extends HTTPSamplerBase
55 {
56     transient private static Logger log= LoggingManager.getLoggerForClass();
57
58     private static final int MAX_CONN_RETRIES = 10; // Maximum connection retries
59

60     //protected static String encoding= "iso-8859-1";
61
private static final PostWriter postWriter= new PostWriter();
62
63     static {// TODO - document what this is doing and why
64
System.setProperty(
65             "java.protocol.handler.pkgs",
66             JMeterUtils.getPropDefault(
67                 "ssl.pkgs",
68                 "com.sun.net.ssl.internal.www.protocol"));
69         System.setProperty("javax.net.ssl.debug", "all");
70     }
71
72     /**
73      * Constructor for the HTTPSampler object.
74      */

75     public HTTPSampler()
76     {
77         setArguments(new Arguments());
78     }
79
80     /**
81      * Set request headers in preparation to opening a connection.
82      *
83      * @param conn <code>URLConnection</code> to set headers on
84      * @exception IOException if an I/O exception occurs
85      */

86     public void setPostHeaders(URLConnection JavaDoc conn) throws IOException JavaDoc
87     {
88         postWriter.setHeaders(conn, this);
89     }
90
91     /**
92      * Send POST data from <code>Entry</code> to the open connection.
93      *
94      * @param connection <code>URLConnection</code> where POST data should
95      * be sent
96      * @exception IOException if an I/O exception occurs
97      */

98     public void sendPostData(URLConnection JavaDoc connection) throws IOException JavaDoc
99     {
100         postWriter.sendPostData(connection, this);
101     }
102
103     /**
104      * Returns an <code>HttpURLConnection</code> fully ready to attempt
105      * connection. This means it sets the request method (GET or
106      * POST), headers, cookies, and authorization for the URL request.
107      * <p>
108      * The request infos are saved into the sample result if one is provided.
109      *
110      * @param u <code>URL</code> of the URL request
111      * @param method http/https
112      * @param res sample result to save request infos to
113      * @return <code>HttpURLConnection</code> ready for .connect
114      * @exception IOException if an I/O Exception occurs
115      */

116     protected HttpURLConnection JavaDoc setupConnection(
117         URL JavaDoc u,
118         String JavaDoc method,
119         HTTPSampleResult res)
120         throws IOException JavaDoc
121     {
122         HttpURLConnection JavaDoc conn;
123         // [Jordi <jsalvata@atg.com>]
124
// I've not been able to find out why we're not using this
125
// feature of HttpURLConnections and we're doing redirection
126
// by hand instead. Everything would be so much simpler...
127
// [/Jordi]
128
// Mike: answer - it didn't work. Maybe in JDK1.4 it works, but
129
// honestly, it doesn't seem like they're working on this.
130
// My longer term plan is to use Apache's home grown HTTP Client, or
131
// maybe even HTTPUnit's classes. I'm sure both would be better than
132
// Sun's.
133

134         // [sebb] Make redirect following configurable (see bug 19004)
135
// They do seem to work on JVM 1.4.1_03 (Sun/WinXP)
136
HttpURLConnection.setFollowRedirects(getPropertyAsBoolean(AUTO_REDIRECTS));
137
138         conn= (HttpURLConnection JavaDoc)u.openConnection();
139         // Delegate SSL specific stuff to SSLManager so that compilation still
140
// works otherwise.
141
if ("https".equalsIgnoreCase(u.getProtocol()))
142         {
143             try
144             {
145                 SSLManager.getInstance().setContext(conn);
146             }
147             catch (Exception JavaDoc e)
148             {
149                 log.warn(
150                     "You may have forgotten to set the ssl.provider property "
151                         + "in jmeter.properties",
152                     e);
153             }
154         }
155
156         // a well-bahaved browser is supposed to send 'Connection: close'
157
// with the last request to an HTTP server. Instead, most browsers
158
// leave it to the server to close the connection after their
159
// timeout period. Leave it to the JMeter user to decide.
160
if (getUseKeepAlive())
161         {
162             conn.setRequestProperty("Connection", "keep-alive");
163         }
164         else
165         {
166             conn.setRequestProperty("Connection", "close");
167         }
168
169         conn.setRequestMethod(method);
170         String JavaDoc hdrs=setConnectionHeaders(conn, u, getHeaderManager());
171         String JavaDoc cookies= setConnectionCookie(conn, u, getCookieManager());
172         if (res != null)
173         {
174             StringBuffer JavaDoc sb= new StringBuffer JavaDoc();
175             if (method.equals(POST))
176             {
177                 String JavaDoc q = this.getQueryString();
178                 res.setQueryString(q);
179                 sb.append("Query data:\n");
180                 sb.append(q);
181                 sb.append('\n');
182             }
183             if (cookies != null)
184             {
185                 res.setCookies(cookies);
186                 sb.append("\nCookie Data:\n");
187                 sb.append(cookies);
188                 sb.append('\n');
189             }
190             res.setSamplerData(sb.toString());
191             //TODO rather than stuff all the information in here,
192
//pick it up from the individual fields later
193

194             res.setURL(u);
195             res.setHTTPMethod(method);
196             res.setRequestHeaders(hdrs);
197         }
198         setConnectionAuthorization(conn, u, getAuthManager());
199         if (method.equals(POST))
200         {
201             setPostHeaders(conn);
202         }
203         return conn;
204     }
205
206     /**
207      * Reads the response from the URL connection.
208      *
209      * @param conn URL from which to read response
210      * @return response content
211      * @exception IOException if an I/O exception occurs
212      */

213     protected byte[] readResponse(HttpURLConnection JavaDoc conn) throws IOException JavaDoc
214     {
215         byte[] readBuffer= getThreadContext().getReadBuffer();
216         BufferedInputStream JavaDoc in;
217         boolean logError=false; // Should we log the error?
218
try
219         {
220             if ("gzip".equals(conn.getContentEncoding()))// works OK even if CE is null
221
{
222                 in=
223                     new BufferedInputStream JavaDoc(
224                         new GZIPInputStream JavaDoc(conn.getInputStream()));
225             }
226             else
227             {
228                 in= new BufferedInputStream JavaDoc(conn.getInputStream());
229             }
230         }
231         catch (IOException JavaDoc e)
232         {
233             //TODO: try to improve error discrimination when using JDK1.3
234
// and/or conditionally call .getCause()
235

236             //JDK1.4: if (e.getCause() instanceof FileNotFoundException)
237
//JDK1.4: {
238
//JDK1.4: log.warn(e.getCause().toString());
239
//JDK1.4: }
240
//JDK1.4: else
241
{
242                 log.error(e.toString());
243                 //JDK1.4: Throwable cause = e.getCause();
244
//JDK1.4: if (cause != null){
245
//JDK1.4: log.error("Cause: "+cause);
246
//JDK1.4: }
247
logError=true;
248             }
249             in= new BufferedInputStream JavaDoc(conn.getErrorStream());
250         }
251         catch (Exception JavaDoc e)
252         {
253             log.error(e.toString());
254             //JDK1.4: Throwable cause = e.getCause();
255
//JDK1.4: if (cause != null){
256
//JDK1.4: log.error("Cause: "+cause);
257
//JDK1.4: }
258
in= new BufferedInputStream JavaDoc(conn.getErrorStream());
259             logError=true;
260         }
261         java.io.ByteArrayOutputStream JavaDoc w= new ByteArrayOutputStream JavaDoc();
262         int x= 0;
263         while ((x= in.read(readBuffer)) > -1)
264         {
265             w.write(readBuffer, 0, x);
266         }
267         in.close();
268         w.flush();
269         w.close();
270         if (logError)
271         {
272             String JavaDoc s;
273             if (w.size() > 1000){
274                 s="\n"+w.toString().substring(0,1000)+"\n\t...";
275             } else {
276                 s="\n"+w.toString();
277             }
278             log.error(s);
279         }
280         return w.toByteArray();
281     }
282
283     /**
284      * Gets the ResponseHeaders from the URLConnection
285      *
286      * @param conn connection from which the headers are read
287      * @return string containing the headers, one per line
288      */

289     protected String JavaDoc getResponseHeaders(HttpURLConnection JavaDoc conn)
290         throws IOException JavaDoc
291     {
292         StringBuffer JavaDoc headerBuf= new StringBuffer JavaDoc();
293         headerBuf.append(conn.getHeaderField(0));//Leave header as is
294
// headerBuf.append(conn.getHeaderField(0).substring(0, 8));
295
// headerBuf.append(" ");
296
// headerBuf.append(conn.getResponseCode());
297
// headerBuf.append(" ");
298
// headerBuf.append(conn.getResponseMessage());
299
headerBuf.append("\n");
300
301         for (int i= 1; conn.getHeaderFieldKey(i) != null; i++)
302         {
303             modifyHeaderValues(conn,i, headerBuf);
304         }
305         return headerBuf.toString();
306     }
307
308     /**
309      * @param conn connection
310      * @param headerIndex which header to use
311      * @param resultBuf output string buffer
312      */

313     protected void modifyHeaderValues(HttpURLConnection JavaDoc conn, int headerIndex, StringBuffer JavaDoc resultBuf)
314     {
315         if ("transfer-encoding" //TODO - why is this not saved? A: it might be a proxy server specific field.
316
// If JMeter is using a proxy, the browser wouldn't know about that.
317
.equalsIgnoreCase(conn.getHeaderFieldKey(headerIndex)))
318         {
319            return;
320         }
321         resultBuf.append(conn.getHeaderFieldKey(headerIndex));
322         resultBuf.append(": ");
323         resultBuf.append(conn.getHeaderField(headerIndex));
324         resultBuf.append("\n");
325     }
326
327     /**
328      * Extracts all the required cookies for that particular URL request and
329      * sets them in the <code>HttpURLConnection</code> passed in.
330      *
331      * @param conn <code>HttpUrlConnection</code> which represents the
332      * URL request
333      * @param u <code>URL</code> of the URL request
334      * @param cookieManager the <code>CookieManager</code> containing all the
335      * cookies for this <code>UrlConfig</code>
336      */

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

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

403     private void setConnectionAuthorization(
404         HttpURLConnection JavaDoc conn,
405         URL JavaDoc u,
406         AuthManager authManager)
407     {
408         if (authManager != null)
409         {
410             String JavaDoc authHeader= authManager.getAuthHeaderForURL(u);
411             if (authHeader != null)
412             {
413                 conn.setRequestProperty("Authorization", authHeader);
414             }
415         }
416     }
417
418     /**
419      * Samples the URL passed in and stores the result in
420      * <code>HTTPSampleResult</code>, following redirects and downloading
421      * page resources as appropriate.
422      * <p>
423      * When getting a redirect target, redirects are not followed and
424      * resources are not downloaded. The caller will take care of this.
425      *
426      * @param url URL to sample
427      * @param method HTTP method: GET, POST,...
428      * @param areFollowingRedirect whether we're getting a redirect target
429      * @param frameDepth Depth of this target in the frame structure.
430      * Used only to prevent infinite recursion.
431      * @return results of the sampling
432      */

433     protected HTTPSampleResult sample(
434         URL JavaDoc url,
435         String JavaDoc method,
436         boolean areFollowingRedirect,
437         int frameDepth)
438     {
439         HttpURLConnection JavaDoc conn= null;
440
441         String JavaDoc urlStr = url.toString();
442         log.debug("Start : sample" + urlStr);
443
444         HTTPSampleResult res= new HTTPSampleResult();
445         if(this.getPropertyAsBoolean(MONITOR)){
446             res.setMonitor(true);
447         } else {
448             res.setMonitor(false);
449         }
450         res.setSampleLabel(urlStr);
451         res.sampleStart(); // Count the retries as well in the time
452

453         try
454         {
455             // Sampling proper - establish the connection and read the response:
456
// Repeatedly try to connect:
457
int retry;
458             for (retry= 1; retry <= MAX_CONN_RETRIES; retry++)
459             {
460                 try
461                 {
462                     conn= setupConnection(url, method, res);
463                     // Attempt the connection:
464
conn.connect();
465                     break;
466                 }
467                 catch (BindException JavaDoc e)
468                 {
469                     if (retry >= MAX_CONN_RETRIES)
470                     {
471                         log.error("Can't connect", e);
472                         throw e;
473                     }
474                     log.debug("Bind exception, try again");
475                     conn.disconnect();
476                     this.setUseKeepAlive(false);
477                     continue; // try again
478
}
479                 catch (IOException JavaDoc e)
480                 {
481                     log.debug("Connection failed, giving up");
482                     throw e;
483                 }
484             }
485             if (retry > MAX_CONN_RETRIES)
486             {
487                 // This should never happen, but...
488
throw new BindException JavaDoc();
489             }
490             // Nice, we've got a connection. Finish sending the request:
491
if (method.equals(POST))
492             {
493                 sendPostData(conn);
494             }
495             // Request sent. Now get the response:
496
byte[] responseData= readResponse(conn);
497
498             res.sampleEnd();
499             // Done with the sampling proper.
500

501             // Now collect the results into the HTTPSampleResult:
502

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

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

705     private void saveConnectionCookies(
706         HttpURLConnection JavaDoc conn,
707         URL JavaDoc u,
708         CookieManager cookieManager)
709     {
710         if (cookieManager != null)
711         {
712             for (int i= 1; conn.getHeaderFieldKey(i) != null; i++)
713             {
714                 if (conn.getHeaderFieldKey(i).equalsIgnoreCase("set-cookie"))
715                 {
716                     cookieManager.addCookieFromHeader(
717                         conn.getHeaderField(i),
718                         u);
719                 }
720             }
721         }
722     }
723
724     public static class Test extends junit.framework.TestCase
725     {
726         public Test(String JavaDoc name)
727         {
728             super(name);
729         }
730
731         public void testArgumentWithoutEquals() throws Exception JavaDoc
732         {
733             HTTPSampler sampler= new HTTPSampler();
734             sampler.setProtocol("http");
735             sampler.setMethod(GET);
736             sampler.setPath("/index.html?pear");
737             sampler.setDomain("www.apache.org");
738             assertEquals(
739                 "http://www.apache.org/index.html?pear",
740                 sampler.getUrl().toString());
741         }
742
743         public void testMakingUrl() throws Exception JavaDoc
744         {
745             HTTPSampler config= new HTTPSampler();
746             config.setProtocol("http");
747             config.setMethod(GET);
748             config.addArgument("param1", "value1");
749             config.setPath("/index.html");
750             config.setDomain("www.apache.org");
751             assertEquals(
752                 "http://www.apache.org/index.html?param1=value1",
753                 config.getUrl().toString());
754         }
755         public void testMakingUrl2() throws Exception JavaDoc
756         {
757             HTTPSampler config= new HTTPSampler();
758             config.setProtocol("http");
759             config.setMethod(GET);
760             config.addArgument("param1", "value1");
761             config.setPath("/index.html?p1=p2");
762             config.setDomain("www.apache.org");
763             assertEquals(
764                 "http://www.apache.org/index.html?param1=value1&p1=p2",
765                 config.getUrl().toString());
766         }
767         public void testMakingUrl3() throws Exception JavaDoc
768         {
769             HTTPSampler config= new HTTPSampler();
770             config.setProtocol("http");
771             config.setMethod(POST);
772             config.addArgument("param1", "value1");
773             config.setPath("/index.html?p1=p2");
774             config.setDomain("www.apache.org");
775             assertEquals(
776                 "http://www.apache.org/index.html?p1=p2",
777                 config.getUrl().toString());
778         }
779
780         // test cases for making Url, and exercise method
781
// addArgument(String name,String value,String metadata)
782

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

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