KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > httpclient > contrib > benchmark > HttpBenchmark


1 /*
2  * $HeadURL: https://svn.apache.org/repos/asf/jakarta/commons/proper/httpclient/trunk/src/contrib/org/apache/commons/httpclient/contrib/benchmark/HttpBenchmark.java $
3  * $Revision: 480424 $
4  * $Date: 2006-11-29 05:56:49 +0000 (Wed, 29 Nov 2006) $
5  *
6  * ====================================================================
7  *
8  * Licensed to the Apache Software Foundation (ASF) under one or more
9  * contributor license agreements. See the NOTICE file distributed with
10  * this work for additional information regarding copyright ownership.
11  * The ASF licenses this file to You under the Apache License, Version 2.0
12  * (the "License"); you may not use this file except in compliance with
13  * the License. You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ====================================================================
23  *
24  * This software consists of voluntary contributions made by many
25  * individuals on behalf of the Apache Software Foundation. For more
26  * information on the Apache Software Foundation, please see
27  * <http://www.apache.org/>.
28  *
29  */

30 package org.apache.commons.httpclient.contrib.benchmark;
31
32 import java.io.File JavaDoc;
33 import java.net.URL JavaDoc;
34
35 import org.apache.commons.cli.CommandLine;
36 import org.apache.commons.cli.CommandLineParser;
37 import org.apache.commons.cli.HelpFormatter;
38 import org.apache.commons.cli.Option;
39 import org.apache.commons.cli.Options;
40 import org.apache.commons.cli.PosixParser;
41 import org.apache.commons.httpclient.HostConfiguration;
42 import org.apache.commons.httpclient.HttpClient;
43 import org.apache.commons.httpclient.HttpMethod;
44 import org.apache.commons.httpclient.HttpVersion;
45 import org.apache.commons.httpclient.methods.FileRequestEntity;
46 import org.apache.commons.httpclient.methods.GetMethod;
47 import org.apache.commons.httpclient.methods.HeadMethod;
48 import org.apache.commons.httpclient.methods.PostMethod;
49 import org.apache.commons.httpclient.params.HttpMethodParams;
50
51 /**
52  * <p>A simple HTTP benchmark tool, which implements a subset of AB (Apache Benchmark) interface</p>
53  *
54  * @author <a HREF="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
55  *
56  * @version $Revision: 480424 $
57  */

58 public class HttpBenchmark {
59
60     private static HttpClient createRequestExecutor() {
61         HttpClient httpclient = new HttpClient();
62         httpclient.getParams().setVersion(HttpVersion.HTTP_1_1);
63         httpclient.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
64         httpclient.getHttpConnectionManager().getParams().setStaleCheckingEnabled(false);
65         return httpclient;
66     }
67     
68     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
69
70         Option iopt = new Option("i", false, "Do HEAD requests instead of GET.");
71         iopt.setRequired(false);
72         
73         Option kopt = new Option("k", false, "Enable the HTTP KeepAlive feature, " +
74                 "i.e., perform multiple requests within one HTTP session. " +
75                 "Default is no KeepAlive");
76         kopt.setRequired(false);
77         
78         Option nopt = new Option("n", true, "Number of requests to perform for the " +
79                 "benchmarking session. The default is to just perform a single " +
80                 "request which usually leads to non-representative benchmarking " +
81                 "results.");
82         nopt.setRequired(false);
83         nopt.setArgName("requests");
84         
85         Option popt = new Option("p", true, "File containing data to POST.");
86         popt.setRequired(false);
87         popt.setArgName("POST-file");
88
89         Option Topt = new Option("T", true, "Content-type header to use for POST data.");
90         Topt.setRequired(false);
91         Topt.setArgName("content-type");
92
93         Option vopt = new Option("v", true, "Set verbosity level - 4 and above prints " +
94                 "information on headers, 3 and above prints response codes (404, 200, " +
95                 "etc.), 2 and above prints warnings and info.");
96         vopt.setRequired(false);
97         vopt.setArgName("verbosity");
98
99         Option hopt = new Option("h", false, "Display usage information.");
100         nopt.setRequired(false);
101         
102         Options options = new Options();
103         options.addOption(iopt);
104         options.addOption(kopt);
105         options.addOption(nopt);
106         options.addOption(popt);
107         options.addOption(Topt);
108         options.addOption(vopt);
109         options.addOption(hopt);
110
111         if (args.length == 0) {
112             showUsage(options);
113             System.exit(1);
114         }
115         
116         CommandLineParser parser = new PosixParser();
117         CommandLine cmd = parser.parse(options, args);
118         
119         if (cmd.hasOption('h')) {
120             showUsage(options);
121             System.exit(1);
122         }
123         
124         int verbosity = 0;
125         if(cmd.hasOption('v')) {
126             String JavaDoc s = cmd.getOptionValue('v');
127             try {
128                 verbosity = Integer.parseInt(s);
129             } catch (NumberFormatException JavaDoc ex) {
130                 System.err.println("Invalid verbosity level: " + s);
131                 showUsage(options);
132                 System.exit(-1);
133             }
134         }
135         
136         boolean keepAlive = false;
137         if(cmd.hasOption('k')) {
138             keepAlive = true;
139         }
140         
141         int num = 1;
142         if(cmd.hasOption('n')) {
143             String JavaDoc s = cmd.getOptionValue('n');
144             try {
145                 num = Integer.parseInt(s);
146             } catch (NumberFormatException JavaDoc ex) {
147                 System.err.println("Invalid number of requests: " + s);
148                 showUsage(options);
149                 System.exit(-1);
150             }
151         }
152         
153         args = cmd.getArgs();
154         if (args.length != 1) {
155             showUsage(options);
156             System.exit(-1);
157         }
158         // Parse the target url
159
URL JavaDoc url = new URL JavaDoc(args[0]);
160         
161         // Prepare host configuration
162
HostConfiguration hostconf = new HostConfiguration();
163         hostconf.setHost(
164                 url.getHost(),
165                 url.getPort(),
166                 url.getProtocol());
167         
168         // Prepare request
169
HttpMethod method = null;
170         if (cmd.hasOption('p')) {
171             PostMethod httppost = new PostMethod(url.getPath());
172             File JavaDoc file = new File JavaDoc(cmd.getOptionValue('p'));
173             if (!file.exists()) {
174                 System.err.println("File not found: " + file);
175                 System.exit(-1);
176             }
177             String JavaDoc contenttype = null;
178             if (cmd.hasOption('T')) {
179                 contenttype = cmd.getOptionValue('T');
180             }
181             FileRequestEntity entity = new FileRequestEntity(file, contenttype);
182             httppost.setRequestEntity(entity);
183             if (file.length() > 100000) {
184                 httppost.setContentChunked(true);
185             }
186             method = httppost;
187         } else if (cmd.hasOption('i')) {
188             HeadMethod httphead = new HeadMethod(url.getPath());
189             method = httphead;
190         } else {
191             GetMethod httpget = new GetMethod(url.getPath());
192             method = httpget;
193         }
194         if (!keepAlive) {
195             method.addRequestHeader("Connection", "close");
196         }
197         
198         // Prepare request executor
199
HttpClient executor = createRequestExecutor();
200         BenchmarkWorker worker = new BenchmarkWorker(executor, verbosity);
201         
202         // Execute
203
Stats stats = worker.execute(hostconf, method, num, keepAlive);
204         
205         // Show the results
206
float totalTimeSec = (float)stats.getDuration() / 1000;
207         float reqsPerSec = (float)stats.getSuccessCount() / totalTimeSec;
208         float timePerReqMs = (float)stats.getDuration() / (float)stats.getSuccessCount();
209         
210         System.out.print("Server Software:\t");
211         System.out.println(stats.getServerName());
212         System.out.print("Server Hostname:\t");
213         System.out.println(hostconf.getHost());
214         System.out.print("Server Port:\t\t");
215         if (hostconf.getPort() > 0) {
216             System.out.println(hostconf.getPort());
217         } else {
218             System.out.println(hostconf.getProtocol().getDefaultPort());
219         }
220         System.out.println();
221         System.out.print("Document Path:\t\t");
222         System.out.println(method.getURI());
223         System.out.print("Document Length:\t");
224         System.out.print(stats.getContentLength());
225         System.out.println(" bytes");
226         System.out.println();
227         System.out.print("Time taken for tests:\t");
228         System.out.print(totalTimeSec);
229         System.out.println(" seconds");
230         System.out.print("Complete requests:\t");
231         System.out.println(stats.getSuccessCount());
232         System.out.print("Failed requests:\t");
233         System.out.println(stats.getFailureCount());
234         System.out.print("Content transferred:\t");
235         System.out.print(stats.getTotal());
236         System.out.println(" bytes");
237         System.out.print("Requests per second:\t");
238         System.out.print(reqsPerSec);
239         System.out.println(" [#/sec] (mean)");
240         System.out.print("Time per request:\t");
241         System.out.print(timePerReqMs);
242         System.out.println(" [ms] (mean)");
243     }
244
245     private static void showUsage(final Options options) {
246         HelpFormatter formatter = new HelpFormatter();
247         formatter.printHelp("HttpBenchmark [options] [http://]hostname[:port]/path", options);
248     }
249     
250 }
251
Popular Tags