KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > samplers > SampleResult


1 // $Header: /home/cvs/jakarta-jmeter/src/core/org/apache/jmeter/samplers/SampleResult.java,v 1.29.2.7 2005/03/12 11:38:39 sebb Exp $
2
/*
3  * Copyright 2001-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.samplers;
20
21 import java.io.Serializable JavaDoc;
22 import java.io.StringWriter JavaDoc;
23 import java.net.URL JavaDoc;
24 import java.util.ArrayList JavaDoc;
25 import java.util.HashSet JavaDoc;
26 import java.util.List JavaDoc;
27 import java.util.Set JavaDoc;
28
29 import junit.framework.TestCase;
30
31 import org.apache.avalon.framework.configuration.Configuration;
32 import org.apache.jmeter.assertions.AssertionResult;
33 import org.apache.jmeter.util.JMeterUtils;
34 import org.apache.jorphan.logging.LoggingManager;
35 import org.apache.log.LogTarget;
36 import org.apache.log.Logger;
37 import org.apache.log.format.Formatter;
38 import org.apache.log.format.RawFormatter;
39 import org.apache.log.output.io.WriterTarget;
40
41 /**
42  * This is a nice packaging for the various information returned from taking a
43  * sample of an entry.
44  *
45  * @version $Revision: 1.29.2.7 $ $Date: 2005/03/12 11:38:39 $
46  */

47 public class SampleResult implements Serializable JavaDoc
48 {
49     // Bug 33196 - encoding ISO-8859-1 is only suitable for Western countries
50
// However the suggested System.getProperty("file.encoding") is Cp1252 on Windows
51
// So use a new property with the original value as default
52
private static final String JavaDoc DEFAULT_ENCODING =
53         JMeterUtils.getPropDefault("sampleresult.default.encoding","ISO-8859-1");
54     
55     /**
56      * Data type value indicating that the response data is text.
57      *
58      * @see #getDataType
59      * @see #setDataType(java.lang.String)
60      */

61     public final static String JavaDoc TEXT = "text";
62
63     /**
64      * Data type value indicating that the response data is binary.
65      *
66      * @see #getDataType
67      * @see #setDataType(java.lang.String)
68      */

69     public final static String JavaDoc BINARY = "bin";
70
71     /* empty arrays which can be returned instead of null */
72     private static final byte [] EMPTY_BA = new byte [0];
73     private static final SampleResult [] EMPTY_SR = new SampleResult[0];
74     private static final AssertionResult [] EMPTY_AR = new AssertionResult[0];
75
76     private byte[] responseData = EMPTY_BA;
77     private String JavaDoc responseCode;
78     private String JavaDoc label;
79     private String JavaDoc samplerData;
80     private String JavaDoc threadName;
81     private String JavaDoc responseMessage="";
82     private String JavaDoc responseHeaders=""; // Never return null
83
private String JavaDoc contentType=""; // e.g. text/html; charset=utf-8
84
private String JavaDoc requestHeaders="";
85     private long timeStamp = 0;// the time stamp - can be start or end
86
private long startTime = 0;
87     private long endTime = 0;
88     private long idleTime = 0;// Allow for non-sample time
89
private long pauseTime = 0;// Start of pause (if any)
90
private List JavaDoc assertionResults;
91     private List JavaDoc subResults;
92     private String JavaDoc dataType;
93     private boolean success;
94     private Set JavaDoc files;
95     private String JavaDoc dataEncoding;// (is this really the character set?) e.g. ISO-8895-1, UTF-8
96
private long time = 0;
97     private boolean stopThread = false; //Should thread terminate?
98
private boolean stopTest = false; //Should test terminate?
99
private boolean isMonitor = false;
100     //TODO do contentType and/or dataEncoding belong in HTTPSampleResult instead?
101

102     private final static String JavaDoc TOTAL_TIME = "totalTime";
103
104     transient private static Logger log = LoggingManager.getLoggerForClass();
105
106     private static final boolean startTimeStamp =
107         JMeterUtils.getPropDefault("sampleresult.timestamp.start",false);
108
109     static{
110         if (startTimeStamp){
111             log.info("Note: Sample TimeStamps are START times");
112         } else {
113             log.info("Note: Sample TimeStamps are END times");
114         }
115         log.info("sampleresult.default.encoding is set to "+DEFAULT_ENCODING);
116     }
117     public SampleResult()
118     {
119         time = 0;
120     }
121
122     /**
123      * Construct a 'parent' result for an already-existing result, essentially
124      * cloning it
125      *
126      * @param res existing sample result
127      */

128     public SampleResult(SampleResult res)
129     {
130         setStartTime(res.getStartTime());
131         setTime(0);
132
133         setSampleLabel(res.getSampleLabel());
134         setRequestHeaders(res.getRequestHeaders());
135         setResponseData(res.getResponseData());
136         setResponseCode(res.getResponseCode());
137         setSuccessful(res.isSuccessful());
138         setResponseMessage(res.getResponseMessage());
139         setDataType(res.getDataType());
140         setResponseHeaders(res.getResponseHeaders());
141
142         addSubResult(res); // this will add res.getTime() to getTime().
143
}
144
145     /**
146      * Create a sample with a specific elapsed time
147      * but don't allow the times to be changed later
148      *
149      * (only used by HTTPSampleResult)
150      *
151      * @param elapsed time
152      * @param atend create the sample finishing now, else starting now
153      */

154     protected SampleResult(long elapsed, boolean atend)
155     {
156         long now = System.currentTimeMillis();
157         if (atend){
158             setTimes(now - elapsed, now);
159         } else {
160             setTimes(now, now + elapsed);
161         }
162     }
163     
164     /**
165      * Create a sample with specific start and end times
166      * for test purposes, but don't allow the times to be changed later
167      *
168      * (used by StatVisualizerModel.Test)
169      *
170      * @param start start time
171      * @param end end time
172      */

173     public static SampleResult createTestSample(long start, long end)
174     {
175         SampleResult res = new SampleResult();
176         res.setStartTime(start);
177         res.setEndTime(end);
178         return res;
179     }
180
181     /**
182      * Create a sample with a specific elapsed time
183      * for test purposes, but don't allow the times to be changed later
184      *
185      * @param elapsed - desired elapsed time
186      */

187     public static SampleResult createTestSample(long elapsed)
188     {
189         long now = System.currentTimeMillis();
190         return createTestSample(now,now+elapsed);
191     }
192
193     /**
194      * Allow users to create a sample with specific timestamp and elapsed times
195      * for cloning purposes, but don't allow the times to be changed later
196      *
197      * Currently used by SaveService only
198      *
199      * @param stamp - this may be a start time or an end time
200      * @param elapsed
201      */

202     public SampleResult(long stamp, long elapsed)
203     {
204         // Maintain the timestamp relationships
205
if (startTimeStamp) {
206             setTimes(stamp, stamp + elapsed);
207         } else {
208             setTimes(stamp - elapsed, stamp);
209         }
210     }
211
212     /**
213      * Method to set the elapsed time for a sample.
214      * Retained for backward compatibility with 3rd party add-ons
215      * It is assumed that the method is called at the end of a sample
216      *
217      * Must not be used in conjunction with sampleStart()/End()
218      *
219      * @deprecated use sampleStart() and sampleEnd() instead
220      * @param elapsed time in milliseconds
221      */

222     public void setTime(long elapsed){
223         long now = System.currentTimeMillis();
224         setTimes(now-elapsed,now);
225     }
226
227     public void setMarked(String JavaDoc filename)
228     {
229         if (files == null)
230         {
231             files = new HashSet JavaDoc();
232         }
233         files.add(filename);
234     }
235
236     public boolean isMarked(String JavaDoc filename)
237     {
238         return files != null && files.contains(filename);
239     }
240
241     public String JavaDoc getResponseCode()
242     {
243         return responseCode;
244     }
245
246     public void setResponseCode(String JavaDoc code)
247     {
248         responseCode = code;
249     }
250
251     public String JavaDoc getResponseMessage()
252     {
253         return responseMessage;
254     }
255
256     public void setResponseMessage(String JavaDoc msg)
257     {
258         responseMessage = msg;
259     }
260
261     public String JavaDoc getThreadName()
262     {
263         return threadName;
264     }
265
266     public void setThreadName(String JavaDoc threadName)
267     {
268         this.threadName = threadName;
269     }
270
271     public long getTimeStamp()
272     {
273         return timeStamp;
274     }
275     
276     public String JavaDoc getSampleLabel()
277     {
278         return label;
279     }
280
281     public void setSampleLabel(String JavaDoc label)
282     {
283         this.label = label;
284     }
285
286     public void addAssertionResult(AssertionResult assertResult)
287     {
288         if (assertionResults == null)
289         {
290             assertionResults = new ArrayList JavaDoc();
291         }
292         assertionResults.add(assertResult);
293     }
294
295     /**
296      * Gets the assertion results associated with this sample.
297      *
298      * @return an array containing the assertion results for this sample.
299      * Returns empty array if there are no assertion results.
300      */

301     public AssertionResult[] getAssertionResults()
302     {
303         if (assertionResults == null)
304         {
305             return EMPTY_AR;
306         }
307         return (AssertionResult[]) assertionResults.toArray(
308             new AssertionResult[0]);
309     }
310
311     public void addSubResult(SampleResult subResult)
312     {
313         if (subResults == null)
314         {
315             subResults = new ArrayList JavaDoc();
316         }
317         subResults.add(subResult);
318         setTime(getTime()+subResult.getTime());
319     }
320
321     /**
322      * Gets the subresults associated with this sample.
323      *
324      * @return an array containing the subresults for this sample. Returns
325      * an empty array if there are no subresults.
326      */

327     public SampleResult[] getSubResults()
328     {
329         if (subResults == null)
330         {
331             return EMPTY_SR;
332         }
333         return (SampleResult[]) subResults.toArray(new SampleResult[0]);
334     }
335
336     public void configure(Configuration info)
337     {
338         time = info.getAttributeAsLong(TOTAL_TIME, 0L);
339     }
340
341     /**
342      * Sets the responseData attribute of the SampleResult object.
343      *
344      * @param response the new responseData value
345      */

346     public void setResponseData(byte[] response)
347     {
348         responseData = response;
349     }
350
351     /**
352      * Gets the responseData attribute of the SampleResult object.
353      *
354      * @return the responseData value
355      */

356     public byte[] getResponseData()
357     {
358         return responseData;
359     }
360
361     /**
362      * Convenience method to get responseData as a non-null byte array
363      *
364      * @return the responseData. If responseData is null
365      * then an empty byte array is returned rather than null.
366      *
367      */

368     public byte [] responseDataAsBA()
369     {
370         return responseData == null ? EMPTY_BA : responseData;
371     }
372
373     public void setSamplerData(String JavaDoc s)
374     {
375         samplerData = s;
376     }
377
378     public String JavaDoc getSamplerData()
379     {
380         return samplerData;
381     }
382
383     /**
384      * Get the time it took this sample to occur.
385      * @return elapsed time in milliseonds
386      *
387      */

388     public long getTime()
389     {
390         return time;
391     }
392
393     public boolean isSuccessful()
394     {
395         return success;
396     }
397
398     public void setDataType(String JavaDoc dataType)
399     {
400         this.dataType = dataType;
401     }
402
403     public String JavaDoc getDataType()
404     {
405         return dataType;
406     }
407
408     /**
409      * Sets the successful attribute of the SampleResult object.
410      *
411      * @param success the new successful value
412      */

413     public void setSuccessful(boolean success)
414     {
415         this.success = success;
416     }
417
418     /**
419      * Returns the display name.
420      *
421      * @return display name of this sample result
422      */

423     public String JavaDoc toString()
424     {
425         return getSampleLabel();
426     }
427     
428     /**
429      * Returns the dataEncoding.
430      */

431     public String JavaDoc getDataEncoding()
432     {
433         if (dataEncoding != null)
434         {
435             return dataEncoding;
436         }
437         else
438         {
439             return DEFAULT_ENCODING;
440         }
441     }
442
443     /**
444      * Sets the dataEncoding.
445      * @param dataEncoding the dataEncoding to set, e.g. ISO-8895-1, UTF-8
446      */

447     public void setDataEncoding(String JavaDoc dataEncoding)
448     {
449         this.dataEncoding = dataEncoding;
450     }
451     /**
452      * @return whether to stop the test
453      */

454     public boolean isStopTest()
455     {
456         return stopTest;
457     }
458
459     /**
460      * @return whether to stop this thread
461      */

462     public boolean isStopThread()
463     {
464         return stopThread;
465     }
466
467     /**
468      * @param b
469      */

470     public void setStopTest(boolean b)
471     {
472         stopTest = b;
473     }
474
475     /**
476      * @param b
477      */

478     public void setStopThread(boolean b)
479     {
480         stopThread = b;
481     }
482
483     /**
484      * @return the request headers
485      */

486     public String JavaDoc getRequestHeaders()
487     {
488         return requestHeaders;
489     }
490
491     /**
492      * @return the response headers
493      */

494     public String JavaDoc getResponseHeaders()
495     {
496         return responseHeaders;
497     }
498
499     /**
500      * @param string - request headers
501      */

502     public void setRequestHeaders(String JavaDoc string)
503     {
504         requestHeaders = string;
505     }
506
507     /**
508      * @param string - response headers
509      */

510     public void setResponseHeaders(String JavaDoc string)
511     {
512         responseHeaders = string;
513     }
514
515     /**
516      * @return the content type - e.g. text/html [;charset=utf-8 ]
517      */

518     public String JavaDoc getContentType()
519     {
520         return contentType;
521     }
522
523     /**
524      * @param string
525      */

526     public void setContentType(String JavaDoc string)
527     {
528         contentType = string;
529     }
530
531     /**
532      * @return the end time
533      */

534     public long getEndTime()
535     {
536         return endTime;
537     }
538
539     /**
540      * @return the start time
541      */

542     public long getStartTime()
543     {
544         return startTime;
545     }
546
547     /*
548      * Helper methods
549      * N.B. setStartTime must be called before setEndTime
550      *
551      * setStartTime is used by HTTPSampleResult to clone
552      * the parent sampler and allow the original start time to be kept
553      */

554     protected final void setStartTime(long start)
555     {
556         startTime = start;
557         if (startTimeStamp){
558             timeStamp = startTime;
559         }
560     }
561
562     private void setEndTime(long end)
563     {
564         endTime = end;
565         if (!startTimeStamp){
566             timeStamp = endTime;
567         }
568         if (startTime == 0){
569             log.error("setEndTime must be called after setStartTime"
570                      , new Throwable JavaDoc("Invalid call sequence"));
571             //TODO should this throw an error?
572
} else {
573             time = endTime - startTime - idleTime;
574         }
575     }
576     
577     private void setTimes(long start, long end)
578     {
579         setStartTime(start);
580         setEndTime(end);
581     }
582
583     /**
584      * Record the start time of a sample
585      *
586      */

587     public void sampleStart()
588     {
589         if (startTime == 0){
590             setStartTime(System.currentTimeMillis());
591         } else {
592             log.error("sampleStart called twice"
593                      , new Throwable JavaDoc("Invalid call sequence"));
594         }
595     }
596     
597     /**
598      * Record the end time of a sample and calculate the elapsed time
599      *
600      */

601     public void sampleEnd()
602     {
603         if (endTime == 0){
604             setEndTime(System.currentTimeMillis());
605         } else {
606             log.error("sampleEnd called twice"
607                      , new Throwable JavaDoc("Invalid call sequence"));
608         }
609     }
610
611     /**
612      * Pause a sample
613      *
614      */

615     public void samplePause()
616     {
617         if (pauseTime != 0) {
618             log.error("samplePause called twice",new Throwable JavaDoc("Invalid call sequence"));
619         }
620         pauseTime = System.currentTimeMillis();
621     }
622     
623     /**
624      * Resume a sample
625      *
626      */

627     public void sampleResume()
628     {
629         if (pauseTime == 0) {
630             log.error("sampleResume without samplePause",new Throwable JavaDoc("Invalid call sequence"));
631         }
632         idleTime += System.currentTimeMillis() - pauseTime;
633         pauseTime=0;
634     }
635     
636     /**
637      * When a Sampler is working as a monitor
638      * @param monitor
639      */

640     public void setMonitor(boolean monitor){
641         isMonitor = monitor;
642     }
643
644     /**
645      * If the sampler is a monitor, method will
646      * return true.
647      * @return true if the sampler is a monitor
648      */

649     public boolean isMonitor(){
650         return isMonitor;
651     }
652     
653 ////////////////////////////// Start of Test Code ///////////////////////////
654

655
656 //TODO need more tests - particularly for the new functions
657

658     public static class Test extends TestCase
659     {
660         public Test(String JavaDoc name)
661         {
662             super(name);
663         }
664         
665         public void testElapsed() throws Exception JavaDoc
666         {
667             SampleResult res = new SampleResult();
668
669             // Check sample increments OK
670
res.sampleStart();
671             Thread.sleep(100);
672             res.sampleEnd();
673             assertTrue(res.getTime() >= 100);
674         }
675
676         public void testPause() throws Exception JavaDoc
677         {
678             SampleResult res = new SampleResult();
679             // Check sample increments OK
680
res.sampleStart();
681             Thread.sleep(100);
682             res.samplePause();
683
684             Thread.sleep(200);
685             
686             // Re-increment
687
res.sampleResume();
688             Thread.sleep(100);
689             res.sampleEnd();
690             long sampleTime = res.getTime();
691             if ((sampleTime < 200) || (sampleTime > 290)) {
692                 fail("Accumulated time ("+sampleTime+") was not between 200 and 290 ms");
693             }
694         }
695
696         private static Formatter fmt=new RawFormatter();
697         private StringWriter JavaDoc wr = null;
698         
699         public void divertLog()
700         {
701             wr=new StringWriter JavaDoc(1000);
702             LogTarget [] lt = {new WriterTarget(wr,fmt)};
703             log.setLogTargets(lt);
704         }
705         
706         public void testPause2() throws Exception JavaDoc
707         {
708             divertLog();
709             SampleResult res = new SampleResult();
710             res.sampleStart();
711             res.samplePause();
712             assertTrue(wr.toString().length()==0);
713             res.samplePause();
714             assertFalse(wr.toString().length()==0);
715         }
716         // TODO some more invalid sequence tests needed
717
}
718
719     private URL JavaDoc location;
720
721     public void setURL(URL JavaDoc location) {
722         this.location= location;
723     }
724
725     public URL JavaDoc getURL() {
726         return location;
727     }
728 }
729
Popular Tags