KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > save > SaveService


1 // $Header: /home/cvs/jakarta-jmeter/src/core/org/apache/jmeter/save/SaveService.java,v 1.37.2.1 2004/06/12 18:32:04 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.save;
20
21 import java.io.ByteArrayInputStream JavaDoc;
22 import java.io.ByteArrayOutputStream JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileInputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStream JavaDoc;
27 import java.io.OutputStream JavaDoc;
28 import java.io.UnsupportedEncodingException JavaDoc;
29 import java.text.ParseException JavaDoc;
30 import java.text.SimpleDateFormat JavaDoc;
31 import java.util.Collection JavaDoc;
32 import java.util.Date JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.LinkedList JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Properties JavaDoc;
38 import java.util.StringTokenizer JavaDoc;
39
40 //import junit.framework.TestCase;
41

42 import org.apache.avalon.framework.configuration.Configuration;
43 import org.apache.avalon.framework.configuration.ConfigurationException;
44 import org.apache.avalon.framework.configuration.DefaultConfiguration;
45 import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
46 import org.apache.avalon.framework.configuration.DefaultConfigurationSerializer;
47 import org.apache.jmeter.assertions.AssertionResult;
48 import org.apache.jmeter.junit.JMeterTestCase;
49 import org.apache.jmeter.samplers.SampleResult;
50 import org.apache.jmeter.testelement.TestElement;
51 import org.apache.jmeter.testelement.property.CollectionProperty;
52 import org.apache.jmeter.testelement.property.JMeterProperty;
53 import org.apache.jmeter.testelement.property.MapProperty;
54 import org.apache.jmeter.testelement.property.StringProperty;
55 import org.apache.jmeter.testelement.property.TestElementProperty;
56 import org.apache.jmeter.util.JMeterUtils;
57 import org.apache.jmeter.util.NameUpdater;
58 import org.apache.jorphan.collections.HashTree;
59 import org.apache.jorphan.collections.ListedHashTree;
60 import org.apache.jorphan.logging.LoggingManager;
61 import org.apache.jorphan.util.JOrphanUtils;
62 import org.apache.log.Logger;
63 import org.xml.sax.SAXException JavaDoc;
64
65 /**
66  * This class provides a means for saving test results. Test results are
67  * typically saved in an XML file, but other storage mechanisms may also be
68  * used, for instance, CSV files or databases.
69  *
70  * @author Mike Stover
71  * @author <a HREF="mailto:kcassell&#X0040;apache.org">Keith Cassell</a>
72  * @version $Revision: 1.37.2.1 $ $Date: 2004/06/12 18:32:04 $
73  */

74 public final class SaveService implements SaveServiceConstants
75 {
76     transient private static final Logger log = LoggingManager.getLoggerForClass();
77
78 //TODO: make most/all of these fields private?
79

80     protected static final int SAVE_NO_ASSERTIONS = 0;
81     protected static final int SAVE_FIRST_ASSERTION = SAVE_NO_ASSERTIONS + 1;
82     protected static final int SAVE_ALL_ASSERTIONS = SAVE_FIRST_ASSERTION + 1;
83
84     /** A formatter for the time stamp. */
85     protected static SimpleDateFormat JavaDoc formatter = null;
86
87     /** A flag to indicate which output format to use for results. */
88     protected static int outputFormat = SAVE_AS_XML;
89
90     /** A flag to indicate whether to print the field names for delimited
91         result files. */

92     protected static boolean printFieldNames = false;
93
94     /** A flag to indicate whether the data type should
95         be saved to the test results. */

96     protected static boolean saveDataType = true;
97
98     /** A flag to indicate whether the assertion result's failure message
99         should be saved to the test results. */

100     protected static boolean saveAssertionResultsFailureMessage = false;
101
102     /** A flag to indicate whether the label should be saved to the test
103         results. */

104     protected static boolean saveLabel = true;
105
106     /** A flag to indicate whether the response code should be saved to the
107         test results. */

108     protected static boolean saveResponseCode = false;
109
110     /** A flag to indicate whether the response data should be saved to the
111         test results. */

112     protected static boolean saveResponseData = false;
113
114     /** A flag to indicate whether the response message should be saved to the
115         test results. */

116     protected static boolean saveResponseMessage = false;
117
118     /** A flag to indicate whether the success indicator should be saved to the
119         test results. */

120     protected static boolean saveSuccessful = true;
121
122     /** A flag to indicate whether the thread name should be saved to the test
123         results. */

124     protected static boolean saveThreadName = true;
125
126     /** A flag to indicate whether the time should be saved to the test
127         results. */

128     protected static boolean saveTime = true;
129
130     /** A flag to indicate the format of the time stamp within the test
131         results. */

132     protected static String JavaDoc timeStampFormat = MILLISECONDS;
133
134     /** A flag to indicate whether the time stamp should be printed in
135         milliseconds. */

136     protected static boolean printMilliseconds = true;
137
138     /** A flag to indicate which assertion results should be saved to the test
139         results. Legitimate values include none, first, all. */

140     protected static String JavaDoc whichAssertionResults = FIRST;
141
142     protected static int assertionsResultsToSave = SAVE_NO_ASSERTIONS;
143
144     /** The string used to separate fields when stored to disk, for example,
145         the comma for CSV files. */

146     protected static String JavaDoc defaultDelimiter = ",";
147
148     private static DefaultConfigurationBuilder builder =
149         new DefaultConfigurationBuilder();
150
151     // Initialize various variables based on properties.
152
static {
153         readProperties();
154     } // static initialization
155

156     /**
157      * Private constructor to prevent instantiation.
158      */

159     private SaveService()
160     {
161     }
162
163     /**
164      * Read in the properties having to do with saving from a properties file.
165      */

166     protected static void readProperties()
167     {
168         Properties JavaDoc systemProps = System.getProperties();
169         Properties JavaDoc props = new Properties JavaDoc(systemProps);
170
171         try
172         {
173             props = JMeterUtils.getJMeterProperties();
174         }
175         catch (Exception JavaDoc e)
176         {
177             log.error(
178                 "SaveService.readProperties: Problem loading properties file: ",
179                 e);
180         }
181
182         printFieldNames =
183             TRUE.equalsIgnoreCase(
184                 props.getProperty(PRINT_FIELD_NAMES_PROP, FALSE));
185
186         saveDataType =
187             TRUE.equalsIgnoreCase(props.getProperty(SAVE_DATA_TYPE_PROP, TRUE));
188
189         saveLabel =
190             TRUE.equalsIgnoreCase(props.getProperty(SAVE_LABEL_PROP, TRUE));
191
192         saveResponseCode =
193             TRUE.equalsIgnoreCase(
194                 props.getProperty(SAVE_RESPONSE_CODE_PROP, TRUE));
195
196         saveResponseData =
197             TRUE.equalsIgnoreCase(
198                 props.getProperty(SAVE_RESPONSE_DATA_PROP, FALSE));
199
200         saveResponseMessage =
201             TRUE.equalsIgnoreCase(
202                 props.getProperty(SAVE_RESPONSE_MESSAGE_PROP, TRUE));
203
204         saveSuccessful =
205             TRUE.equalsIgnoreCase(
206                 props.getProperty(SAVE_SUCCESSFUL_PROP, TRUE));
207
208         saveThreadName =
209             TRUE.equalsIgnoreCase(
210                 props.getProperty(SAVE_THREAD_NAME_PROP, TRUE));
211
212         saveTime =
213             TRUE.equalsIgnoreCase(props.getProperty(SAVE_TIME_PROP, TRUE));
214
215         timeStampFormat =
216             props.getProperty(TIME_STAMP_FORMAT_PROP, MILLISECONDS);
217
218         printMilliseconds = MILLISECONDS.equalsIgnoreCase(timeStampFormat);
219
220         // Prepare for a pretty date
221
if (!printMilliseconds
222             && !NONE.equalsIgnoreCase(timeStampFormat)
223             && (timeStampFormat != null))
224         {
225             formatter = new SimpleDateFormat JavaDoc(timeStampFormat);
226         }
227
228         whichAssertionResults = props.getProperty(ASSERTION_RESULTS_PROP, NONE);
229         saveAssertionResultsFailureMessage =
230             TRUE.equalsIgnoreCase(
231                 props.getProperty(
232                     ASSERTION_RESULTS_FAILURE_MESSAGE_PROP,
233                     FALSE));
234
235         if (NONE.equals(whichAssertionResults))
236         {
237             assertionsResultsToSave = SAVE_NO_ASSERTIONS;
238         }
239         else if (FIRST.equals(whichAssertionResults))
240         {
241             assertionsResultsToSave = SAVE_FIRST_ASSERTION;
242         }
243         else if (ALL.equals(whichAssertionResults))
244         {
245             assertionsResultsToSave = SAVE_ALL_ASSERTIONS;
246         }
247
248         String JavaDoc howToSave = props.getProperty(OUTPUT_FORMAT_PROP, XML);
249
250         if (CSV.equals(howToSave))
251         {
252             outputFormat = SAVE_AS_CSV;
253         }
254         else
255         {
256             outputFormat = SAVE_AS_XML;
257         }
258
259         defaultDelimiter = props.getProperty(DEFAULT_DELIMITER_PROP, ",");
260     }
261
262     /**
263      * Return the format for the saved results, e.g., csv or xml.
264      *
265      * @return the format for the saved results
266      */

267     public static int getOutputFormat()
268     {
269         return outputFormat;
270     }
271
272     /**
273      * Return whether the field names should be printed to a delimited results
274      * file.
275      * @return whether the field names should be printed
276      */

277     public static boolean getPrintFieldNames()
278     {
279         return printFieldNames;
280     }
281     
282     /**
283      * Make a SampleResult given a delimited string.
284      * @param delim
285      * @return
286      * SampleResult
287      */

288     public static SampleResult makeResultFromDelimitedString(String JavaDoc delim)
289     {
290         SampleResult result = null;
291         long timeStamp = 0;
292         long elapsed = 0;
293         StringTokenizer JavaDoc splitter = new StringTokenizer JavaDoc(delim,defaultDelimiter);
294         String JavaDoc text = null;
295         if (printMilliseconds)
296         {
297             text = splitter.nextToken();
298             timeStamp = Long.parseLong(text);
299         }
300            else if (formatter != null)
301            {
302                text = splitter.nextToken();
303                try
304             {
305                 Date JavaDoc stamp = formatter.parse(text);
306                 timeStamp = stamp.getTime();
307             }
308             catch (ParseException JavaDoc e)
309             {
310                 e.printStackTrace();
311             }
312            }
313         
314            if (saveTime)
315            {
316                text = splitter.nextToken();
317                elapsed = Long.parseLong(text);
318            }
319         
320            result = new SampleResult(timeStamp,elapsed);
321            
322            if (saveLabel)
323            {
324                text = splitter.nextToken();
325                result.setSampleLabel(text);
326            }
327            if (saveResponseCode)
328            {
329                text = splitter.nextToken();
330                result.setResponseCode(text);
331            }
332         
333            if (saveResponseMessage)
334            {
335                text = splitter.nextToken();
336                result.setResponseMessage(text);
337            }
338         
339            if (saveThreadName)
340            {
341                text = splitter.nextToken();
342                result.setThreadName(text);
343            }
344         
345            if (saveDataType)
346            {
347                text = splitter.nextToken();
348                result.setDataType(text);
349            }
350         
351            if (saveSuccessful)
352            {
353                text = splitter.nextToken();
354                result.setSuccessful(Boolean.valueOf(text).booleanValue());
355            }
356         
357            if (saveAssertionResultsFailureMessage)
358            {
359                text = splitter.nextToken();
360            }
361         return result;
362     }
363
364     /**
365      * Return whether the field names should be printed to the output file.
366      * @return whether the field names should be printed to the output file
367      */

368     public static String JavaDoc printableFieldNamesToString()
369     {
370         StringBuffer JavaDoc text = new StringBuffer JavaDoc();
371
372         if (printMilliseconds || (formatter != null))
373         {
374             text.append(SaveServiceConstants.TIME_STAMP);
375             text.append(defaultDelimiter);
376         }
377
378         if (saveTime)
379         {
380             text.append(SaveServiceConstants.TIME);
381             text.append(defaultDelimiter);
382         }
383
384         if (saveLabel)
385         {
386             text.append(SaveServiceConstants.LABEL);
387             text.append(defaultDelimiter);
388         }
389
390         if (saveResponseCode)
391         {
392             text.append(SaveServiceConstants.RESPONSE_CODE);
393             text.append(defaultDelimiter);
394         }
395
396         if (saveResponseMessage)
397         {
398             text.append(SaveServiceConstants.RESPONSE_MESSAGE);
399             text.append(defaultDelimiter);
400         }
401
402         if (saveThreadName)
403         {
404             text.append(SaveServiceConstants.THREAD_NAME);
405             text.append(defaultDelimiter);
406         }
407
408         if (saveDataType)
409         {
410             text.append(SaveServiceConstants.DATA_TYPE);
411             text.append(defaultDelimiter);
412         }
413
414         if (saveSuccessful)
415         {
416             text.append(SaveServiceConstants.SUCCESSFUL);
417             text.append(defaultDelimiter);
418         }
419
420         if (saveAssertionResultsFailureMessage)
421         {
422             text.append(SaveServiceConstants.FAILURE_MESSAGE);
423             text.append(defaultDelimiter);
424         }
425
426         String JavaDoc resultString = null;
427         int size = text.length();
428         int delSize = defaultDelimiter.length();
429
430         // Strip off the trailing delimiter
431
if (size >= delSize)
432         {
433             resultString = text.substring(0, size - delSize);
434         }
435         else
436         {
437             resultString = text.toString();
438         }
439         return resultString;
440     }
441
442     public static void saveSubTree(HashTree subTree, OutputStream JavaDoc writer)
443         throws IOException JavaDoc
444     {
445         Configuration config =
446             (Configuration) getConfigsFromTree(subTree).get(0);
447         DefaultConfigurationSerializer saver =
448             new DefaultConfigurationSerializer();
449
450         saver.setIndent(true);
451         try
452         {
453             saver.serialize(writer, config);
454         }
455         catch (SAXException JavaDoc e)
456         {
457             throw new IOException JavaDoc("SAX implementation problem");
458         }
459         catch (ConfigurationException e)
460         {
461             throw new IOException JavaDoc("Problem using Avalon Configuration tools");
462         }
463     }
464
465     public static SampleResult getSampleResult(Configuration config)
466     {
467         SampleResult result = new SampleResult(
468                                   config.getAttributeAsLong(TIME_STAMP, 0L),
469                                   config.getAttributeAsLong(TIME, 0L));
470
471         result.setThreadName(config.getAttribute(THREAD_NAME, ""));
472         result.setDataType(config.getAttribute(DATA_TYPE, ""));
473         result.setResponseCode(config.getAttribute(RESPONSE_CODE, ""));
474         result.setResponseMessage(config.getAttribute(RESPONSE_MESSAGE, ""));
475         result.setSuccessful(config.getAttributeAsBoolean(SUCCESSFUL, false));
476         result.setSampleLabel(config.getAttribute(LABEL, ""));
477         result.setResponseData(getBinaryData(config.getChild(BINARY)));
478         Configuration[] subResults = config.getChildren(SAMPLE_RESULT_TAG_NAME);
479
480         for (int i = 0; i < subResults.length; i++)
481         {
482             result.addSubResult(getSampleResult(subResults[i]));
483         }
484         Configuration[] assResults =
485             config.getChildren(ASSERTION_RESULT_TAG_NAME);
486
487         for (int i = 0; i < assResults.length; i++)
488         {
489             result.addAssertionResult(getAssertionResult(assResults[i]));
490         }
491
492         Configuration[] samplerData = config.getChildren("property");
493         for (int i = 0; i < samplerData.length; i++)
494         {
495             result.setSamplerData(samplerData[i].getValue(""));
496         }
497         return result;
498     }
499
500     private static List JavaDoc getConfigsFromTree(HashTree subTree)
501     {
502         Iterator JavaDoc iter = subTree.list().iterator();
503         List JavaDoc configs = new LinkedList JavaDoc();
504
505         while (iter.hasNext())
506         {
507             TestElement item = (TestElement) iter.next();
508             DefaultConfiguration config =
509                 new DefaultConfiguration("node", "node");
510
511             config.addChild(getConfigForTestElement(null, item));
512             List JavaDoc configList = getConfigsFromTree(subTree.getTree(item));
513             Iterator JavaDoc iter2 = configList.iterator();
514
515             while (iter2.hasNext())
516             {
517                 config.addChild((Configuration) iter2.next());
518             }
519             configs.add(config);
520         }
521         return configs;
522     }
523
524     public static Configuration getConfiguration(byte[] bin)
525     {
526         DefaultConfiguration config =
527             new DefaultConfiguration(BINARY, "JMeter Save Service");
528
529         try
530         {
531             config.setValue(new String JavaDoc(bin, "UTF-8"));
532         }
533         catch (UnsupportedEncodingException JavaDoc e)
534         {
535             log.error("", e);
536         }
537         return config;
538     }
539
540     public static byte[] getBinaryData(Configuration config)
541     {
542         if (config == null)
543         {
544             return new byte[0];
545         }
546         try
547         {
548             return config.getValue("").getBytes("UTF-8");
549         }
550         catch (UnsupportedEncodingException JavaDoc e)
551         {
552             return new byte[0];
553         }
554     }
555
556     public static AssertionResult getAssertionResult(Configuration config)
557     {
558         AssertionResult result = new AssertionResult();
559         result.setError(config.getAttributeAsBoolean(ERROR, false));
560         result.setFailure(config.getAttributeAsBoolean(FAILURE, false));
561         result.setFailureMessage(config.getAttribute(FAILURE_MESSAGE, ""));
562         return result;
563     }
564
565     public static Configuration getConfiguration(AssertionResult assResult)
566     {
567         DefaultConfiguration config =
568             new DefaultConfiguration(
569                 ASSERTION_RESULT_TAG_NAME,
570                 "JMeter Save Service");
571
572         config.setAttribute(FAILURE_MESSAGE, assResult.getFailureMessage());
573         config.setAttribute(ERROR, "" + assResult.isError());
574         config.setAttribute(FAILURE, "" + assResult.isFailure());
575         return config;
576     }
577
578     /**
579      * This method determines the content of the result data that will be
580      * stored.
581      * @param result the object containing all of the data that has been
582      * collected.
583      * @param funcTest an indicator of whether the user wants all data
584      * recorded.
585      */

586     public static Configuration getConfiguration(
587         SampleResult result,
588         boolean funcTest)
589     {
590         DefaultConfiguration config =
591             new DefaultConfiguration(
592                 SAMPLE_RESULT_TAG_NAME,
593                 "JMeter Save Service");
594
595         if (saveTime)
596         {
597             config.setAttribute(TIME, "" + result.getTime());
598         }
599         if (saveLabel)
600         {
601             config.setAttribute(LABEL, result.getSampleLabel());
602         }
603         if (saveResponseCode)
604         {
605             config.setAttribute(RESPONSE_CODE, result.getResponseCode());
606         }
607         if (saveResponseMessage)
608         {
609             config.setAttribute(RESPONSE_MESSAGE, result.getResponseMessage());
610         }
611         if (saveThreadName)
612         {
613             config.setAttribute(THREAD_NAME, result.getThreadName());
614         }
615         if (saveDataType)
616         {
617             config.setAttribute(DATA_TYPE, result.getDataType());
618         }
619
620         if (printMilliseconds)
621         {
622             config.setAttribute(TIME_STAMP, "" + result.getTimeStamp());
623         }
624         else if (formatter != null)
625         {
626             String JavaDoc stamp = formatter.format(new Date JavaDoc(result.getTimeStamp()));
627
628             config.setAttribute(TIME_STAMP, stamp);
629         }
630
631         if (saveSuccessful)
632         {
633             config.setAttribute(
634                 SUCCESSFUL,
635                 JOrphanUtils.booleanToString(result.isSuccessful()));
636         }
637
638         SampleResult[] subResults = result.getSubResults();
639
640         for (int i = 0; i < subResults.length; i++)
641         {
642             config.addChild(getConfiguration(subResults[i], funcTest));
643         }
644
645         AssertionResult[] assResults = result.getAssertionResults();
646
647         if (funcTest)
648         {
649             config.addChild(
650             createConfigForString("samplerData", result.getSamplerData()));
651             for (int i = 0; i < assResults.length; i++)
652             {
653                 config.addChild(getConfiguration(assResults[i]));
654             }
655             config.addChild(getConfiguration(result.getResponseData()));
656         }
657         // Determine which of the assertion results to save and
658
// whether to save the response data
659
else
660         {
661             if (assertionsResultsToSave == SAVE_ALL_ASSERTIONS)
662             {
663                 config.addChild(
664                     createConfigForString(
665                         "samplerData",
666                         result.getSamplerData()));
667                 if (assResults != null)
668                 {
669                     for (int i = 0; i < assResults.length; i++)
670                     {
671                         config.addChild(getConfiguration(assResults[i]));
672                     }
673                 }
674             }
675             else if (
676                 (assertionsResultsToSave == SAVE_FIRST_ASSERTION)
677                     && assResults != null
678                     && assResults.length > 0)
679             {
680                 config.addChild(getConfiguration(assResults[0]));
681             }
682
683             if (saveResponseData)
684             {
685                 config.addChild(getConfiguration(result.getResponseData()));
686             }
687         }
688         return config;
689     }
690
691     /**
692      * Convert a result into a string, where the fields of the result are
693      * separated by the default delimiter.
694      *
695      * @param sample the test result to be converted
696      * @return the separated value representation of the result
697      */

698     public static String JavaDoc resultToDelimitedString(SampleResult sample)
699     {
700         return resultToDelimitedString(sample, defaultDelimiter);
701     }
702
703     /**
704      * Convert a result into a string, where the fields of the result are
705      * separated by a specified String.
706      *
707      * @param sample the test result to be converted
708      * @param delimiter the separation string
709      * @return the separated value representation of the result
710      */

711     public static String JavaDoc resultToDelimitedString(
712         SampleResult sample,
713         String JavaDoc delimiter)
714     {
715         StringBuffer JavaDoc text = new StringBuffer JavaDoc();
716
717         if (printMilliseconds)
718         {
719             text.append("" + sample.getTimeStamp());
720             text.append(delimiter);
721         }
722         else if (formatter != null)
723         {
724             String JavaDoc stamp = formatter.format(new Date JavaDoc(sample.getTimeStamp()));
725             text.append(stamp);
726             text.append(delimiter);
727         }
728
729         if (saveTime)
730         {
731             text.append("" + sample.getTime());
732             text.append(delimiter);
733         }
734
735         if (saveLabel)
736         {
737             text.append(sample.getSampleLabel());
738             text.append(delimiter);
739         }
740
741         if (saveResponseCode)
742         {
743             text.append(sample.getResponseCode());
744             text.append(delimiter);
745         }
746
747         if (saveResponseMessage)
748         {
749             text.append(sample.getResponseMessage());
750             text.append(delimiter);
751         }
752
753         if (saveThreadName)
754         {
755             text.append(sample.getThreadName());
756             text.append(delimiter);
757         }
758
759         if (saveDataType)
760         {
761             text.append(sample.getDataType());
762             text.append(delimiter);
763         }
764
765         if (saveSuccessful)
766         {
767             text.append("" + sample.isSuccessful());
768             text.append(delimiter);
769         }
770
771         if (saveAssertionResultsFailureMessage)
772         {
773             String JavaDoc message = null;
774             AssertionResult[] results = sample.getAssertionResults();
775
776             if (results.length > 0)
777             {
778                 message = results[0].getFailureMessage();
779             }
780
781             if (message == null)
782             {
783                 message = "";
784             }
785             text.append(message);
786             text.append(delimiter);
787         }
788         // text.append(sample.getSamplerData().toString());
789
// text.append(getAssertionResult(sample));
790

791         String JavaDoc resultString = null;
792         int size = text.length();
793         int delSize = delimiter.length();
794
795         // Strip off the trailing delimiter
796
if (size >= delSize)
797         {
798             resultString = text.substring(0, size - delSize);
799         }
800         else
801         {
802             resultString = text.toString();
803         }
804         return resultString;
805     }
806
807     public static Configuration getConfigForTestElement(
808         String JavaDoc named,
809         TestElement item)
810     {
811         TestElementSaver saver = new TestElementSaver(named);
812         item.traverse(saver);
813         Configuration config = saver.getConfiguration();
814         /* DefaultConfiguration config =
815            new DefaultConfiguration("testelement", "testelement");
816         
817          if (named != null)
818          {
819              config.setAttribute("name", named);
820          }
821          if (item.getProperty(TestElement.TEST_CLASS) != null)
822          {
823              config.setAttribute("class",
824                     (String) item.getProperty(TestElement.TEST_CLASS));
825          }
826          else
827          {
828              config.setAttribute("class", item.getClass().getName());
829          }
830          Iterator iter = item.getPropertyNames().iterator();
831         
832          while (iter.hasNext())
833          {
834              String name = (String) iter.next();
835              Object value = item.getProperty(name);
836         
837              if (value instanceof TestElement)
838              {
839                  config.addChild(getConfigForTestElement(name,
840                         (TestElement) value));
841              }
842              else if (value instanceof Collection)
843              {
844                  config.addChild(createConfigForCollection(name,
845                         (Collection) value));
846              }
847              else if (value != null)
848              {
849                  config.addChild(createConfigForString(name, value.toString()));
850              }
851          }*/

852         return config;
853     }
854
855     /*
856      *
857      * NOTUSED
858     private static Configuration createConfigForCollection(
859         String propertyName,
860         Collection list)
861     {
862         DefaultConfiguration config =
863             new DefaultConfiguration("collection", "collection");
864
865         if (propertyName != null)
866         {
867             config.setAttribute("name", propertyName);
868         }
869         config.setAttribute("class", list.getClass().getName());
870         Iterator iter = list.iterator();
871
872         while (iter.hasNext())
873         {
874             Object item = iter.next();
875
876             if (item instanceof TestElement)
877             {
878                 config.addChild(
879                     getConfigForTestElement(null, (TestElement) item));
880             }
881             else if (item instanceof Collection)
882             {
883                 config.addChild(
884                     createConfigForCollection(null, (Collection) item));
885             }
886             else
887             {
888                 config.addChild(createConfigForString(item.toString()));
889             }
890         }
891         return config;
892     }
893     */

894
895     /*
896      * NOTUSED
897      *
898     private static Configuration createConfigForString(String value)
899     {
900         DefaultConfiguration config =
901             new DefaultConfiguration("string", "string");
902
903         config.setValue(value);
904         config.setAttribute(XML_SPACE, PRESERVE);
905         return config;
906     }
907     */

908
909
910     private static Configuration createConfigForString(
911         String JavaDoc name,
912         String JavaDoc value)
913     {
914         if (value == null)
915         {
916             value = "";
917         }
918         DefaultConfiguration config =
919             new DefaultConfiguration("property", "property");
920
921         config.setAttribute("name", name);
922         config.setValue(value);
923         config.setAttribute(XML_SPACE, PRESERVE);
924         return config;
925     }
926
927     public synchronized static HashTree loadSubTree(InputStream JavaDoc in)
928         throws IOException JavaDoc
929     {
930         try
931         {
932             Configuration config = builder.build(in);
933             HashTree loadedTree = generateNode(config);
934
935             return loadedTree;
936         }
937         catch (ConfigurationException e)
938         {
939             String JavaDoc message = "Problem loading using Avalon Configuration tools";
940             log.error(message, e);
941             throw new IOException JavaDoc(message);
942         }
943         catch (SAXException JavaDoc e)
944         {
945             String JavaDoc message = "Problem with SAX implementation";
946             log.error(message, e);
947             throw new IOException JavaDoc(message);
948         }
949     }
950
951     public static TestElement createTestElement(Configuration config)
952         throws
953             ConfigurationException,
954             ClassNotFoundException JavaDoc,
955             IllegalAccessException JavaDoc,
956             InstantiationException JavaDoc
957     {
958         TestElement element = null;
959
960         String JavaDoc testClass= (String JavaDoc) config.getAttribute("class");
961         element = (TestElement) Class.forName(
962             NameUpdater.getCurrentName(testClass)).newInstance();
963         Configuration[] children = config.getChildren();
964
965         for (int i = 0; i < children.length; i++)
966         {
967             if (children[i].getName().equals("property"))
968             {
969                 try
970                 {
971                     element.setProperty(createProperty(children[i], testClass));
972                 }
973                 catch (Exception JavaDoc ex)
974                 {
975                     log.error("Problem loading property", ex);
976                     element.setProperty(children[i].getAttribute("name"), "");
977                 }
978             }
979             else if (children[i].getName().equals("testelement"))
980             {
981                 element.setProperty(
982                     new TestElementProperty(
983                         children[i].getAttribute("name",""),
984                         createTestElement(children[i])));
985             }
986             else if (children[i].getName().equals("collection"))
987             {
988                 element.setProperty(
989                     new CollectionProperty(
990                         children[i].getAttribute("name",""),
991                         createCollection(children[i], testClass)));
992             }
993             else if (children[i].getName().equals("map"))
994             {
995                 element.setProperty(
996                     new MapProperty(
997                         children[i].getAttribute("name",""),
998                         createMap(children[i], testClass)));
999             }
1000        }
1001        return element;
1002    }
1003
1004    private static Collection JavaDoc createCollection(
1005            Configuration config, String JavaDoc testClass)
1006        throws
1007            ConfigurationException,
1008            ClassNotFoundException JavaDoc,
1009            IllegalAccessException JavaDoc,
1010            InstantiationException JavaDoc
1011    {
1012        Collection JavaDoc coll =
1013            (Collection JavaDoc) Class
1014                .forName((String JavaDoc) config.getAttribute("class"))
1015                .newInstance();
1016        Configuration[] items = config.getChildren();
1017
1018        for (int i = 0; i < items.length; i++)
1019        {
1020            if (items[i].getName().equals("property"))
1021            {
1022                coll.add(createProperty(items[i], testClass));
1023            }
1024            else if (items[i].getName().equals("testelement"))
1025            {
1026                coll.add(
1027                    new TestElementProperty(
1028                        items[i].getAttribute("name", ""),
1029                        createTestElement(items[i])));
1030            }
1031            else if (items[i].getName().equals("collection"))
1032            {
1033                coll.add(
1034                    new CollectionProperty(
1035                        items[i].getAttribute("name", ""),
1036                        createCollection(items[i], testClass)));
1037            }
1038            else if (items[i].getName().equals("string"))
1039            {
1040                coll.add(createProperty(items[i], testClass));
1041            }
1042            else if (items[i].getName().equals("map"))
1043            {
1044                coll.add(
1045                    new MapProperty(
1046                        items[i].getAttribute("name", ""),
1047                        createMap(items[i], testClass)));
1048            }
1049        }
1050        return coll;
1051    }
1052
1053    private static JMeterProperty createProperty(Configuration config, String JavaDoc testClass)
1054        throws
1055            ConfigurationException,
1056            IllegalAccessException JavaDoc,
1057            ClassNotFoundException JavaDoc,
1058            InstantiationException JavaDoc
1059    {
1060        String JavaDoc value = config.getValue("");
1061        String JavaDoc name= config.getAttribute("name", value);
1062        String JavaDoc type= config.getAttribute("propType", StringProperty.class.getName());
1063        
1064        // Do upgrade translation:
1065
name= NameUpdater.getCurrentName(name, testClass);
1066        if (TestElement.GUI_CLASS.equals(name) || TestElement.TEST_CLASS.equals(name))
1067        {
1068            value= NameUpdater.getCurrentName(value);
1069        }
1070        else
1071        {
1072            value= NameUpdater.getCurrentName(value, name, testClass);
1073        }
1074        
1075        // Create the property:
1076
JMeterProperty prop = (JMeterProperty) Class.forName(type).newInstance();
1077        prop.setName(name);
1078        prop.setObjectValue(value);
1079
1080        return prop;
1081    }
1082
1083    private static Map JavaDoc createMap(Configuration config, String JavaDoc testClass)
1084        throws
1085            ConfigurationException,
1086            ClassNotFoundException JavaDoc,
1087            IllegalAccessException JavaDoc,
1088            InstantiationException JavaDoc
1089    {
1090        Map JavaDoc map =
1091            (Map JavaDoc) Class
1092                .forName((String JavaDoc) config.getAttribute("class"))
1093                .newInstance();
1094        Configuration[] items = config.getChildren();
1095
1096        for (int i = 0; i < items.length; i++)
1097        {
1098            if (items[i].getName().equals("property"))
1099            {
1100                JMeterProperty prop = createProperty(items[i], testClass);
1101                map.put(prop.getName(), prop);
1102            }
1103            else if (items[i].getName().equals("testelement"))
1104            {
1105                map.put(
1106                    items[i].getAttribute("name",""),
1107                    new TestElementProperty(
1108                        items[i].getAttribute("name", ""),
1109                        createTestElement(items[i])));
1110            }
1111            else if (items[i].getName().equals("collection"))
1112            {
1113                map.put(
1114                    items[i].getAttribute("name"),
1115                    new CollectionProperty(
1116                        items[i].getAttribute("name", ""),
1117                        createCollection(items[i], testClass)));
1118            }
1119            else if (items[i].getName().equals("map"))
1120            {
1121                map.put(
1122                    items[i].getAttribute("name", ""),
1123                    new MapProperty(
1124                        items[i].getAttribute("name", ""),
1125                        createMap(items[i], testClass)));
1126            }
1127        }
1128        return map;
1129    }
1130
1131    private static HashTree generateNode(Configuration config)
1132    {
1133        TestElement element = null;
1134
1135        try
1136        {
1137            element = createTestElement(config.getChild("testelement"));
1138        }
1139        catch (Exception JavaDoc e)
1140        {
1141            log.error("Problem loading part of file", e);
1142            return null;
1143        }
1144        HashTree subTree = new ListedHashTree(element);
1145        Configuration[] subNodes = config.getChildren("node");
1146
1147        for (int i = 0; i < subNodes.length; i++)
1148        {
1149            HashTree t = generateNode(subNodes[i]);
1150
1151            if (t != null)
1152            {
1153                subTree.add(element, t);
1154            }
1155        }
1156        return subTree;
1157    }
1158
1159    public static class Test extends JMeterTestCase
1160    {
1161        private static final String JavaDoc[] FILES =
1162            new String JavaDoc[] {
1163                "AssertionTestPlan.jmx",
1164                "AuthManagerTestPlan.jmx",
1165                "HeaderManagerTestPlan.jmx",
1166                "InterleaveTestPlan2.jmx",
1167                "InterleaveTestPlan.jmx",
1168                "LoopTestPlan.jmx",
1169                "Modification Manager.jmx",
1170                "OnceOnlyTestPlan.jmx",
1171                "proxy.jmx",
1172                "ProxyServerTestPlan.jmx",
1173                "SimpleTestPlan.jmx",
1174                "GuiTest.jmx",
1175                };
1176
1177        public Test(String JavaDoc name)
1178        {
1179            super(name);
1180        }
1181
1182        public void setUp()
1183        {}
1184
1185        public void testLoadAndSave() throws java.io.IOException JavaDoc
1186        {
1187            byte[] original = new byte[1000000];
1188
1189            boolean failed = false; // Did a test fail?
1190

1191            for (int i = 0; i < FILES.length; i++)
1192            {
1193                InputStream JavaDoc in =
1194                    new FileInputStream JavaDoc(new File JavaDoc("testfiles/" + FILES[i]));
1195                int len = in.read(original);
1196
1197                in.close();
1198
1199                in = new ByteArrayInputStream JavaDoc(original, 0, len);
1200                HashTree tree = loadSubTree(in);
1201
1202                in.close();
1203
1204                ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc(1000000);
1205
1206                saveSubTree(tree, out);
1207                out.close();
1208
1209                // We only check the length of the result. Comparing the
1210
// actual result (out.toByteArray==original) will usually
1211
// fail, because the order of the properties within each
1212
// test element may change. Comparing the lengths should be
1213
// enough to detect most problem cases...
1214
if (len != out.size())
1215                {
1216                    failed=true;
1217                    System.out.println();
1218                    System.out.println(
1219                        "Loading file bin/testfiles/"
1220                            + FILES[i]
1221                            + " and "
1222                            + "saving it back changes its size from "+len+" to "+out.size()+".");
1223                }
1224
1225                // Note this test will fail if a property is added or
1226
// removed to any of the components used in the test
1227
// files. The way to solve this is to appropriately change
1228
// the test file.
1229
}
1230            if (failed) //TODO make these separate tests?
1231
{
1232                fail("One or more failures detected");
1233            }
1234        }
1235    }
1236}
1237
Popular Tags