KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > protocol > tcp > sampler > TCPSampler


1 // $Header: /home/cvs/jakarta-jmeter/src/protocol/tcp/org/apache/jmeter/protocol/tcp/sampler/TCPSampler.java,v 1.5.2.7 2004/10/06 01:56:56 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.tcp.sampler;
20
21 import java.io.File JavaDoc;
22 import java.io.FileInputStream JavaDoc;
23 import java.io.FileNotFoundException JavaDoc;
24 import java.io.IOException JavaDoc;
25 import java.io.InputStream JavaDoc;
26 import java.io.OutputStream JavaDoc;
27 import java.net.Socket JavaDoc;
28 import java.net.UnknownHostException JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.HashSet JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Properties JavaDoc;
34 import java.util.Set JavaDoc;
35
36 import org.apache.jmeter.config.ConfigTestElement;
37 import org.apache.jmeter.util.JMeterUtils;
38 import org.apache.jmeter.engine.event.LoopIterationEvent;
39 import org.apache.jmeter.samplers.AbstractSampler;
40 import org.apache.jmeter.samplers.Entry;
41 import org.apache.jmeter.samplers.SampleResult;
42 import org.apache.jmeter.testelement.TestListener;
43 import org.apache.jorphan.logging.LoggingManager;
44 import org.apache.log.Logger;
45
46 /**
47  * A sampler which understands Tcp requests.
48  *
49  * @version $Revision: 1.5.2.7 $ $Date: 2004/10/06 01:56:56 $
50  */

51 public class TCPSampler extends AbstractSampler implements TestListener
52 {
53     private static final Logger log = LoggingManager.getLoggerForClass();
54
55     public final static String JavaDoc SERVER = "TCPSampler.server"; //$NON-NLS-1$
56
public final static String JavaDoc PORT = "TCPSampler.port"; //$NON-NLS-1$
57
public final static String JavaDoc FILENAME = "TCPSampler.filename"; //$NON-NLS-1$
58
public final static String JavaDoc CLASSNAME = "TCPSampler.classname";//$NON-NLS-1$
59
public final static String JavaDoc NODELAY = "TCPSampler.nodelay"; //$NON-NLS-1$
60
public final static String JavaDoc TIMEOUT = "TCPSampler.timeout"; //$NON-NLS-1$
61
public final static String JavaDoc REQUEST = "TCPSampler.request"; //$NON-NLS-1$
62

63     private final static String JavaDoc TCPKEY = "TCP"; //$NON-NLS-1$ key for HashMap
64
private final static String JavaDoc ERRKEY = "ERR"; //$NON-NLS-1$ key for HashMap
65

66     private static Set JavaDoc allSockets = new HashSet JavaDoc();// Keep track of connections to allow close
67

68     // If set, this is the regex that is used to extract the status from the response
69
//NOT implemented yet private final static String STATUS_REGEX = JMeterUtils.getPropDefault("tcp.status.regex","");
70

71     // Otherwise, the response is scanned for these strings
72
private final static String JavaDoc STATUS_PREFIX = JMeterUtils.getPropDefault("tcp.status.prefix","");
73     private final static String JavaDoc STATUS_SUFFIX = JMeterUtils.getPropDefault("tcp.status.suffix","");
74     
75     private final static String JavaDoc STATUS_PROPERTIES = JMeterUtils.getPropDefault("tcp.status.properties","");
76     private final static Properties JavaDoc statusProps = new Properties JavaDoc();
77     private static boolean haveStatusProps = false;
78     
79     static
80     {
81         log.info("Protocol Handler name="+getClassname());
82         log.info("Status prefix="+STATUS_PREFIX);
83         log.info("Status suffix="+STATUS_SUFFIX);
84         log.info("Status properties="+STATUS_PROPERTIES);
85         if (STATUS_PROPERTIES.length()>0)
86         {
87             File JavaDoc f = new File JavaDoc(STATUS_PROPERTIES);
88             try {
89                 statusProps.load(new FileInputStream JavaDoc(f));
90                 log.info("Successfully loaded properties");
91                 haveStatusProps = true;
92             } catch (FileNotFoundException JavaDoc e) {
93                 log.info("Property file not found");
94             } catch (IOException JavaDoc e) {
95                 log.info("Property file error "+e.toString());
96             }
97         }
98     }
99     
100     /** the cache of TCP Connections */
101     private static ThreadLocal JavaDoc tp = new ThreadLocal JavaDoc(){
102         protected Object JavaDoc initialValue(){
103             return new HashMap JavaDoc();
104         }
105     };
106
107     private transient TCPClient protocolHandler;
108     
109     public TCPSampler()
110     {
111         log.debug("Created "+this);
112         protocolHandler=getProtocol();
113         log.debug("Using Protocol Handler: "
114                 +protocolHandler.getClass().getName());
115     }
116
117     private String JavaDoc getError(){
118         Map JavaDoc cp = (Map JavaDoc) tp.get();
119         return (String JavaDoc) cp.get(ERRKEY);
120     }
121
122     private Socket JavaDoc getSocket() {
123         Map JavaDoc cp = (Map JavaDoc) tp.get();
124         Socket JavaDoc con = (Socket JavaDoc) cp.get(TCPKEY);
125         if (con != null) {
126             log.debug(this+" Reusing connection "+con); //$NON-NLS-1$
127
return (Socket JavaDoc) con;
128         }
129     
130         // Not in cache, so create new one and cache it
131
try
132         {
133             con = new Socket JavaDoc(getServer(),getPort());
134             con.setSoTimeout(getTimeout());
135             con.setTcpNoDelay(getNoDelay());
136             
137             log.debug(this+" Timeout "+getTimeout()+" NoDelay "+getNoDelay()); //$NON-NLS-1$
138
log.debug("Created new connection "+con); //$NON-NLS-1$
139
cp.put(TCPKEY,con);
140             allSockets.add(con);// Save so can be closed
141
}
142         catch (UnknownHostException JavaDoc e)
143         {
144             log.warn("Unknown host for "+getLabel(),e);//$NON-NLS-1$
145
cp.put(ERRKEY,e.toString());
146         }
147         catch (IOException JavaDoc e)
148         {
149             log.warn("Could not create socket for "+getLabel(),e); //$NON-NLS-1$
150
cp.put(ERRKEY,e.toString());
151         }
152         return con;
153     }
154
155     public String JavaDoc getUsername()
156     {
157         return getPropertyAsString(ConfigTestElement.USERNAME);
158     }
159
160     public String JavaDoc getPassword()
161     {
162         return getPropertyAsString(ConfigTestElement.PASSWORD);
163     }
164
165     public void setServer(String JavaDoc newServer)
166     {
167         this.setProperty(SERVER, newServer);
168     }
169     public String JavaDoc getServer()
170     {
171         return getPropertyAsString(SERVER);
172     }
173     public void setPort(String JavaDoc newFilename)
174     {
175         this.setProperty(PORT, newFilename);
176     }
177     public int getPort()
178     {
179         return getPropertyAsInt(PORT);
180     }
181     
182     public void setFilename(String JavaDoc newFilename)
183     {
184         this.setProperty(FILENAME, newFilename);
185     }
186     public String JavaDoc getFilename()
187     {
188         return getPropertyAsString(FILENAME);
189     }
190
191
192     public void setRequestData(String JavaDoc newRequestData)
193     {
194         this.setProperty(REQUEST, newRequestData);
195     }
196     
197     public String JavaDoc getRequestData()
198     {
199         return getPropertyAsString(REQUEST);
200     }
201
202
203     public void setTimeout(String JavaDoc newTimeout)
204     {
205         this.setProperty(FILENAME, newTimeout);
206     }
207     public int getTimeout()
208     {
209         return getPropertyAsInt(TIMEOUT);
210     }
211
212
213     public void setNoDelay(String JavaDoc newNoDelay)
214     {
215         this.setProperty(NODELAY, newNoDelay);
216     }
217     
218     public boolean getNoDelay()
219     {
220         return getPropertyAsBoolean(NODELAY);
221     }
222
223
224
225     /**
226      * Returns a formatted string label describing this sampler
227      * Example output:
228      * Tcp://Tcp.nowhere.com/pub/README.txt
229      *
230      * @return a formatted string label describing this sampler
231      */

232     public String JavaDoc getLabel()
233     {
234         return ("tcp://" + this.getServer() + ":" + this.getPort());//$NON-NLS-1$
235
}
236
237     private static String JavaDoc getClassname()
238     {
239         String JavaDoc className = JMeterUtils.getPropDefault("tcp.handler","TCPClientImpl");
240         return className;
241     }
242
243     private static final String JavaDoc protoPrefix = "org.apache.jmeter.protocol.tcp.sampler.";
244     private Class JavaDoc getClass(String JavaDoc className)
245     {
246         Class JavaDoc c = null;
247         try
248         {
249             c = Class.forName(className
250                 ,false,Thread.currentThread().getContextClassLoader());
251         }
252         catch (ClassNotFoundException JavaDoc e)
253         {
254             try
255             {
256                 c = Class.forName(protoPrefix+className
257                     ,false,Thread.currentThread().getContextClassLoader());
258             }
259             catch (ClassNotFoundException JavaDoc e1)
260             {
261                 log.error("Could not find protocol class "+ className);
262             }
263         }
264         return c;
265         
266     }
267
268     private TCPClient getProtocol(){
269         TCPClient TCPClient = null;
270         Class JavaDoc javaClass = getClass(getClassname());
271         try
272         {
273             TCPClient = (TCPClient) javaClass.newInstance();
274             if (log.isDebugEnabled())
275             {
276                 log.debug(this
277                         + "Created: "
278                         + getClassname()
279                         + "@"
280                         + Integer.toHexString(TCPClient.hashCode()));
281             }
282         }
283         catch (Exception JavaDoc e)
284         {
285             log.error(
286                 this + " Exception creating: " + getClassname(),e);
287         }
288         return TCPClient;
289     }
290
291     public SampleResult sample(Entry e)// Entry tends to be ignored ...
292
{
293         log.debug(getLabel()+" "+getFilename()+" "+getUsername()+" "+getPassword());
294         SampleResult res = new SampleResult();
295         boolean isSuccessful = false;
296         res.setSampleLabel(getName());//Use the test element name for the label
297
res.setSamplerData("Host: "+getServer()+" Port: "+getPort());
298         res.sampleStart();
299         try
300         {
301             Socket JavaDoc sock = getSocket();
302             if (sock == null){
303                 res.setResponseCode("500");
304                 res.setResponseMessage(getError());
305             } else {
306                 InputStream JavaDoc is = sock.getInputStream();
307                 OutputStream JavaDoc os = sock.getOutputStream();
308                 String JavaDoc req = getRequestData();
309                 //TODO handle filenames
310
res.setSamplerData(req);
311                 protocolHandler.write(os,req);
312                 String JavaDoc in = protocolHandler.read(is);
313                 res.setResponseData(in.getBytes());
314                 res.setDataType(SampleResult.TEXT);
315                 res.setResponseCode("200");
316                 res.setResponseMessage("OK");
317                 isSuccessful = true;
318                 //Reset the status code if the message contains one
319
if (STATUS_PREFIX.length() > 0)
320                 {
321                     int i = in.indexOf(STATUS_PREFIX);
322                     int j = in.indexOf(STATUS_SUFFIX,i+STATUS_PREFIX.length());
323                     if (i != -1 && j > i)
324                     {
325                         String JavaDoc rc = in.substring(i+STATUS_PREFIX.length(),j);
326                         res.setResponseCode(rc);
327                         isSuccessful = checkResponseCode(rc);
328                         if (haveStatusProps)
329                         {
330                             res.setResponseMessage(
331                                     statusProps.getProperty(rc,"Status code not found in properties"));
332                         }
333                         else
334                         {
335                             res.setResponseMessage("No status property file");
336                         }
337                     }
338                     else
339                     {
340                         res.setResponseCode("999");
341                         res.setResponseMessage("Status value not found");
342                         isSuccessful=false;
343                     }
344                 }
345             }
346         }
347         catch (Exception JavaDoc ex)
348         {
349             log.debug("",ex);
350             res.setResponseCode("500");
351             res.setResponseMessage(ex.toString());
352         }
353
354         // Calculate response time
355
res.sampleEnd();
356
357         // Set if we were successful or not
358
res.setSuccessful(isSuccessful);
359
360         return res;
361     }
362
363      /**
364      * @param rc response code
365      * @return whether this represents success or not
366      */

367     private boolean checkResponseCode(String JavaDoc rc) {
368         if (rc.compareTo("400")>=0 && rc.compareTo("499")<=0)
369         {
370             return false;
371         }
372         if (rc.compareTo("500")>=0 && rc.compareTo("599")<=0)
373         {
374             return false;
375         }
376         return true;
377     }
378
379     private void disconnectAll(){
380         synchronized (allSockets)
381         {
382             Iterator JavaDoc i = allSockets.iterator();
383             while (i.hasNext())
384             {
385                 Socket JavaDoc socket = (Socket JavaDoc) i.next();
386                 try
387                 {
388                     socket.close();
389                 }
390                 catch (IOException JavaDoc e)
391                 {
392                     log.warn("Error closing socket ",e);
393                 } finally {
394                     i.remove();
395                 }
396             }
397         }
398      }
399
400
401      /* (non-Javadoc)
402       * @see org.apache.jmeter.testelement.TestListener#testStarted()
403       */

404      public void testStarted() // Only called once per class?
405
{
406          log.debug(this+" test started");
407      }
408
409     /* (non-Javadoc)
410      * @see org.apache.jmeter.testelement.TestListener#testEnded()
411      */

412     public void testEnded() // Only called once per class?
413
{
414         log.debug(this+" test ended");
415         disconnectAll();
416     }
417
418     /* (non-Javadoc)
419      * @see org.apache.jmeter.testelement.TestListener#testStarted(java.lang.String)
420      */

421     public void testStarted(String JavaDoc host)
422     {
423         log.debug(this+" test started on "+host);
424         // TODO Auto-generated method stub
425

426     }
427
428     /* (non-Javadoc)
429      * @see org.apache.jmeter.testelement.TestListener#testEnded(java.lang.String)
430      */

431     public void testEnded(String JavaDoc host)
432     {
433         log.debug(this+" test ended on "+host);
434         disconnectAll();
435         
436     }
437
438     /* (non-Javadoc)
439      * @see org.apache.jmeter.testelement.TestListener#testIterationStart(org.apache.jmeter.engine.event.LoopIterationEvent)
440      */

441     public void testIterationStart(LoopIterationEvent event)
442     {
443         log.debug(this+" test iteration start on "+event.getIteration());
444         // TODO Auto-generated method stub
445

446     }
447 }
448
Popular Tags