KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > reporters > ResultCollector


1 // $Header: /home/cvs/jakarta-jmeter/src/core/org/apache/jmeter/reporters/ResultCollector.java,v 1.36.2.3 2004/10/26 22:47:46 mstover1 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.reporters;
20
21
22 import java.io.BufferedOutputStream JavaDoc;
23 import java.io.BufferedReader JavaDoc;
24 import java.io.ByteArrayOutputStream JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.FileNotFoundException JavaDoc;
27 import java.io.FileOutputStream JavaDoc;
28 import java.io.FileReader JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.OutputStreamWriter JavaDoc;
31 import java.io.PrintWriter JavaDoc;
32 import java.io.RandomAccessFile JavaDoc;
33 import java.io.Serializable JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.HashSet JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Set JavaDoc;
38
39 import org.apache.avalon.framework.configuration.Configuration;
40 import org.apache.avalon.framework.configuration.ConfigurationException;
41 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
42 import org.apache.avalon.framework.configuration.DefaultConfigurationSerializer;
43 import org.apache.jmeter.engine.event.LoopIterationEvent;
44 import org.apache.jmeter.engine.util.NoThreadClone;
45 import org.apache.jmeter.samplers.Clearable;
46 import org.apache.jmeter.samplers.Remoteable;
47 import org.apache.jmeter.samplers.SampleEvent;
48 import org.apache.jmeter.samplers.SampleListener;
49 import org.apache.jmeter.samplers.SampleResult;
50 import org.apache.jmeter.save.SaveService;
51 import org.apache.jmeter.testelement.TestListener;
52 import org.apache.jmeter.testelement.property.BooleanProperty;
53 import org.apache.jorphan.logging.LoggingManager;
54 import org.apache.log.Logger;
55 import org.xml.sax.SAXException JavaDoc;
56
57
58 /**
59  * @version $Revision: 1.36.2.3 $ on $Date: 2004/10/26 22:47:46 $
60  */

61 public class ResultCollector
62     extends AbstractListenerElement
63     implements
64         SampleListener,
65         Clearable,
66         Serializable JavaDoc,
67         TestListener,
68         Remoteable,
69         NoThreadClone
70 {
71     private static final String JavaDoc TESTRESULTS_START = "<testResults>";//$NON-NLS-1$
72
private static final String JavaDoc TESTRESULTS_END = "</testResults>";//$NON-NLS-1$
73
private static final String JavaDoc XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";//$NON-NLS-1$
74
private static final int MIN_XML_FILE_LEN =
75             XML_HEADER.length() + TESTRESULTS_START.length() + TESTRESULTS_END.length();
76     transient private static Logger log = LoggingManager.getLoggerForClass();
77     public final static String JavaDoc FILENAME = "filename"; //$NON-NLS-1$
78
transient private static boolean functionalMode = false;
79     public static final String JavaDoc ERROR_LOGGING = "ResultCollector.error_logging";//$NON-NLS-1$
80
// protected List results = Collections.synchronizedList(new ArrayList());
81
//private int current;
82
transient private DefaultConfigurationSerializer serializer;
83     //private boolean inLoading = false;
84
transient private volatile PrintWriter JavaDoc out;
85     transient private boolean inTest = false;
86     transient private static Map JavaDoc files = new HashMap JavaDoc();
87     transient private Set JavaDoc hosts = new HashSet JavaDoc();
88
89     /**
90      * No-arg constructor.
91      */

92     public ResultCollector()
93     {
94         //current = -1;
95
serializer = new DefaultConfigurationSerializer();
96         setErrorLogging(false);
97     }
98
99     private void setFilenameProperty(String JavaDoc f)
100     {
101         setProperty(FILENAME, f);
102     }
103
104     public String JavaDoc getFilename()
105     {
106         return getPropertyAsString(FILENAME);
107     }
108
109     public boolean isErrorLogging()
110     {
111         return getPropertyAsBoolean(ERROR_LOGGING);
112     }
113
114     public void setErrorLogging(boolean errorLogging)
115     {
116         setProperty(new BooleanProperty(ERROR_LOGGING, errorLogging));
117     }
118
119     /**
120      * Sets the filename attribute of the ResultCollector object.
121      *
122      * @param f the new filename value
123      */

124     public void setFilename(String JavaDoc f)
125     {
126         if (inTest)
127         {
128             return;
129         }
130         setFilenameProperty(f);
131     }
132
133     public void testEnded(String JavaDoc host)
134     {
135         hosts.remove(host);
136         if (hosts.size() == 0)
137         {
138             finalizeFileOutput();
139             inTest = false;
140         }
141     }
142
143     public void testStarted(String JavaDoc host)
144     {
145         hosts.add(host);
146         try
147         {
148             initializeFileOutput();//TODO - move to first sample??
149
}
150         catch (Exception JavaDoc e)
151         {
152             log.error("", e);
153         }
154         inTest = true;
155     }
156
157     public void testEnded()
158     {
159         testEnded("local");//$NON-NLS-1$
160
}
161
162     public void testStarted()
163     {
164         testStarted("local");//$NON-NLS-1$
165
}
166
167     public void loadExistingFile()
168         throws SAXException JavaDoc, IOException JavaDoc, ConfigurationException
169     {
170         //inLoading = true;
171
if (new File JavaDoc(getFilename()).exists())
172         {
173             clearVisualizer();
174             BufferedReader JavaDoc dataReader = null;
175             try
176             {
177                 Configuration savedSamples = getConfiguration(getFilename());
178                 readSamples(savedSamples);
179             }
180             catch(SAXException JavaDoc e)
181             {
182                 dataReader = new BufferedReader JavaDoc(new FileReader JavaDoc(getFilename()));
183                 String JavaDoc line;
184                 while((line = dataReader.readLine()) != null)
185                 {
186                     sendToVisualizer(SaveService.makeResultFromDelimitedString(line));
187                 }
188             }
189             catch (Exception JavaDoc e)
190             {
191                 log.error("", e);
192             }
193             finally
194             {
195                 if (dataReader != null) dataReader.close();
196             }
197         }
198         //inLoading = false;
199
}
200
201     private static void writeFileStart(PrintWriter JavaDoc writer)
202     {
203         if (SaveService.getOutputFormat() == SaveService.SAVE_AS_XML)
204         {
205             writer.println(XML_HEADER);
206             writer.println(TESTRESULTS_START);
207         }
208         else if (SaveService.getOutputFormat() == SaveService.SAVE_AS_CSV)
209         {
210             if (SaveService.getPrintFieldNames())
211             {
212                 writer.println(SaveService.printableFieldNamesToString());
213             }
214         }
215     }
216
217
218     private static void writeFileEnd(PrintWriter JavaDoc pw)
219     {
220         if (SaveService.getOutputFormat() == SaveService.SAVE_AS_XML)
221         {
222             pw.print("\n");//$NON-NLS-1$
223
pw.print(TESTRESULTS_END);
224         }
225     }
226
227     private static synchronized PrintWriter JavaDoc getFileWriter(String JavaDoc filename)
228         throws IOException JavaDoc
229     {
230         if (filename == null || filename.length() == 0)
231         {
232             return null;
233         }
234         PrintWriter JavaDoc writer = (PrintWriter JavaDoc) files.get(filename);
235         boolean trimmed = true;
236
237         if (writer == null)
238         {
239              if (SaveService.getOutputFormat() == SaveService.SAVE_AS_XML)
240              {
241                 trimmed = trimLastLine(filename);
242              }
243             writer =
244                 new PrintWriter JavaDoc(
245                     new OutputStreamWriter JavaDoc(
246                         new BufferedOutputStream JavaDoc(
247                             new FileOutputStream JavaDoc(filename, trimmed)),
248                         "UTF-8"),//$NON-NLS-1$
249
true);
250             files.put(filename, writer);
251         }
252         if (!trimmed)
253         {
254             writeFileStart(writer);
255         }
256         return writer;
257     }
258
259     // returns false if the file did not contain the terminator
260
private static boolean trimLastLine(String JavaDoc filename)
261     {
262         RandomAccessFile JavaDoc raf = null;
263         try
264         {
265             raf = new RandomAccessFile JavaDoc(filename,"rw");//$NON-NLS-1$
266
long len = raf.length();
267             if (len < MIN_XML_FILE_LEN)
268             {
269                 return false;
270             }
271             raf.seek(len-TESTRESULTS_END.length()-10);//TODO: may not work on all OSes?
272
String JavaDoc line;
273             long pos = raf.getFilePointer();
274             int end=0;
275             while((line = raf.readLine()) != null)// reads to end of line OR file
276
{
277                 end = line.indexOf(TESTRESULTS_END);
278                 if (end >= 0) // found the string
279
{
280                     break;
281                 }
282                 pos = raf.getFilePointer();
283             }
284             if (line == null)
285             {
286                 log.warn("Unexpected EOF trying to find XML end marker in "+filename);
287                 raf.close();
288                 return false;
289             }
290             raf.setLength(pos+end);// Truncate the file
291
raf.close();
292         }
293         catch (FileNotFoundException JavaDoc e)
294         {
295             return false;
296         } catch (IOException JavaDoc e) {
297             log.warn("Error trying to find XML terminator "+e.toString());
298             try {
299                 if (raf != null) raf.close();
300             } catch (IOException JavaDoc e1) {}
301             return false;
302         }
303         return true;
304     }
305
306     public static void enableFunctionalMode(boolean mode)
307     {
308         functionalMode = mode;
309     }
310
311     public boolean getFunctionalMode()
312     {
313         return functionalMode || isErrorLogging();
314     }
315
316     /**
317      * Gets the serializedSampleResult attribute of the ResultCollector object.
318      *
319      * @param result description of the Parameter
320      * @return the serializedSampleResult value
321      */

322     private String JavaDoc getSerializedSampleResult(SampleResult result)
323             throws SAXException JavaDoc, IOException JavaDoc, ConfigurationException
324     {
325         ByteArrayOutputStream JavaDoc tempOut = new ByteArrayOutputStream JavaDoc();
326
327         serializer.serialize(
328             tempOut,
329             SaveService.getConfiguration(result, getFunctionalMode()));
330         String JavaDoc serVer = tempOut.toString();
331         int index = serVer.indexOf(System.getProperty("line.separator"));
332         if(index > -1)
333         {
334             return serVer.substring(index);
335         }
336         else
337         {
338             return serVer;
339         }
340     }
341
342     private void readSamples(Configuration testResults)
343             throws IOException JavaDoc, SAXException JavaDoc, ConfigurationException
344     {
345         Configuration[] samples = testResults.getChildren();
346
347         for (int i = 0; i < samples.length; i++)
348         {
349             SampleResult result = SaveService.getSampleResult(samples[i]);
350
351             sendToVisualizer(result);
352             recordResult(result);
353         }
354     }
355
356     /**
357      * Gets the configuration attribute of the ResultCollector object.
358      *
359      * @return the configuration value
360      */

361     private Configuration getConfiguration(String JavaDoc filename)
362             throws SAXException JavaDoc, IOException JavaDoc, ConfigurationException
363     {
364         DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
365
366         return builder.buildFromFile(filename);
367     }
368
369     public void clearVisualizer()
370     {
371         //current = -1;
372
if (getVisualizer() != null && getVisualizer() instanceof Clearable)
373         {
374             ((Clearable) getVisualizer()).clear();
375         }
376         finalizeFileOutput();
377     }
378
379     public void setListener(Object JavaDoc l)
380     {
381     }
382
383     public void sampleStarted(SampleEvent e)
384     {
385     }
386
387     public void sampleStopped(SampleEvent e)
388     {
389     }
390
391
392     /**
393      * When a test result is received, display it and save it.
394      * @param e the sample event that was received
395      */

396     public void sampleOccurred(SampleEvent e)
397     {
398         SampleResult result = e.getResult();
399
400         if (!isErrorLogging() || !result.isSuccessful())
401         {
402             sendToVisualizer(result);
403
404             try
405             {
406                 if (SaveService.getOutputFormat() == SaveService.SAVE_AS_CSV)
407                 {
408                     if (out != null)
409                     {
410                         String JavaDoc savee =
411                                 SaveService.resultToDelimitedString(result);
412                         out.println(savee);
413                     }
414                 }
415                 // Save results as XML
416
else
417                 {
418                     recordResult(result);
419                 }
420             }
421             catch (Exception JavaDoc err)
422             {
423                 log.error("", err); // should throw exception back to caller
424
}
425         }
426     }
427
428     protected void sendToVisualizer(SampleResult r)
429     {
430         if (getVisualizer() != null)
431         {
432             getVisualizer().add(r);
433         }
434     }
435
436     private void recordResult(SampleResult result)
437             throws SAXException JavaDoc, IOException JavaDoc, ConfigurationException
438     {
439         if (out != null)
440         {
441             if (!isResultMarked(result))
442             {
443                 out.print(getSerializedSampleResult(result));
444             }
445         }
446     }
447
448     private synchronized boolean isResultMarked(SampleResult res)
449     {
450         String JavaDoc filename = getFilename();
451         boolean marked = res.isMarked(filename);
452
453         if (!marked)
454         {
455             res.setMarked(filename);
456         }
457         return marked;
458     }
459
460     private synchronized void initializeFileOutput()
461         throws IOException JavaDoc, ConfigurationException, SAXException JavaDoc
462     {
463
464         String JavaDoc filename = getFilename();
465         if (out == null && filename != null)
466         {
467             if (out == null)
468             {
469                 try
470                 {
471                     out = getFileWriter(filename);
472                 }
473                 catch (FileNotFoundException JavaDoc e)
474                 {
475                     out = null;
476                 }
477             }
478         }
479     }
480
481     private synchronized void finalizeFileOutput()
482     {
483         if (out != null)
484         {
485             writeFileEnd(out);
486             out.close();
487             files.remove(getFilename());
488             out = null;
489         }
490     }
491
492     /* (non-Javadoc)
493      * @see TestListener#testIterationStart(LoopIterationEvent)
494      */

495     public void testIterationStart(LoopIterationEvent event)
496     {
497     }
498 }
499
Popular Tags