KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > protocol > java > test > JavaTest


1 // $Header: /home/cvs/jakarta-jmeter/src/protocol/java/org/apache/jmeter/protocol/java/test/JavaTest.java,v 1.10.2.3 2004/06/25 10:22:00 sebb Exp $
2
/*
3  * Copyright 2003-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17 */

18
19 package org.apache.jmeter.protocol.java.test;
20
21 import java.io.Serializable JavaDoc;
22 import java.util.Iterator JavaDoc;
23
24 import org.apache.jmeter.config.Arguments;
25 import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
26 import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
27 import org.apache.jmeter.samplers.SampleResult;
28
29 /**
30  * The <code>JavaTest</code> class is a simple sampler which
31  * is intended for use when developing test plans.
32  * The sampler generates results internally,
33  * so does not need access to any external
34  * resources such as web, ftp or LDAP servers.
35  * In addition, because the exact values of most of the SampleResult
36  * can be directly set, it is possible to easily test most Assertions that use
37  * the sample results.
38  *
39  * <p>
40  * During each sample, this client will sleep for some amount of
41  * time. The amount of time to sleep is determined from the
42  * two parameters Sleep_Time and Sleep_Mask using the formula:
43  * <pre>
44  * totalSleepTime = Sleep_Time + (System.currentTimeMillis() % Sleep_Mask)
45  * </pre>
46  * Thus, the Sleep_Mask provides a way to add a random component
47  * to the sleep time.
48  * <p>
49  * The sampler is able to define the precise values of:
50  * <pre>
51  * - responseCode
52  * - responseMessage
53  * - Label
54  * - success/fail status
55  * </pre>
56  * The elapsed time and end-time cannot be directly controlled.
57  *<p>
58  * Note: this class was derived from {@link SleepTest}.
59  *
60  * @version $Version: 1.3 $ $Date: 2004/06/25 10:22:00 $
61  */

62
63 public class JavaTest
64     extends AbstractJavaSamplerClient
65     implements Serializable JavaDoc
66 {
67     /** The base number of milliseconds to sleep during each sample. */
68     private long sleepTime;
69
70     /** The default value of the SleepTime parameter, in milliseconds. */
71     public static final long DEFAULT_SLEEP_TIME = 100;
72
73     /** The name used to store the SleepTime parameter. */
74     private static final String JavaDoc SLEEP_NAME="Sleep_Time";
75
76
77     /**
78      * A mask to be applied to the current time in order to add a
79      * semi-random component to the sleep time.
80      */

81     private long sleepMask;
82
83     /** The default value of the SleepMask parameter. */
84     public static final long DEFAULT_SLEEP_MASK = 0xff;
85     
86     /** Formatted string representation of the default SleepMask. */
87     private static final String JavaDoc DEFAULT_MASK_STRING =
88         "0x" + (Long.toHexString(DEFAULT_SLEEP_MASK)).toUpperCase();
89
90     /** The name used to store the SleepMask parameter. */
91     private static final String JavaDoc MASK_NAME="Sleep_Mask";
92
93
94     /** The label to store in the sample result. */
95     private String JavaDoc label;
96
97     /** The default value of the Label parameter. */
98     private static final String JavaDoc LABEL_DEFAULT = "JavaTest";
99     
100     /** The name used to store the Label parameter. */
101     private static final String JavaDoc LABEL_NAME = "Label";
102
103
104     /** The response message to store in the sample result. */
105     private String JavaDoc responseMessage;
106     
107     /** The default value of the ResponseMessage parameter. */
108     private static final String JavaDoc RESPONSE_MESSAGE_DEFAULT = "";
109     
110     /** The name used to store the ResponseMessage parameter. */
111     private static final String JavaDoc RESPONSE_MESSAGE_NAME = "ResponseMessage";
112
113     
114     /** The response code to be stored in the sample result. */
115     private String JavaDoc responseCode;
116     
117     /** The default value of the ResponseCode parameter. */
118     private static final String JavaDoc RESPONSE_CODE_DEFAULT = "";
119     
120     /** The name used to store the ResponseCode parameter. */
121     private static final String JavaDoc RESPONSE_CODE_NAME = "ResponseCode";
122
123
124     /** The sampler data (shown as Request Data in the Tree display). */
125     private String JavaDoc samplerData;
126     
127     /** The default value of the SamplerData parameter. */
128     private static final String JavaDoc SAMPLER_DATA_DEFAULT = "";
129     
130     /** The name used to store the SamplerData parameter. */
131     private static final String JavaDoc SAMPLER_DATA_NAME = "SamplerData";
132
133      
134     /** Holds the result data (shown as Response Data in the Tree display). */
135     private String JavaDoc resultData;
136     
137     /** The default value of the ResultData parameter. */
138     private static final String JavaDoc RESULT_DATA_DEFAULT = "";
139     
140     /** The name used to store the ResultData parameter. */
141     private static final String JavaDoc RESULT_DATA_NAME = "ResultData";
142
143
144     /** The success status to be stored in the sample result. */
145     private boolean success;
146     
147     /** The default value of the Success Status parameter. */
148     private static final String JavaDoc SUCCESS_DEFAULT = "OK";
149     
150     /** The name used to store the Success Status parameter. */
151     private static final String JavaDoc SUCCESS_NAME = "Status";
152
153
154     /**
155      * Default constructor for <code>JavaTest</code>.
156      *
157      * The Java Sampler uses the default constructor to instantiate
158      * an instance of the client class.
159      */

160     public JavaTest()
161     {
162         getLogger().debug(whoAmI() + "\tConstruct");
163     }
164
165
166     /*
167      * Utility method to set up all the values
168      */

169     private void setupValues(JavaSamplerContext context)
170     {
171
172         sleepTime = context.getLongParameter(SLEEP_NAME, DEFAULT_SLEEP_TIME);
173         sleepMask = context.getLongParameter(MASK_NAME, DEFAULT_SLEEP_MASK);
174
175         responseMessage =
176             context.getParameter(
177                 RESPONSE_MESSAGE_NAME,
178                 RESPONSE_MESSAGE_DEFAULT);
179
180         responseCode =
181             context.getParameter(RESPONSE_CODE_NAME, RESPONSE_CODE_DEFAULT);
182
183         success =
184             context.getParameter(
185                 SUCCESS_NAME,
186                 SUCCESS_DEFAULT).equalsIgnoreCase(
187                 "OK");
188
189         label = context.getParameter(LABEL_NAME, LABEL_DEFAULT);
190
191         samplerData =
192             context.getParameter(SAMPLER_DATA_NAME, SAMPLER_DATA_DEFAULT);
193
194         resultData =
195             context.getParameter(RESULT_DATA_NAME, RESULT_DATA_DEFAULT);
196     }
197     /**
198      * Do any initialization required by this client.
199      *
200      * There is none, as it is done in runTest() in order to be able
201      * to vary the data for each sample.
202      *
203      * @param context the context to run with. This provides access
204      * to initialization parameters.
205      */

206     public void setupTest(JavaSamplerContext context)
207     {
208         getLogger().debug(whoAmI() + "\tsetupTest()");
209         listParameters(context);
210     }
211
212
213     /**
214      * Provide a list of parameters which this test supports. Any
215      * parameter names and associated values returned by this method
216      * will appear in the GUI by default so the user doesn't have
217      * to remember the exact names. The user can add other parameters
218      * which are not listed here. If this method returns null then
219      * no parameters will be listed. If the value for some parameter
220      * is null then that parameter will be listed in the GUI with
221      * an empty value.
222      *
223      * @return a specification of the parameters used by this
224      * test which should be listed in the GUI, or null
225      * if no parameters should be listed.
226      */

227     public Arguments getDefaultParameters()
228     {
229         Arguments params = new Arguments();
230         params.addArgument(SLEEP_NAME, String.valueOf(DEFAULT_SLEEP_TIME));
231         params.addArgument(MASK_NAME, DEFAULT_MASK_STRING);
232         params.addArgument(LABEL_NAME, LABEL_DEFAULT);
233         params.addArgument(RESPONSE_CODE_NAME, RESPONSE_CODE_DEFAULT);
234         params.addArgument(RESPONSE_MESSAGE_NAME, RESPONSE_MESSAGE_DEFAULT);
235         params.addArgument(SUCCESS_NAME, SUCCESS_DEFAULT);
236         params.addArgument(SAMPLER_DATA_NAME, SAMPLER_DATA_DEFAULT);
237         params.addArgument(RESULT_DATA_NAME, SAMPLER_DATA_DEFAULT);
238         return params;
239     }
240
241     /**
242      * Perform a single sample.<br>
243      * In this case, this method will simply sleep for some amount of time.
244      *
245      * This method returns a <code>SampleResult</code> object.
246      * <pre>
247      * The following fields are always set:
248      * - responseCode (default "")
249      * - responseMessage (default "")
250      * - label (default "JavaTest")
251      * - success (default true)
252      * </pre>
253      * The following fields are set from the user-defined
254      * parameters, if supplied:
255      * <pre>
256      * - samplerData
257      * - responseData
258      * </pre>
259      *
260      * @see org.apache.jmeter.samplers.SampleResult#sampleStart()
261      * @see org.apache.jmeter.samplers.SampleResult#sampleEnd()
262      * @see org.apache.jmeter.samplers.SampleResult#setSuccessful(boolean)
263      * @see org.apache.jmeter.samplers.SampleResult#setSampleLabel(String)
264      * @see org.apache.jmeter.samplers.SampleResult#setResponseCode(String)
265      * @see org.apache.jmeter.samplers.SampleResult#setResponseMessage(String)
266      * @see org.apache.jmeter.samplers.SampleResult#setResponseData(byte [])
267      * @see org.apache.jmeter.samplers.SampleResult#setDataType(String)
268      *
269      * @param context the context to run with. This provides access
270      * to initialization parameters.
271      *
272      * @return a SampleResult giving the results of this
273      * sample.
274      */

275     public SampleResult runTest(JavaSamplerContext context)
276     {
277         setupValues(context);
278
279         SampleResult results = new SampleResult();
280
281         results.setResponseCode(responseCode);
282         results.setResponseMessage(responseMessage);
283         results.setSampleLabel(label);
284
285         if (samplerData != null && samplerData.length() > 0)
286         {
287             results.setSamplerData(samplerData);
288         }
289
290         if (resultData != null && resultData.length() > 0)
291         {
292             results.setResponseData(resultData.getBytes());
293             results.setDataType(SampleResult.TEXT);
294         }
295
296         // Record sample start time.
297
results.sampleStart();
298         
299         long sleep = sleepTime;
300         if (sleepTime > 0 && sleepMask > 0)
301         { /// Only do the calculation if it is needed
302
long start = System.currentTimeMillis();
303             // Generate a random-ish offset value using the current time.
304
sleep = sleepTime + (start % sleepMask);
305         }
306         
307         try
308         {
309             // Execute the sample. In this case sleep for the
310
// specified time, if any
311
if (sleep > 0)
312             {
313                 Thread.sleep(sleep);
314             }
315             results.setSuccessful(success);
316         }
317         catch (InterruptedException JavaDoc e)
318         {
319             getLogger().warn("JavaTest: interrupted.");
320             results.setSuccessful(true);
321         }
322         catch (Exception JavaDoc e)
323         {
324             getLogger().error("JavaTest: error during sample", e);
325             results.setSuccessful(false);
326         } finally{
327             // Record end time and populate the results.
328
results.sampleEnd();
329         }
330
331         if (getLogger().isDebugEnabled())
332         {
333             getLogger().debug(
334                 whoAmI() + "\trunTest()" + "\tTime:\t" + results.getTime());
335             listParameters(context);
336         }
337
338         return results;
339     }
340
341     /**
342      * Do any clean-up required by this test. In this case no
343      * clean-up is necessary, but some messages are logged for
344      * debugging purposes.
345      *
346      * @param context the context to run with. This provides access
347      * to initialization parameters.
348      */

349     public void teardownTest(JavaSamplerContext context)
350     {
351         getLogger().debug(whoAmI() + "\tteardownTest()");
352         listParameters(context);
353     }
354     /**
355      * Dump a list of the parameters in this context to the debug log.
356      *
357      * @param context the context which contains the initialization
358      * parameters.
359      */

360     private void listParameters(JavaSamplerContext context)
361     {
362         if (getLogger().isDebugEnabled())
363         {
364             Iterator JavaDoc argsIt = context.getParameterNamesIterator();
365             while (argsIt.hasNext())
366             {
367                 String JavaDoc name = (String JavaDoc) argsIt.next();
368                 getLogger().debug(name + "=" + context.getParameter(name));
369             }
370         }
371     }
372
373     /**
374      * Generate a String identifier of this test for debugging
375      * purposes.
376      *
377      * @return a String identifier for this test instance
378      */

379     private String JavaDoc whoAmI()
380     {
381         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
382         sb.append(Thread.currentThread().toString());
383         sb.append("@");
384         sb.append(Integer.toHexString(hashCode()));
385         return sb.toString();
386     }
387
388 }
389
Popular Tags