KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > protocol > java > sampler > JavaSampler


1 // $Header: /home/cvs/jakarta-jmeter/src/protocol/java/org/apache/jmeter/protocol/java/sampler/JavaSampler.java,v 1.20 2004/02/10 00:46:44 sebb Exp $
2
/*
3  * Copyright 2002-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.sampler;
20
21 import java.util.HashSet JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Set JavaDoc;
24
25 import org.apache.jmeter.config.Arguments;
26 import org.apache.jmeter.engine.event.LoopIterationEvent;
27 import org.apache.jmeter.samplers.AbstractSampler;
28 import org.apache.jmeter.samplers.Entry;
29 import org.apache.jmeter.samplers.SampleResult;
30 import org.apache.jmeter.testelement.TestListener;
31 import org.apache.jmeter.testelement.property.TestElementProperty;
32 import org.apache.jorphan.logging.LoggingManager;
33 import org.apache.log.Logger;
34
35 /**
36  * A sampler for executing custom Java code in each sample. See
37  * {@link JavaSamplerClient} and {@link AbstractJavaSamplerClient} for
38  * information on writing Java code to be executed by this sampler.
39  *
40  * @author <a HREF="mailto:jeremy_a@bigfoot.com">Jeremy Arnold</a>
41  * @version $Revision: 1.20 $
42  */

43 public class JavaSampler extends AbstractSampler implements TestListener
44 {
45     /**
46      * Property key representing the classname of the JavaSamplerClient to
47      * user.
48      */

49     public static final String JavaDoc CLASSNAME = "classname";
50
51     /**
52      * Property key representing the arguments for the JavaSamplerClient.
53      */

54     public static final String JavaDoc ARGUMENTS = "arguments";
55
56     /**
57      * The JavaSamplerClient instance used by this sampler to actually perform
58      * the sample.
59      */

60     private transient JavaSamplerClient javaClient = null;
61
62     /**
63      * The JavaSamplerContext instance used by this sampler to hold
64      * information related to the test run, such as the parameters
65      * specified for the sampler client.
66      */

67     private transient JavaSamplerContext context = null;
68
69     /**
70      * Logging
71      */

72     private static transient Logger log = LoggingManager.getLoggerForClass();
73
74     /**
75      * Set used to register all active JavaSamplers. This is used so that the
76      * samplers can be notified when the test ends.
77      */

78     private static Set JavaDoc allSamplers = new HashSet JavaDoc();
79
80     /**
81      * Create a JavaSampler.
82      */

83     public JavaSampler()
84     {
85         setArguments(new Arguments());
86         synchronized (allSamplers)
87         {
88             allSamplers.add(this);
89         }
90     }
91
92     /**
93      * Set the arguments (parameters) for the JavaSamplerClient to be executed
94      * with.
95      *
96      * @param args the new arguments. These replace any existing arguments.
97      */

98     public void setArguments(Arguments args)
99     {
100         setProperty(new TestElementProperty(ARGUMENTS, args));
101     }
102
103     /**
104      * Get the arguments (parameters) for the JavaSamplerClient to be executed
105      * with.
106      *
107      * @return the arguments
108      */

109     public Arguments getArguments()
110     {
111         return (Arguments) getProperty(ARGUMENTS).getObjectValue();
112     }
113
114     /**
115      * Releases Java Client.
116      */

117     private void releaseJavaClient ()
118     {
119         if (javaClient != null)
120         {
121             javaClient.teardownTest(context);
122         }
123         javaClient = null;
124         context = null;
125     }
126
127     /**
128      * Sets the Classname attribute of the JavaConfig object
129      *
130      * @param classname the new Classname value
131      */

132     public void setClassname(String JavaDoc classname)
133     {
134         setProperty(CLASSNAME, classname);
135     }
136
137     /**
138      * Gets the Classname attribute of the JavaConfig object
139      *
140      * @return the Classname value
141      */

142     public String JavaDoc getClassname()
143     {
144         return getPropertyAsString(CLASSNAME);
145     }
146
147     /**
148      * Performs a test sample.
149      *
150      * The <code>sample()</code> method retrieves the reference to the
151      * Java client and calls its <code>runTest()</code> method.
152      *
153      * @see JavaSamplerClient#runTest(JavaSamplerContext)
154      *
155      * @param entry the Entry for this sample
156      * @return test SampleResult
157      */

158     public SampleResult sample(Entry entry)
159     {
160         context = new JavaSamplerContext(getArguments());
161         if (javaClient == null)
162         {
163             log.debug(whoAmI() + "Creating Java Client");
164             createJavaClient();
165             javaClient.setupTest(context);
166         }
167
168         return createJavaClient().runTest(context);
169     }
170
171     /**
172      * Returns reference to <code>JavaSamplerClient</code>.
173      *
174      * The <code>createJavaClient()</code> method uses reflection
175      * to create an instance of the specified Java protocol client.
176      * If the class can not be found, the method returns a reference
177      * to <code>this</code> object.
178      *
179      * @return JavaSamplerClient reference.
180      */

181     private JavaSamplerClient createJavaClient()
182     {
183         if (javaClient == null)
184         {
185             try
186             {
187                 Class JavaDoc javaClass = Class.forName(getClassname().trim(),
188                         false,
189                         Thread.currentThread().getContextClassLoader());
190                 javaClient = (JavaSamplerClient) javaClass.newInstance();
191                 context = new JavaSamplerContext(getArguments());
192
193                 if (log.isDebugEnabled())
194                 {
195                     log.debug(
196                         whoAmI()
197                             + "\tCreated:\t"
198                             + getClassname()
199                             + "@"
200                             + Integer.toHexString(javaClient.hashCode()));
201                 }
202             }
203             catch (Exception JavaDoc e)
204             {
205                 log.error(
206                     whoAmI() + "\tException creating: " + getClassname(),
207                     e);
208                 javaClient = new ErrorSamplerClient();
209             }
210         }
211         return javaClient;
212     }
213
214     /**
215      * Retrieves reference to JavaSamplerClient.
216      *
217      * Convience method used to check for null reference without
218      * actually creating a JavaSamplerClient
219      *
220      * @return reference to JavaSamplerClient
221      * NOTUSED
222     private JavaSamplerClient retrieveJavaClient()
223     {
224         return javaClient;
225     }
226     */

227
228     /**
229      * Generate a String identifier of this instance for debugging
230      * purposes.
231      *
232      * @return a String identifier for this sampler instance
233      */

234     private String JavaDoc whoAmI()
235     {
236         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
237         sb.append(Thread.currentThread().getName());
238         sb.append("@");
239         sb.append(Integer.toHexString(hashCode()));
240         return sb.toString();
241     }
242
243     // TestListener implementation
244
/* Implements TestListener.testStarted() */
245     public void testStarted()
246     {
247         log.debug(whoAmI() + "\ttestStarted");
248     }
249
250     /* Implements TestListener.testStarted(String) */
251     public void testStarted(String JavaDoc host)
252     {
253         log.debug(whoAmI() + "\ttestStarted(" + host + ")");
254     }
255
256     /**
257      * Method called at the end of the test. This is called only on one
258      * instance of JavaSampler. This method will loop through all of the
259      * other JavaSamplers which have been registered (automatically in the
260      * constructor) and notify them that the test has ended, allowing the
261      * JavaSamplerClients to cleanup.
262      */

263     public void testEnded()
264     {
265         log.debug(whoAmI() + "\ttestEnded");
266         synchronized (allSamplers)
267         {
268             Iterator JavaDoc i = allSamplers.iterator();
269             while (i.hasNext())
270             {
271                 JavaSampler sampler = (JavaSampler) i.next();
272                 sampler.releaseJavaClient();
273                 i.remove();
274             }
275         }
276     }
277
278     /* Implements TestListener.testEnded(String) */
279     public void testEnded(String JavaDoc host)
280     {
281         testEnded();
282     }
283
284     /* Implements TestListener.testIterationStart(LoopIterationEvent) */
285     public void testIterationStart(LoopIterationEvent event)
286     {
287     }
288
289     /**
290      * A {@link JavaSamplerClient} implementation used for error handling. If
291      * an error occurs while creating the real JavaSamplerClient object, it is
292      * replaced with an instance of this class. Each time a sample occurs with
293      * this class, the result is marked as a failure so the user can see that
294      * the test failed.
295      */

296     class ErrorSamplerClient extends AbstractJavaSamplerClient
297     {
298         /**
299          * Return SampleResult with data on error.
300          * @see JavaSamplerClient#runTest()
301          */

302         public SampleResult runTest(JavaSamplerContext context)
303         {
304             log.debug(whoAmI() + "\trunTest");
305             Thread.yield();
306             SampleResult results = new SampleResult();
307             results.setSuccessful(false);
308             results.setResponseData(
309                 ("Class not found: " + getClassname()).getBytes());
310             results.setSampleLabel("ERROR: " + getClassname());
311             return results;
312         }
313     }
314 }
315
Popular Tags