adding all of botlist, initial add
[botlist.git] / openbotlist / tests / system / loadhttptest / src / org / spirit / loadtest / LoadTestManager.java
bloba3bcc841d10dabe98a26f3a7a1ede0e08244c9ee
1 /*-----------------------------------------------
2 * Berlin Brown
3 * Created on Apr 13, 2007
4 * Released under a BSD style license
6 * LoadTestManager.java
8 * -- Notes ---------------------------
9 * Two classes needed to compile, LoadTestManager and
10 * LoadTestManagerThread.
12 * -- Todo ----------------------------
13 * Finish SSL support and login functionality.
14 * Add socket based connect functionality (for finer grain testing)
16 *-----------------------------------------------
18 package org.spirit.loadtest;
20 import java.io.BufferedReader;
21 import java.io.BufferedWriter;
22 import java.io.File;
23 import java.io.FileInputStream;
24 import java.io.FileReader;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.InputStreamReader;
29 import java.io.OutputStreamWriter;
30 import java.net.HttpURLConnection;
31 import java.net.MalformedURLException;
32 import java.net.URL;
33 import java.net.URLConnection;
34 import java.net.URLEncoder;
35 import java.security.KeyManagementException;
36 import java.security.NoSuchAlgorithmException;
37 import java.security.cert.CertificateException;
38 import java.security.cert.X509Certificate;
39 import java.util.ArrayList;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Properties;
45 import javax.net.ssl.HostnameVerifier;
46 import javax.net.ssl.HttpsURLConnection;
47 import javax.net.ssl.KeyManager;
48 import javax.net.ssl.SSLContext;
49 import javax.net.ssl.SSLSession;
50 import javax.net.ssl.SSLSocketFactory;
51 import javax.net.ssl.TrustManager;
52 import javax.net.ssl.X509TrustManager;
54 /**
55 * Simple HTTP Load Test framework, create the property file with the following
56 * key values and launch the application to get status code and response time
57 * information. This is not a replacement for Grinder or any of the other
58 * frameworks. Two simple classes for quickly evaluating a set of links.
60 * Example Property Settings, in the testclient.properties property file:
62 * enable.proxy=true -- Enable Proxying proxy.host=theproxy -- Proxy Host
63 * proxy.port=9999 -- Proxy Port test.url = http://localhost:8080/ -- Test URL
64 * number.requests = 1 -- Number of Requests sleep = 100 -- Sleep time between
65 * requests (in ms) thread.count = 1 -- Number of threads to launch debug =
66 * false -- Enable debug information use.logfile = true -- Enable a logfile
67 * logfile = output/loadtest.log -- Log File to write to use.datafile = true --
68 * Enable an input data file (enable set of URLs) datafile = testurldata.dat --
69 * Input data file to use (text file with set of URLs)
71 public class LoadTestManager {
73 public static String PROPERTY_FILE = "testclient.properties";
75 public static final int MAX_LOG_RESULT_TUPLE = 5;
77 public static final String SYSTEM_DIRS[] = { "data", "data/html", "data/logs", "cookies", "output" };
79 public static final int MAX_LINE_MESSAGES = 40;
81 public static final int MAX_HEADER_THRES = 60;
83 public static final String DEFAULT_USER_AGENT_IE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1)";
85 private int numberThreads = 1;
87 private int threadSleepTime = 200;
89 // lines write = number of requests
90 private int linesWrite = 10;
92 private boolean propertiesLoaded = false;
94 private String defaultUserAgent = DEFAULT_USER_AGENT_IE;
96 private String testURL = "http://localhost";
98 private boolean useSynchronized = false;
100 private boolean sslEnabled = false;
102 private boolean login = false;
104 private String username = "user";
106 private String password = "abc";
108 private boolean debugEnabled = false;
110 private boolean sequencesEnabled = false;
112 private String sequenceFile = "data/sequence_requests.dat";
114 private boolean useLogFile = false;
116 private String logFile = "data/loadtest_local.txt";
118 private BufferedWriter testBufferWriter = null;
120 private boolean useDataFile = false;
122 private String dataFile = "testurldata.dat";
124 private int numberOfRequests = 0;
126 private long totalTime = 0;
128 private boolean enableProxy = false;
130 private String proxyHost = "theproxy";
132 private String proxyPort = "8080";
134 private boolean validateXHTMLEnabled = false;
136 private LoadTestHtmlOutput htmlOutput = new LoadTestHtmlOutput().setEnabled(true);
139 * Singleton Object, Load Test Manager.
141 private static LoadTestManager client;
143 public static final boolean safeStringToBoolean(final String bstr) {
144 if ((bstr == null) || (bstr.length() == 0)) {
145 return false;
146 } else {
147 return Boolean.valueOf(bstr).booleanValue();
148 } // End of the If
150 public static LoadTestManager getTestClient() {
151 if (client == null) {
152 client = new LoadTestManager();
153 // Load the news reader properties
154 Properties properties = new Properties();
155 try {
156 System.out.println("Loading " + PROPERTY_FILE);
157 properties.load(new FileInputStream(PROPERTY_FILE));
159 String userAgent = properties.getProperty("user.agent") != null ? properties.getProperty("user.agent")
160 .trim() : DEFAULT_USER_AGENT_IE;
161 String url = properties.getProperty("test.url") != null ? properties.getProperty("test.url").trim()
162 : "http://localhost";
163 int iLines = Integer.parseInt(properties.getProperty("number.requests") != null ? properties
164 .getProperty("number.requests").trim() : "10");
165 int iSleep = Integer.parseInt(properties.getProperty("sleep") != null ? properties.getProperty("sleep")
166 .trim() : "200");
167 int iThreads = Integer.parseInt(properties.getProperty("thread.count") != null ? properties
168 .getProperty("thread.count").trim() : "1");
169 boolean sync = Boolean.valueOf(
170 properties.getProperty("use.synchronized") != null ? properties.getProperty("use.synchronized")
171 .trim() : "false").booleanValue();
172 boolean debug = Boolean.valueOf(
173 properties.getProperty("debug") != null ? properties.getProperty("debug").trim() : "false")
174 .booleanValue();
176 boolean ssl = Boolean.valueOf(
177 properties.getProperty("ssl.enabled") != null ? properties.getProperty("ssl.enabled").trim()
178 : "" + client.isSslEnabled()).booleanValue();
179 // Load the sequences enabled data
180 boolean sequences_enabled = Boolean.valueOf(
181 properties.getProperty("sequences.enabled") != null ? properties.getProperty(
182 "sequences.enabled").trim() : "" + client.isSequencesEnabled()).booleanValue();
184 boolean log = Boolean.valueOf(
185 properties.getProperty("login") != null ? properties.getProperty("login").trim() : ""
186 + client.isLogin()).booleanValue();
187 String username = properties.getProperty("username") != null ? properties.getProperty("username")
188 .trim() : client.getUsername();
189 String password = properties.getProperty("password") != null ? properties.getProperty("password")
190 .trim() : client.getPassword();
192 boolean use_logfile = Boolean.valueOf(
193 properties.getProperty("use.logfile") != null ? properties.getProperty("use.logfile").trim()
194 : "" + client.isUseLogFile()).booleanValue();
195 String logfile = properties.getProperty("logfile") != null ? properties.getProperty("logfile").trim()
196 : client.getLogFile();
198 boolean use_datafile = Boolean.valueOf(
199 properties.getProperty("use.datafile") != null ? properties.getProperty("use.datafile").trim()
200 : "" + client.isUseDataFile()).booleanValue();
201 String data_file = properties.getProperty("datafile") != null ? properties.getProperty("datafile")
202 .trim() : client.getDataFile();
204 String proxy_host = properties.getProperty("proxy.host") != null ? properties.getProperty("proxy.host")
205 .trim() : "localhost";
206 String proxy_port = properties.getProperty("proxy.port") != null ? properties.getProperty("proxy.port")
207 .trim() : "8080";
209 String enable_proxy = properties.getProperty("enable.proxy") != null ? properties.getProperty(
210 "proxy.port").trim() : "false";
211 boolean hasProxy = Boolean.valueOf(enable_proxy).booleanValue();
213 String enable_xhtml_validate = properties.getProperty("enable.xhtml.validate") != null
214 ? properties.getProperty("enable.xhtml.validate").trim() : "false";
215 //*******************************
216 // Set the client properties
217 //*******************************
218 client.setValidateXHTMLEnabled(Boolean.valueOf(enable_xhtml_validate).booleanValue());
219 client.setTestURL(url).setDefaultUserAgent(userAgent).setLinesWrite(iLines);
220 client.setThreadSleepTime(iSleep).setUseSynchronized(sync).setNumberThreads(iThreads);
222 client.setSslEnabled(ssl).setLogin(log).setUsername(username).setPassword(password);
223 client.setDebugEnabled(debug);
225 client.setUseLogFile(use_logfile).setLogFile(logfile);
227 client.setDataFile(data_file);
228 client.setUseDataFile(use_datafile);
230 client.setSequencesEnabled(sequences_enabled);
231 // If sequence files are enabled, disable the url data file
232 if (client.isSequencesEnabled()) {
233 System.out.println("INFO: sequences enabled");
234 //client.setUseDataFile(false);
236 client.setProxyHost(proxy_host).setProxyPort(proxy_port).setEnableProxy(hasProxy);
238 if (client.isUseLogFile()) {
239 BufferedWriter errorout = new BufferedWriter(new FileWriter(client.getLogFile(), false));
240 client.setTestBufferWriter(errorout);
243 } catch (IOException e) {
244 client.setPropertiesLoaded(false);
245 e.printStackTrace();
246 throw new RuntimeException("Invalid Properties File");
249 return client;
252 public static void prettyPrintTrimData(final String data, final int maxLen) {
253 String res = "";
254 if (data != null) {
255 if (data.length() > maxLen) {
256 res = data.substring(0, maxLen) + "...";
257 } else {
258 res = data;
260 } else {
261 res = "";
263 System.out.println(res);
266 public static void log(long diff, String[] responseTuple, String url) {
267 String smsg = responseTuple[1].length() < MAX_LINE_MESSAGES ? responseTuple[1] : "";
268 String errmsg = responseTuple[2].length() < MAX_LINE_MESSAGES ? responseTuple[2] : "";
269 //*******************
270 // Create Tab Delimited File (url, no, response-time, status-code,
271 // message, errmsg)
272 //*******************
273 final StringBuffer logLine = new StringBuffer();
274 logLine.append("url=").append(url).append("\tno=");
275 logLine.append((getTestClient().getNumberOfRequests()) + "\trtime=" + diff + "\tcode=");
276 logLine.append(responseTuple[0]).append("\tmessage=[" + smsg + "]").append("\terrmsg=[" + errmsg + "]");
278 String additional_msg = "";
279 boolean valid_xhtml = false;
280 //*****************************
281 // TODO: fix me
282 // Add additional response tuple values
283 //*****************************
284 if (responseTuple.length >= LoadTestManager.MAX_LOG_RESULT_TUPLE) {
285 additional_msg = responseTuple[3];
286 valid_xhtml = LoadTestManager.safeStringToBoolean(responseTuple[4]);
288 //*************************
289 // Add the information about this request for later use.
290 //*************************
291 getTestClient().getHtmlOutput().addRequest(Thread.currentThread().getName(), url, (int) diff, responseTuple[0], additional_msg, valid_xhtml);
292 try {
293 //*************************
294 // Also, add additional message to log output
295 //*************************
296 getTestClient().writeLogFile(logLine + "\n");
297 } catch (IOException e) {
298 System.out.println("ERR: error writing to logfile - " + getTestClient().getLogFile());
299 e.printStackTrace();
303 public static Object[] loadDataFile(final String filename) {
304 List lData = new ArrayList();
305 String feed = null;
306 BufferedReader in = null;
307 try {
308 in = new BufferedReader(new FileReader(filename));
309 while ((feed = in.readLine()) != null) {
310 feed = feed.trim();
311 if ((feed != null) && (!feed.startsWith("#")) && (feed.length() > 2)) {
312 lData.add(feed);
314 } // End of the While
315 } catch (Exception e) {
316 e.printStackTrace();
317 } finally {
318 if (in != null) {
319 try {
320 in.close();
321 } catch (IOException e) {
325 return lData.toArray();
328 public static void printHeaderInfo(URLConnection conn) {
329 if (getTestClient().debugEnabled) {
330 // Debugging (where 50 equals some arbitrary number of headers)
331 for (int i = 0; i < MAX_HEADER_THRES; i++) {
332 String headerval = conn.getHeaderField(i);
333 if (headerval == null)
334 break;
335 System.out.println(" header# " + conn.getHeaderFieldKey(i) + " = " + conn.getHeaderField(i));
340 public static String[] connectURL(final String fullURL, final boolean loadExistingCookies) {
341 String[] tuple = new String[3];
342 tuple[0] = "";
343 tuple[1] = "";
344 tuple[2] = "";
345 HttpURLConnection conn = null;
346 try {
347 System.getProperties().put("http.agent", getTestClient().getDefaultUserAgent());
348 System.getProperties().put("proxySet", "" + getTestClient().isEnableProxy());
349 System.getProperties().put("proxyHost", getTestClient().getProxyHost());
350 System.getProperties().put("proxyPort", getTestClient().getProxyPort());
352 URL url = new URL(fullURL);
353 // Read all the text returned by the server
354 conn = (HttpURLConnection) url.openConnection();
355 LoadTestCookieManager cookieManager = new LoadTestCookieManager();
356 setReadCookieData(cookieManager, conn, url.getHost(), loadExistingCookies);
358 BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
359 printHeaderInfo(conn);
360 cookieManager.parseCookieData(conn, url.getHost(), loadExistingCookies);
361 cookieManager.writeCookieData();
363 String str;
364 StringBuffer buf = new StringBuffer(500);
365 while ((str = in.readLine()) != null) {
366 buf.append(str);
369 //**************
370 // Write the html document to the cache directory (filesystem), similar to a browser
371 //**************
372 LoadTestWriteHtmlDoc.writeOutput("data/html/"
373 + LoadTestWriteHtmlDoc.generatedHtmlFilename(fullURL) + ".html", buf.toString());
375 in.close();
376 tuple[0] = "" + conn.getResponseCode();
377 tuple[1] = buf.toString();
378 if (getTestClient().isDebugEnabled()) {
379 LoadTestManager.prettyPrintTrimData("[" + conn.getResponseCode() + "] Data Returned=" + buf.toString(),
380 MAX_HEADER_THRES);
383 } catch (MalformedURLException me) {
384 me.printStackTrace();
385 } catch (IOException e) {
386 System.out.println("ERR: IOException error=" + e.getMessage());
387 if (conn != null) {
388 try {
389 if (conn != null) {
390 String errContent = readInputStream(new BufferedReader(
391 new InputStreamReader(((HttpURLConnection) conn).getErrorStream())));
392 tuple[2] = errContent;
394 tuple[0] = "" + conn.getResponseCode();
395 tuple[1] = conn.getResponseMessage();
396 } catch (IOException ie) {
399 e.printStackTrace();
401 return tuple;
403 // ===============================================================
404 // SSL Utilities
405 // ===============================================================
406 public static URL getSSLURL(final String urlString) throws IOException {
407 URL url = null;
408 try {
409 url = new URL(urlString);
410 } catch (MalformedURLException e1) {
411 e1.printStackTrace();
413 // make untrusted SSL certificates work
414 if (url.getProtocol().equals("https")) {
415 try {
416 // System.setProperty("java.protocol.handler.pkgs",
417 // "com.ibm.net.ssl.internal.www.protocol");
418 // TODO: May need a provider here
419 // Security.addProvider(new com.ibm.jsse.IBMJSSEProvider());
421 javax.net.ssl.SSLSocketFactory sf = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory
422 .getDefault();
423 javax.net.ssl.SSLSocket sock = null;
424 X509TrustManager tm = new MyX509TrustManager();
425 HostnameVerifier hm = new MyHostnameVerifier();
426 KeyManager[] km = null;
427 TrustManager[] tma = { tm };
428 SSLContext sc = SSLContext.getInstance("SSL");
429 sc.init(km, tma, new java.security.SecureRandom());
430 SSLSocketFactory sf1 = sc.getSocketFactory();
432 HttpsURLConnection.setDefaultSSLSocketFactory(sf1);
433 HttpsURLConnection.setDefaultHostnameVerifier(hm);
434 } catch (KeyManagementException e) {
435 IOException e2 = new IOException();
436 e2.initCause(e);
437 throw e2;
438 } catch (NoSuchAlgorithmException e) {
439 IOException e2 = new IOException();
440 e2.initCause(e);
441 throw e2;
444 return url;
447 public static void setReadCookieData(LoadTestCookieManager cookieManager, HttpURLConnection conn,
448 final String hostname, final boolean loadExistingCookies) {
449 // If cookies enabled, load them in this request.
450 if (loadExistingCookies) {
451 cookieManager.readCookieData(hostname);
452 String cookieData = cookieManager.getIncomingCookieData(hostname);
453 if ((cookieData != null) && (cookieData.length() > 0)) {
454 conn.setRequestProperty("Cookie", cookieData);
457 // Also set the referer
458 String referer = cookieManager.getRefererUrl();
459 if ((referer != null) && (referer.length() > 0)) {
460 System.out.println("INFO!! Setting Referer for connection=" + referer);
461 conn.setRequestProperty("Referer", referer);
465 public static String[] connectURLSSL(String fullURL, final boolean loadExistingCookies) {
466 HttpURLConnection conn = null;
467 String[] tuple = new String[3];
468 tuple[0] = "";
469 tuple[1] = "";
470 tuple[2] = "";
471 try {
472 System.getProperties().put("http.agent", getTestClient().getDefaultUserAgent());
473 URL url = getSSLURL(fullURL);
474 conn = (HttpsURLConnection) url.openConnection();
476 boolean followRedirects = false;
477 HttpURLConnection.setFollowRedirects(followRedirects);
478 LoadTestCookieManager cookieManager = new LoadTestCookieManager();
479 setReadCookieData(cookieManager, conn, url.getHost(), loadExistingCookies);
481 // Updated modification, set the referer URL
482 cookieManager.queueRefererUrl(fullURL);
483 conn.setDoInput(true);
484 printHeaderInfo(conn);
485 // Load the cookie manager to write content
486 cookieManager.parseCookieData(conn, url.getHost(), loadExistingCookies);
487 cookieManager.writeCookieData();
489 // Read all the text returned by the server
490 InputStream inStream = conn.getInputStream();
491 System.out.println("DEBUG: inputstream available=" + inStream.available());
492 // TODO: test, is this correct, changed getInputStream from open
493 // stream
494 BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
495 String str;
496 StringBuffer buf = new StringBuffer(500);
497 while ((str = in.readLine()) != null) {
498 buf.append(str);
500 //**************
501 // Write the html document to the cache directory (filesystem), similar to a browser
502 //**************
503 LoadTestWriteHtmlDoc.writeOutput("data/html/"
504 + LoadTestWriteHtmlDoc.generatedHtmlFilename(fullURL) + ".html", buf.toString());
505 in.close();
506 System.out.println("INFO: SSL content:");
507 prettyPrintTrimData(buf.toString(), 40);
509 // Also handle redirects outside of Java's implementation
510 int statusCode = conn.getResponseCode();
511 if (!followRedirects) {
512 if (statusCode == 302) {
513 String newLocation = conn.getHeaderField("Location");
514 System.out.println("INFO: following redirect to=" + newLocation);
515 tuple = connectURLSSL(newLocation, loadExistingCookies);
519 } catch (MalformedURLException me) {
520 me.printStackTrace();
521 } catch (IOException e) {
522 e.printStackTrace();
524 return tuple;
527 public static String [] postDataSSL(Map mapData, HttpURLConnection conn, URL url, final String fullURL,
528 final boolean followRedirects, final boolean loadExistingCookies) {
529 OutputStreamWriter wr = null;
530 BufferedReader rd = null;
531 String[] tuple = new String[3];
532 tuple[0] = "";
533 tuple[1] = "";
534 tuple[2] = "";
535 try {
536 // Construct data
537 String data = "";
538 for (Iterator it = mapData.keySet().iterator(); it.hasNext();) {
539 String key = (String) it.next();
540 String keyValue = (String) mapData.get(key);
541 if (data.length() != 0)
542 data += "&";
543 data += URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(keyValue, "UTF-8");
545 conn.setDoOutput(true);
546 conn.setDoInput(true);
547 LoadTestCookieManager cookieManager = new LoadTestCookieManager();
548 setReadCookieData(cookieManager, conn, url.getHost(), loadExistingCookies);
550 wr = new OutputStreamWriter(conn.getOutputStream());
551 wr.write(data);
552 wr.flush();
554 // Get the response
555 InputStream inStream = conn.getInputStream();
556 System.out.println("DEBUG: inputstream available=" + inStream.available());
557 rd = new BufferedReader(new InputStreamReader(inStream));
558 printHeaderInfo(conn);
560 // Load the cookie manager to write content
561 cookieManager.parseCookieData(conn, url.getHost(), loadExistingCookies);
562 cookieManager.writeCookieData();
564 String line;
565 StringBuffer buf = new StringBuffer();
566 while ((line = rd.readLine()) != null) {
567 buf.append(line);
570 //**************
571 // Write the html document to the cache directory (filesystem), similar to a browser
572 //**************
573 LoadTestWriteHtmlDoc.writeOutput("data/html/"
574 + LoadTestWriteHtmlDoc.generatedHtmlFilename(fullURL) + ".html", buf.toString());
576 wr.flush();
577 rd.close();
578 wr.close();
580 int statusCode = conn.getResponseCode();
581 LoadTestManager.prettyPrintTrimData("[" + statusCode + "] Data Returned=" + buf.toString(),
582 MAX_HEADER_THRES);
584 // Also handle redirects outside of Java's implementation
585 if (!followRedirects) {
586 if (statusCode == 302) {
587 String newLocation = conn.getHeaderField("Location");
588 System.out.println("INFO: following redirect to=" + newLocation);
589 connectURLSSL(newLocation, loadExistingCookies);
593 tuple[0] = "" + statusCode;
594 tuple[1] = buf.toString();
596 } catch (Exception e) {
597 System.out.println("* ERR: while connecting = connectWithURL()");
598 e.printStackTrace();
599 try {
600 // Clear the error response buffer.
601 if (conn != null) {
602 String errContent = readInputStream(new BufferedReader(new InputStreamReader(
603 ((HttpURLConnection) conn).getErrorStream())));
604 System.err.println(errContent);
605 System.err.println("* Done with error response body");
607 } catch (IOException e1) {
608 e1.printStackTrace();
610 } finally {
611 if (rd != null)
612 try {
613 rd.close();
614 } catch (IOException e2) {
615 e2.printStackTrace();
618 if (wr != null)
619 try {
620 wr.close();
621 } catch (IOException e1) {
626 return tuple;
629 // == End of SSL Utilities =================================================
632 * Ensure that 'data' and 'data/log' directories are created and/or
633 * validated.
635 private static void verifySystemDirs() {
636 for (int i = 0; i < SYSTEM_DIRS.length; i++) {
637 File f = new File(SYSTEM_DIRS[i]);
638 System.out.print(" verifying system file=" + f.getName());
639 if (f.exists()) {
640 System.out.print(" [ exists ]");
641 } else {
642 System.out.print(" [ not found, creating ] ");
643 boolean res = f.mkdirs();
644 System.out.print(res);
646 System.out.println();
650 private static String readInputStream(BufferedReader br) throws IOException {
651 String line = null;
652 StringBuffer buf = new StringBuffer();
653 // read the response body
654 while ((line = br.readLine()) != null) {
655 buf.append(line);
657 // close the errorstream
658 br.close();
659 return buf.toString();
662 public static void init() {
663 System.out.println("running...servlet log client");
664 getTestClient();
667 public static void shutdown() throws Exception {
668 System.out.println("-------------------------------");
669 System.out.println(" * Total Requests=" + getTestClient().getNumberOfRequests());
670 System.out.println(" * Total Time=" + getTestClient().getTotalTime());
671 System.out.println("-------------------------------");
672 log();
673 getTestClient().closeLogFile();
674 getTestClient().getHtmlOutput().writeOutput();
677 private static void log() {
678 // Create Tab Delimited File for response time
679 String logLine = "url=" + "TOTAL_REQUESTS" + "\tno=" + getTestClient().getNumberOfRequests() + "\trtime="
680 + getTestClient().getTotalTime() + "\tcode=" + -1 + "\tmessage=[]" + "\terrmsg=[]";
681 try {
682 getTestClient().writeLogFile(logLine + "\r\n");
683 } catch (IOException e) {
684 System.out.println("ERR: error writing to logfile - " + getTestClient().getLogFile());
685 e.printStackTrace();
689 // =====================================================
690 // Bean Methods
691 // =====================================================
693 protected void incNumberOfRequests() {
694 this.numberOfRequests++;
697 protected void incTotalTime(long time) {
698 this.totalTime += time;
701 protected void writeLogFile(String line) throws IOException {
702 if (this.testBufferWriter != null) {
703 this.testBufferWriter.write(line);
707 protected void closeLogFile() throws IOException {
708 if (this.testBufferWriter != null) {
709 this.testBufferWriter.flush();
710 this.testBufferWriter.close();
714 public boolean isValidateXHTMLEnabled() {
715 return validateXHTMLEnabled;
718 public LoadTestManager setValidateXHTMLEnabled(boolean validateXHTMLEnabled) {
719 this.validateXHTMLEnabled = validateXHTMLEnabled;
720 return this;
724 * @return
726 public int getLinesWrite() {
727 return linesWrite;
731 * @return
733 public int getNumberThreads() {
734 return numberThreads;
738 * @return
740 public boolean isPropertiesLoaded() {
741 return propertiesLoaded;
745 * @return
747 public int getThreadSleepTime() {
748 return threadSleepTime;
752 * @param i
753 * @return
755 public LoadTestManager setLinesWrite(int i) {
756 linesWrite = i;
757 return this;
761 * @param i
762 * @return
764 public LoadTestManager setNumberThreads(int i) {
765 numberThreads = i;
766 return this;
770 * @param b
772 public void setPropertiesLoaded(boolean b) {
773 propertiesLoaded = b;
777 * @param i
778 * @return
780 public LoadTestManager setThreadSleepTime(int i) {
781 threadSleepTime = i;
782 return this;
786 * @return
788 public String getDefaultUserAgent() {
789 return defaultUserAgent;
793 * @param string
795 public LoadTestManager setDefaultUserAgent(String string) {
796 defaultUserAgent = string;
797 return this;
801 * @return
803 public String getTestURL() {
804 return testURL;
808 * @param string
810 public LoadTestManager setTestURL(String string) {
811 testURL = string;
812 return this;
816 * @return
818 public boolean isUseSynchronized() {
819 return useSynchronized;
823 * @param b
824 * @return
826 public LoadTestManager setUseSynchronized(boolean b) {
827 useSynchronized = b;
828 return this;
832 * @return
834 public String getUsername() {
835 return username;
839 * @param string
840 * @return
842 public LoadTestManager setUsername(String string) {
843 username = string;
844 return this;
848 * @return
850 public String getPassword() {
851 return password;
855 * @param string
856 * @return
858 public LoadTestManager setPassword(String string) {
859 password = string;
860 return this;
864 * @return
866 public boolean isSslEnabled() {
867 return sslEnabled;
871 * @param b
873 public LoadTestManager setSslEnabled(boolean b) {
874 sslEnabled = b;
875 return this;
879 * @return
881 public boolean isLogin() {
882 return login;
886 * @param b
888 public LoadTestManager setLogin(boolean b) {
889 login = b;
890 return this;
894 * @return
896 public boolean isDebugEnabled() {
897 return debugEnabled;
901 * @param b
903 public void setDebugEnabled(boolean b) {
904 debugEnabled = b;
908 * @return
910 public int getNumberOfRequests() {
911 return numberOfRequests;
915 * @param i
917 public void setNumberOfRequests(int i) {
918 numberOfRequests = i;
922 * @return
924 public long getTotalTime() {
925 return totalTime;
929 * @param l
931 public void setTotalTime(long l) {
932 totalTime = l;
936 * @return
938 public boolean isUseLogFile() {
939 return useLogFile;
943 * @param b
944 * @return
946 public LoadTestManager setUseLogFile(boolean b) {
947 useLogFile = b;
948 return this;
952 * @return
954 public String getLogFile() {
955 return logFile;
959 * @param string
960 * @return
962 public LoadTestManager setLogFile(String string) {
963 logFile = string;
964 return this;
967 public BufferedWriter getTestBufferWriter() {
968 return testBufferWriter;
971 public void setTestBufferWriter(BufferedWriter writer) {
972 testBufferWriter = writer;
975 public boolean isEnableProxy() {
976 return enableProxy;
979 public LoadTestManager setEnableProxy(boolean b) {
980 enableProxy = b;
981 return this;
984 public LoadTestManager setProxyHost(String string) {
985 proxyHost = string;
986 return this;
989 public LoadTestManager setProxyPort(String string) {
990 proxyPort = string;
991 return this;
994 public boolean isSequencesEnabled() {
995 return sequencesEnabled;
998 public LoadTestManager setSequencesEnabled(boolean sequencesEnabled) {
999 this.sequencesEnabled = sequencesEnabled;
1000 return this;
1003 public String getProxyHost() {
1004 return proxyHost;
1007 public String getProxyPort() {
1008 return proxyPort;
1011 public String getDataFile() {
1012 return dataFile;
1015 public boolean isUseDataFile() {
1016 return useDataFile;
1019 public void setDataFile(String string) {
1020 dataFile = string;
1023 public String getSequenceFile() {
1024 return sequenceFile;
1027 public void setSequenceFile(String sequenceFile) {
1028 this.sequenceFile = sequenceFile;
1031 public void setUseDataFile(boolean b) {
1032 useDataFile = b;
1035 public static Object[] loadTextFile(final String filename) {
1036 List lData = new ArrayList();
1037 String feed = null;
1038 BufferedReader in = null;
1039 try {
1040 in = new BufferedReader(new FileReader(filename));
1041 while ((feed = in.readLine()) != null) {
1042 feed = feed.trim();
1043 if (feed != null) {
1044 lData.add(feed);
1046 } // End of the While
1047 } catch (Exception e) {
1048 e.printStackTrace();
1049 } finally {
1050 if (in != null) {
1051 try {
1052 in.close();
1053 } catch (IOException e) {
1057 return lData.toArray();
1060 public LoadTestHtmlOutput getHtmlOutput() {
1061 return htmlOutput;
1064 // =====================================================
1065 // Static Classes for SSL
1066 // =====================================================
1067 static class MyHostnameVerifier implements HostnameVerifier {
1068 public boolean verify(String urlHostname, SSLSession session) {
1069 return true;
1073 static class MyX509TrustManager implements X509TrustManager {
1074 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
1077 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
1080 public X509Certificate[] getAcceptedIssuers() {
1081 return new X509Certificate[0];
1085 // =====================================================
1086 // Main - Entry Point
1087 // =====================================================
1088 private static void launchThreads() throws InterruptedException {
1089 final int noThreads = getTestClient().getNumberThreads();
1090 Thread[] threadSet = new Thread[noThreads];
1091 for (int i = 0; i < getTestClient().getNumberThreads(); i++) {
1092 LoadTestManagerThread c = new LoadTestManagerThread(getTestClient());
1093 threadSet[i] = new Thread(c);
1094 threadSet[i].start();
1095 Thread.sleep(getTestClient().getThreadSleepTime());
1097 // Join all of threads just created.
1098 for (int i = 0; i < noThreads; ++i) {
1099 try {
1100 threadSet[i].join();
1101 } catch (InterruptedException e) {
1102 System.out.println("ERR: Join interrupted");
1107 private static void launchFromSequenceData() {
1108 LoadTestSequenceParser parser = new LoadTestSequenceParser();
1109 parser.parse(getTestClient().getSequenceFile());
1110 parser.printSummary();
1111 parser.handleSequence();
1114 public static void main(String[] args) throws Exception {
1115 if (args.length != 2) {
1116 System.out.println("Usage: LoadTestManager -f <test properties filename>");
1117 System.exit(-1);
1118 return;
1120 PROPERTY_FILE = args[1];
1121 verifySystemDirs();
1122 init();
1123 if (getTestClient().isUseDataFile()) {
1124 // Check for use data file first, with sequences taking lower priority
1125 launchThreads();
1126 } else if (getTestClient().isSequencesEnabled()) {
1127 launchFromSequenceData();
1128 } else {
1129 launchThreads();
1131 shutdown();
1134 // End of File