KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > Webtest


1 /*
2 * CLIF is a Load Injection Framework
3 * Copyright (C) 2004 France Telecom R&D
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 *
19 * CLIF $Name: $
20 *
21 * Contact: clif@objectweb.org
22 */

23
24
25 import org.objectweb.clif.scenario.util.multithread.MTScenario;
26 import org.objectweb.clif.scenario.util.multithread.MTScenarioSession;
27 import org.objectweb.clif.storage.api.ActionEvent;
28 import org.objectweb.clif.util.ClifClassLoader;
29 import org.objectweb.clif.supervisor.api.ClifException;
30 import org.apache.commons.httpclient.HttpClient;
31 import org.apache.commons.httpclient.HttpMethod;
32 import org.apache.commons.httpclient.cookie.CookiePolicy;
33 import org.apache.commons.httpclient.methods.GetMethod;
34 import org.apache.commons.httpclient.methods.PostMethod;
35 import org.apache.log4j.BasicConfigurator;
36 import org.apache.log4j.varia.NullAppender;
37 import java.util.StringTokenizer JavaDoc;
38 import java.util.Map JavaDoc;
39 import java.util.HashMap JavaDoc;
40 import java.util.List JavaDoc;
41 import java.util.ArrayList JavaDoc;
42 import java.io.BufferedReader JavaDoc;
43 import java.io.InputStreamReader JavaDoc;
44 import java.io.Serializable JavaDoc;
45
46
47 /**
48  * Example of MTScenario utilization, with actions consisting in simple calls to sleep().
49  * The constructor String argument should contain 5 arguments: the three first arguments are
50  * those required for MTScenario constructor, and the two trailing arguments respectively
51  * give the think time in seconds between two HTTP requests (for each session), and the name
52  * of the file holding the list of URLs to visit. This URL list file should reside at a
53  * suitable location (typically in the base directory of the example class itself).
54  * <P>
55  * URLs file format:
56  * <UL>
57  * <LI>lines beginning with character '#' are ignored
58  * <LI>lines beginning with character 'p' or 'P' should contain a trailing http URL which will be
59  * loaded using an HTTP POST method
60  * <LI>other lines should contain a URL, which will be loaded using an HTTP GET method
61  * </UL>
62  * @author Bruno Dillenseger
63  */

64 public class Webtest extends MTScenario
65 {
66     static private Map JavaDoc urlsCache = new HashMap JavaDoc();
67
68
69     static // configure log4j before using HttpClient library
70
{
71         BasicConfigurator.configure(new NullAppender());
72     }
73
74
75     static protected synchronized void clearURLs()
76     {
77         urlsCache.clear();
78     }
79
80
81     static protected String JavaDoc[] initURLs(String JavaDoc filename)
82     {
83         String JavaDoc[] urls;
84         if (urlsCache.containsKey(filename))
85         {
86             urls = (String JavaDoc[])urlsCache.get(filename);
87         }
88         else
89         {
90             synchronized(urlsCache)
91             {
92                 if (urlsCache.containsKey(filename))
93                 {
94                     urls = (String JavaDoc[])urlsCache.get(filename);
95                 }
96                 else
97                 {
98                     try
99                     {
100                         List JavaDoc urlList = new ArrayList JavaDoc();
101                         BufferedReader JavaDoc br = new BufferedReader JavaDoc(
102                             new InputStreamReader JavaDoc(ClifClassLoader.getClassLoader().getResourceAsStream(filename)));
103                         String JavaDoc line = null;
104                         while ((line = br.readLine()) != null)
105                         {
106                             line = line.trim();
107                             if (! line.startsWith("#"))
108                             {
109                                 urlList.add(line);
110                             }
111                         }
112                         br.close();
113                         urls = (String JavaDoc[])urlList.toArray(new String JavaDoc[urlList.size()]);
114                         urlsCache.put(filename, urls);
115                     }
116                     catch (Exception JavaDoc ex)
117                     {
118                         ex.printStackTrace(System.err);
119                         urls = null;
120                     }
121                 }
122             }
123         }
124         return urls;
125     }
126
127
128     long arg_sleep_ms = 0;
129
130
131     public void init(Serializable JavaDoc testId)
132         throws ClifException
133     {
134         clearURLs();
135         super.init(testId);
136     }
137
138
139     /**
140      * @param sessionId the session identifier
141      * @param arg should contain 2 arguments: first, an integer setting the think time in seconds
142      * between 2 HTTP requests, then a file name containing the list of URLs to visit. The location
143      * of this file must be included in the RMI server codebase (typically the directory where this
144      * class has been compiled to). URLs are loaded via a GET method, unless the URL is prefixed by
145      * the 'post' keyword (actually any string starting with character 'p' or 'P' will be OK), in
146      * which case a POST method will be issued for the trailing URL.
147      * @return a new Webtest session
148      */

149     public MTScenarioSession newSession(int sessionId, String JavaDoc arg)
150         throws ClifException
151     {
152         MTScenarioSession session = null;
153
154         try
155         {
156             StringTokenizer JavaDoc parser = new StringTokenizer JavaDoc(arg);
157             arg_sleep_ms = Integer.parseInt(parser.nextToken()) * 1000;
158             session = new Session(sessionId, initURLs(parser.nextToken()));
159         }
160         catch (Exception JavaDoc ex)
161         {
162             throw new ClifException(
163                 "Webtest requires 5 arguments:\n\t<number of concurrent threads>\n\t<test duration in seconds>\n\t<ramp-up duration in seconds>\n\t<think time in s>\n\t<file containing URL list>",
164                 ex);
165         }
166         return session;
167     }
168
169
170     class Session extends HttpClient implements MTScenarioSession
171     {
172         int index;
173         int id;
174         HttpMethod[] methods;
175
176         public Session(int id, String JavaDoc[] urls)
177         {
178             super();
179             this.id = id;
180             index = 0;
181             getState().setCookiePolicy(CookiePolicy.COMPATIBILITY);
182             methods = new HttpMethod[urls.length];
183             for (int i=0 ; i<urls.length ; ++i)
184             {
185                 if (urls[i].charAt(0) == 'p' || urls[i].charAt(0) == 'P')
186                 {
187                     methods[i] = new PostMethod(urls[i].substring(urls[i].indexOf("http")));
188                 }
189                 else
190                 {
191                     methods[i] = new GetMethod(urls[i]);
192                 }
193                 methods[i].setFollowRedirects(true);
194                 methods[i].setStrictMode(false);
195             }
196         }
197
198         public ActionEvent action(ActionEvent report)
199         {
200             try
201             {
202                 if (methods[index] instanceof PostMethod)
203                 {
204                     report.type = "HTTP POST";
205                 }
206                 else
207                 {
208                     report.type = "HTTP GET";
209                 }
210                 report.setDate(System.currentTimeMillis());
211                 try
212                 {
213                     executeMethod(methods[index]);
214                     report.result = methods[index].getStatusCode() + " - " + methods[index].getStatusText();
215                 }
216                 catch (Exception JavaDoc ex)
217                 {
218                     report.result = ex.toString();
219                     report.successful = false;
220                 }
221                 methods[index].releaseConnection();
222                 report.comment = methods[index].getURI().toString();
223                 String JavaDoc path = methods[index].getPath();
224                 methods[index].recycle();
225                 methods[index].setPath(path);
226                 report.duration = (int) (System.currentTimeMillis() - report.getDate());
227                 report.sessionId = id;
228                 if (++index == methods.length)
229                 {
230                     index = 0;
231                 }
232                 Thread.sleep(arg_sleep_ms);
233             }
234             catch (Exception JavaDoc ex)
235             {
236                 ex.printStackTrace(System.err);
237             }
238             return report;
239         }
240     }
241 }
242
Popular Tags