1 17 package org.apache.jmeter.protocol.http.sampler; 18 19 import java.io.File ; 20 import java.io.FileInputStream ; 21 import java.io.IOException ; 22 import java.net.MalformedURLException ; 23 import java.net.URL ; 24 25 import java.util.Date ; 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 59 public class HTTPSampler2 extends HTTPSamplerBase 60 { 61 transient private static Logger log= LoggingManager.getLoggerForClass(); 62 63 static { 64 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 75 private transient HttpConnection httpConn = null; 76 77 81 private transient HttpMethodBase httpMethod = null; 82 private transient HttpState httpState = null; 83 84 87 public HTTPSampler2() 88 { 89 setArguments(new Arguments()); 90 } 91 92 98 private void setPostHeaders(PostMethod post) throws IOException 99 { 100 } 104 105 112 private void sendPostData(HttpMethod connection) throws IOException 113 { 114 115 sendPostData((PostMethod)connection, this); 116 } 117 118 121 public void sendPostData(PostMethod post, HTTPSampler2 sampler) 122 throws IOException 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 String filename = sampler.getFilename(); 132 if ((filename != null) && (filename.trim().length() > 0)) 133 { 134 File input = new File (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 post.setRequestHeader("Content-Disposition", 142 "form-data; name=\"" 143 + encode(sampler.getFileField()) 144 + "\"; filename=\"" 145 + encode(filename) 146 + "\""); 147 post.setRequestHeader("Content-Type", sampler.getMimetype()); 149 post.setRequestBody(new FileInputStream (input)); 150 } 151 } 152 153 private String encode(String value) 154 { 155 StringBuffer newValue = new StringBuffer (); 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 184 private HttpConnection setupConnection( 185 URL u, 186 String method, 187 HTTPSampleResult res) 188 throws IOException 189 { 190 191 String urlStr = u.toString(); 192 193 org.apache.commons.httpclient.URI 194 uri = new org.apache.commons.httpclient.URI(urlStr); 195 196 String schema = uri.getScheme(); 197 if ((schema == null) || (schema.equals(""))) 198 { 199 schema = "http"; 200 } 201 Protocol protocol = Protocol.getProtocol(schema); 202 203 String 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 } 212 else 213 { 214 httpConn = new HttpConnection(hc); 215 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 new DefaultMethodRetryHandler(); 229 } 230 231 httpMethod.setHttp11(!JMeterUtils.getPropDefault("httpclient.version","1.1").equals("1.0")); 232 233 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 httpMethod.setFollowRedirects(getPropertyAsBoolean(AUTO_REDIRECTS)); 243 244 if (getUseKeepAlive()) 249 { 250 httpMethod.setRequestHeader("Connection", "keep-alive"); 251 } 252 else 253 { 254 httpMethod.setRequestHeader("Connection", "close"); 255 } 256 257 String hdrs=setConnectionHeaders(httpMethod, u, getHeaderManager()); 258 String cookies= setConnectionCookie(httpMethod, u, getCookieManager()); 259 260 if (res != null) 261 { 262 StringBuffer sb= new StringBuffer (); 263 if (method.equals(POST)) 264 { 265 String 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 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 302 protected String getResponseHeaders(HttpMethod method) 303 throws IOException 304 { 305 StringBuffer headerBuf= new StringBuffer (); 306 org.apache.commons.httpclient.Header rh[] = method.getResponseHeaders(); 307 headerBuf.append(method.getStatusLine()); headerBuf.append("\n"); 309 310 for (int i= 0; i < rh.length; i++) 311 { 312 String key = rh[i].getName(); 313 if (!key.equalsIgnoreCase("transfer-encoding")) { 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 333 private String setConnectionCookie( 334 HttpMethod method, 335 URL u, 336 CookieManager cookieManager) 337 { 338 String 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 360 private String setConnectionHeaders( 361 HttpMethod method, 362 URL u, 363 HeaderManager headerManager) 364 { 365 StringBuffer hdrs = new StringBuffer (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 n=header.getName(); 377 String 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 398 private void setConnectionAuthorization( 399 HttpMethod method, 400 URL u, 401 AuthManager authManager) 402 { 403 if (authManager != null) 404 { 405 String authHeader= authManager.getAuthHeaderForURL(u); 407 if (authHeader != null) 408 { 409 method.setRequestHeader("Authorization", authHeader); 410 } 411 412 } 429 } 430 431 446 protected HTTPSampleResult sample( 447 URL url, 448 String method, 449 boolean areFollowingRedirect, 450 int frameDepth) 451 { 452 453 String 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(); 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 byte[] responseData= httpMethod.getResponseBody(); 482 483 res.sampleEnd(); 484 486 488 res.setSampleLabel(httpMethod.getURI().toString()); 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 ct=null; 497 org.apache.commons.httpclient.Header h = 498 httpMethod.getResponseHeader("Content-Type"); 499 if (h!=null) { 501 ct= h.getValue(); 502 res.setContentType(ct); } 504 if (ct != null) 505 { 506 String de=ct.toLowerCase(); 511 final String 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 saveConnectionCookies(httpState, getCookieManager()); 535 536 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 ("Maximum frame/iframe nesting depth exceeded."), 560 null, 561 0)); 562 } 563 else 564 { 565 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 e) { 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 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 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 location= encodeSpaces(lastRes.getRedirectLocation()); 625 try 629 { 630 lastRes= 631 sample( 632 new URL (lastRes.getURL(), location), 633 GET, 634 true, 635 frameDepth); 636 } 637 catch (MalformedURLException 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 ("Exceeeded maximum number of redirects: "+MAX_REDIRECTS), 653 null, 654 0); 655 totalRes.addSubResult(lastRes); 656 } 657 658 totalRes.setSampleLabel( 661 totalRes.getSampleLabel() + "->" + lastRes.getSampleLabel()); 662 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 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 exp = c[i].getExpiryDate(); 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 ) 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 726 public static class Test extends junit.framework.TestCase 727 { 728 public Test(String name) 729 { 730 super(name); 731 } 732 733 public void testArgumentWithoutEquals() throws Exception 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 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 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 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 785 public void testMakingUrl4() throws Exception 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 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 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 825 public void testMakingUrl7() throws Exception 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 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 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 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 |