1 30 package org.apache.commons.httpclient.contrib.benchmark; 31 32 import java.io.IOException ; 33 import java.io.InputStream ; 34 35 import org.apache.commons.httpclient.Header; 36 import org.apache.commons.httpclient.HostConfiguration; 37 import org.apache.commons.httpclient.HttpClient; 38 import org.apache.commons.httpclient.HttpException; 39 import org.apache.commons.httpclient.HttpMethod; 40 41 48 public class BenchmarkWorker { 49 50 private byte[] buffer = new byte[4096]; 51 private final int verbosity; 52 private final HttpClient httpexecutor; 53 54 public BenchmarkWorker(final HttpClient httpexecutor, int verbosity) { 55 super(); 56 this.httpexecutor = httpexecutor; 57 this.verbosity = verbosity; 58 } 59 60 public Stats execute( 61 final HostConfiguration hostconf, 62 final HttpMethod method, 63 int count, 64 boolean keepalive) throws HttpException { 65 Stats stats = new Stats(); 66 stats.start(); 67 for (int i = 0; i < count; i++) { 68 try { 69 this.httpexecutor.executeMethod(hostconf, method); 70 if (this.verbosity >= 4) { 71 System.out.println(">> " + method.getName() + " " + 72 method.getURI() + " " + method.getParams().getVersion()); 73 Header[] headers = method.getRequestHeaders(); 74 for (int h = 0; h < headers.length; h++) { 75 System.out.print(">> " + headers[h].toString()); 76 } 77 System.out.println(); 78 } 79 if (this.verbosity >= 3) { 80 System.out.println(method.getStatusLine().getStatusCode()); 81 } 82 if (this.verbosity >= 4) { 83 System.out.println("<< " + method.getStatusLine().toString()); 84 Header[] headers = method.getResponseHeaders(); 85 for (int h = 0; h < headers.length; h++) { 86 System.out.print("<< " + headers[h].toString()); 87 } 88 System.out.println(); 89 } 90 InputStream instream = method.getResponseBodyAsStream(); 91 long contentlen = 0; 92 if (instream != null) { 93 int l = 0; 94 while ((l = instream.read(this.buffer)) != -1) { 95 stats.incTotal(l); 96 contentlen += l; 97 } 98 } 99 stats.setContentLength(contentlen); 100 stats.incSuccessCount(); 101 } catch (IOException ex) { 102 stats.incFailureCount(); 103 if (this.verbosity >= 2) { 104 System.err.println("I/O error: " + ex.getMessage()); 105 } 106 } finally { 107 method.releaseConnection(); 108 } 109 if (!keepalive) { 110 this.httpexecutor.getHttpConnectionManager().closeIdleConnections(0); 111 } 112 } 113 stats.finish(); 114 Header header = method.getResponseHeader("Server"); 115 if (header != null) { 116 stats.setServerName(header.getValue()); 117 } 118 return stats; 119 } 120 121 } 122 | Popular Tags |