KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > util > JMeterUtils


1 // $Header: /home/cvs/jakarta-jmeter/src/core/org/apache/jmeter/util/JMeterUtils.java,v 1.66.2.3 2005/01/08 02:28:06 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.util;
20
21 import java.awt.Dimension JavaDoc;
22 import java.awt.event.ActionListener JavaDoc;
23 import java.io.BufferedReader JavaDoc;
24 import java.io.File JavaDoc;
25 import java.io.FileInputStream JavaDoc;
26 import java.io.IOException JavaDoc;
27 import java.io.InputStream JavaDoc;
28 import java.io.InputStreamReader JavaDoc;
29 import java.util.Enumeration JavaDoc;
30 import java.util.Hashtable JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.Locale JavaDoc;
33 import java.util.MissingResourceException JavaDoc;
34 import java.util.Properties JavaDoc;
35 import java.util.Random JavaDoc;
36 import java.util.ResourceBundle JavaDoc;
37 import java.util.StringTokenizer JavaDoc;
38 import java.util.Vector JavaDoc;
39
40 import javax.swing.ImageIcon JavaDoc;
41 import javax.swing.JButton JavaDoc;
42 import javax.swing.JComboBox JavaDoc;
43 import javax.swing.JOptionPane JavaDoc;
44 //import javax.xml.parsers.SAXParserFactory;
45

46 import org.apache.jmeter.gui.GuiPackage;
47 import org.apache.jorphan.logging.LoggingManager;
48 import org.apache.jorphan.test.UnitTestManager;
49 import org.apache.jorphan.util.JOrphanUtils;
50 import org.apache.log.Logger;
51 import org.apache.oro.text.PatternCacheLRU;
52 import org.apache.oro.text.regex.Perl5Compiler;
53 import org.apache.oro.text.regex.Perl5Matcher;
54 import org.xml.sax.XMLReader JavaDoc;
55
56 /**
57  * This class contains the static utility methods used by JMeter.
58  *
59  * @version $Revision: 1.66.2.3 $ updated on $Date: 2005/01/08 02:28:06 $
60  */

61 public class JMeterUtils implements UnitTestManager
62 {
63     private static PatternCacheLRU patternCache =
64         new PatternCacheLRU(1000, new Perl5Compiler());
65
66     transient private static Logger log = LoggingManager.getLoggerForClass();
67     
68     private static final String JavaDoc EXPERT_MODE_PROPERTY="jmeter.expertMode";
69
70     // Not used currently
71
// private static final SAXParserFactory xmlFactory;
72
// static {
73
// SAXParserFactory temp = null;
74
// try
75
// {
76
// temp = SAXParserFactory.newInstance();
77
// }
78
// catch (Exception e)
79
// {
80
// log.error("", e);
81
// temp = null;
82
// }
83
// xmlFactory = temp;
84
// }
85
private static Properties JavaDoc appProperties;
86     private static Vector JavaDoc localeChangeListeners = new Vector JavaDoc();
87     private static Locale JavaDoc locale;
88     private static ResourceBundle JavaDoc resources;
89
90     private static ThreadLocal JavaDoc localMatcher = new ThreadLocal JavaDoc()
91     {
92         protected Object JavaDoc initialValue()
93         {
94             return new Perl5Matcher();
95         }
96     };
97
98     //Provide Random numbers to whomever wants one
99
private static Random JavaDoc rand = new Random JavaDoc();
100
101     /**
102      * Gets Perl5Matcher for this thread.
103      */

104     public static Perl5Matcher getMatcher()
105     {
106         return (Perl5Matcher) localMatcher.get();
107     }
108
109     /**
110      * This method is used by the init method to load the property file that
111      * may even reside in the user space, or in the classpath under
112      * org.apache.jmeter.jmeter.properties.
113      *
114      *@param file the file to load
115      *@return the Properties from the file
116      */

117     public static Properties JavaDoc getProperties(String JavaDoc file)
118     {
119         Properties JavaDoc p = new Properties JavaDoc(System.getProperties());
120         try
121         {
122             File JavaDoc f = new File JavaDoc(file);
123             p.load(new FileInputStream JavaDoc(f));
124         }
125         catch (Exception JavaDoc e)
126         {
127             try
128             {
129                 InputStream JavaDoc is = ClassLoader.getSystemResourceAsStream(
130                     "org/apache/jmeter/jmeter.properties");
131                 if (is == null) throw new RuntimeException JavaDoc("Could not read JMeter properties file");
132                 p.load(is);
133             }
134             catch (IOException JavaDoc ex)
135             {
136                 // JMeter.fail("Could not read internal resource. " +
137
// "Archive is broken.");
138
}
139         }
140         appProperties = p;
141         LoggingManager.initializeLogging(appProperties);
142         log = LoggingManager.getLoggerForClass();
143         String JavaDoc loc = appProperties.getProperty("language");
144         if (loc != null)
145         {
146             setLocale(new Locale JavaDoc(loc, ""));
147         }
148         else
149         {
150             setLocale(Locale.getDefault());
151         }
152         return p;
153     }
154
155     public static PatternCacheLRU getPatternCache()
156     {
157         return patternCache;
158     }
159
160     public void initializeProperties(String JavaDoc file)
161     {
162         System.out.println("Initializing Properties: " + file);
163         getProperties(file);
164         String JavaDoc home;
165         int pathend=file.lastIndexOf("/");
166         if (pathend == -1){// No path separator found, must be in current directory
167
home = ".";
168         } else {
169             home = file.substring(0, pathend);
170         }
171         home = new File JavaDoc(home + "/..").getAbsolutePath();
172         System.out.println("Setting JMeter home: " + home);
173         setJMeterHome(home);
174     }
175     public static String JavaDoc[] getSearchPaths()
176     {
177         String JavaDoc p= JMeterUtils.getPropDefault("search_paths", null);
178         String JavaDoc[] result= new String JavaDoc[1];
179         
180         if (p!=null) {
181             String JavaDoc[] paths= JOrphanUtils.split(p,";");// was p.split(";") - JDK1.4
182
result= new String JavaDoc[paths.length+1];
183             for (int i=1; i<result.length; i++)
184             {
185                 result[i]= paths[i-1];
186             }
187         }
188         result[0]= getJMeterHome() + "/lib/ext";
189         return result;
190     }
191
192     /**
193      * Provide random numbers
194      * @param r - the upper bound (exclusive)
195      */

196     public static int getRandomInt(int r)
197     {
198         return rand.nextInt(r);
199     }
200
201     /**
202      * Changes the current locale: re-reads resource strings and notifies
203      * listeners.
204      *
205      * author Oliver Rossmueller
206      * @param loc - new locale
207      */

208     public static void setLocale(Locale JavaDoc loc)
209     {
210         locale = loc;
211         resources =
212             ResourceBundle.getBundle(
213                 "org.apache.jmeter.resources.messages",
214                 locale);
215         notifyLocaleChangeListeners();
216     }
217
218     /**
219      * Gets the current locale.
220      *
221      * author Oliver Rossmueller
222      * @return current locale
223      */

224     public static Locale JavaDoc getLocale()
225     {
226         return locale;
227     }
228
229     /**
230      * author Oliver Rossmueller
231      */

232     public static void addLocaleChangeListener(LocaleChangeListener listener)
233     {
234         localeChangeListeners.add(listener);
235     }
236
237     /**
238      * author Oliver Rossmueller
239      */

240     public static void removeLocaleChangeListener(LocaleChangeListener listener)
241     {
242         localeChangeListeners.remove(listener);
243     }
244
245     /**
246      * Notify all listeners interested in locale changes.
247      *
248      * author Oliver Rossmueller
249      */

250     private static void notifyLocaleChangeListeners()
251     {
252         LocaleChangeEvent event =
253             new LocaleChangeEvent(JMeterUtils.class, locale);
254         Iterator JavaDoc iterator = ((Vector JavaDoc)localeChangeListeners.clone()).iterator();
255
256         while (iterator.hasNext())
257         {
258             LocaleChangeListener listener =
259                 (LocaleChangeListener) iterator.next();
260             listener.localeChanged(event);
261         }
262     }
263
264     /**
265      * Gets the resource string for this key.
266      *
267      * If the resource is not found, a warning is logged
268      *
269      * @param key the key in the resource file
270      * @return the resource string if the key is found; otherwise, return
271      * "[res_key="+key+"]"
272      */

273     public static String JavaDoc getResString(String JavaDoc key)
274     {
275         return getResStringDefault(key,RES_KEY_PFX+key+"]");
276     }
277     public static final String JavaDoc RES_KEY_PFX="[res_key=";
278     
279     /**
280      * Gets the resource string for this key.
281      *
282      * If the resource is not found, a warning is logged
283      *
284      * @param key the key in the resource file
285      * @param defaultValue - the default value
286      *
287      * @return the resource string if the key is found;
288      * otherwise, return the default
289      * @deprecated Only intended for use in development; use getResString(String) normally
290      */

291     public static String JavaDoc getResString(String JavaDoc key, String JavaDoc defaultValue)
292     {
293         return getResStringDefault(key,defaultValue);
294     }
295     
296     /*
297      * Helper method to do the actual work of fetching resources;
298      * allows getResString(S,S) to be deprecated without affecting getResString(S);
299      */

300     private static String JavaDoc getResStringDefault(String JavaDoc key, String JavaDoc defaultValue)
301     {
302         if (key == null)
303         {
304             return null;
305         }
306         key = key.replace(' ', '_');
307         key = key.toLowerCase();
308         String JavaDoc resString = null;
309         try
310         {
311             resString = resources.getString(key);
312         }
313         catch (MissingResourceException JavaDoc mre)
314         {
315             log.warn("ERROR! Resource string not found: [" + key + "]");
316             resString = defaultValue;
317         }
318         return resString;
319     }
320     /**
321      * This gets the currently defined appProperties. It can only be called
322      * after the {@link #getProperties(String)} method is called.
323      *
324      * @return The JMeterProperties value
325      */

326     public static Properties JavaDoc getJMeterProperties()
327     {
328         return appProperties;
329     }
330     /**
331      * This looks for the requested image in the classpath under
332      * org.apache.jmeter.images. <name>
333      *
334      * @param name Description of Parameter
335      * @return The Image value
336      */

337     public static ImageIcon JavaDoc getImage(String JavaDoc name)
338     {
339         try
340         {
341             return new ImageIcon JavaDoc(
342                 JMeterUtils.class.getClassLoader().getResource(
343                     "org/apache/jmeter/images/" + name.trim()));
344         }
345         catch (NullPointerException JavaDoc e)
346         {
347             log.warn("no icon for " + name);
348             return null;
349         }
350     }
351     public static String JavaDoc getResourceFileAsText(String JavaDoc name)
352     {
353         try
354         {
355             String JavaDoc lineEnd = System.getProperty("line.separator");
356             BufferedReader JavaDoc fileReader =
357                 new BufferedReader JavaDoc(
358                     new InputStreamReader JavaDoc(
359                         JMeterUtils.class.getClassLoader().getResourceAsStream(
360                             name)));
361             StringBuffer JavaDoc text = new StringBuffer JavaDoc();
362             String JavaDoc line = "NOTNULL";
363             while (line != null)
364             {
365                 line = fileReader.readLine();
366                 if (line != null)
367                 {
368                     text.append(line);
369                     text.append(lineEnd);
370                 }
371             }
372             fileReader.close();
373             return text.toString();
374         }
375         catch (NullPointerException JavaDoc e) // Cannot find file
376
{
377             return "";
378         }
379         catch (IOException JavaDoc e)
380         {
381             return "";
382         }
383     }
384     /**
385      * Creates the vector of Timers plugins.
386      *
387      *@param properties Description of Parameter
388      *@return The Timers value
389      */

390     public static Vector JavaDoc getTimers(Properties JavaDoc properties)
391     {
392         return instantiate(
393             getVector(properties, "timer."),
394             "org.apache.jmeter.timers.Timer");
395     }
396     /**
397      * Creates the vector of visualizer plugins.
398      *
399      *@param properties Description of Parameter
400      *@return The Visualizers value
401      */

402     public static Vector JavaDoc getVisualizers(Properties JavaDoc properties)
403     {
404         return instantiate(
405             getVector(properties, "visualizer."),
406             "org.apache.jmeter.visualizers.Visualizer");
407     }
408     /**
409      * Creates a vector of SampleController plugins.
410      *
411      *@param properties The properties with information about the samplers
412      *@return The Controllers value
413      */

414     //TODO - does not appear to be called directly
415
public static Vector JavaDoc getControllers(Properties JavaDoc properties)
416     {
417         String JavaDoc name = "controller.";
418         Vector JavaDoc v = new Vector JavaDoc();
419         Enumeration JavaDoc names = properties.keys();
420         while (names.hasMoreElements())
421         {
422             String JavaDoc prop = (String JavaDoc) names.nextElement();
423             if (prop.startsWith(name))
424             {
425                 Object JavaDoc o =
426                     instantiate(
427                         properties.getProperty(prop),
428                         "org.apache.jmeter.control.SamplerController");
429                 v.addElement(o);
430             }
431         }
432         return v;
433     }
434     /**
435      * Create a string of class names for a particular SamplerController
436      *
437      *@param properties The properties with info about the samples.
438      *@param name The name of the sampler controller.
439      *@return The TestSamples value
440      */

441     public static String JavaDoc[] getTestSamples(Properties JavaDoc properties, String JavaDoc name)
442     {
443         return (String JavaDoc[]) getVector(properties, name + ".testsample").toArray(
444             new String JavaDoc[0]);
445     }
446     /**
447      * Create an instance of an org.xml.sax.Parser
448      *
449      * @deprecated use the plain version instead. We are using JAXP!
450      *@param properties The properties file containing the parser's class name
451      *@return The XMLParser value
452      */

453     public static XMLReader JavaDoc getXMLParser(Properties JavaDoc properties)
454     {
455         return getXMLParser();
456     }
457     /**
458      * Create an instance of an org.xml.sax.Parser based on the default props.
459      *
460      *@return The XMLParser value
461      */

462     public static XMLReader JavaDoc getXMLParser()
463     {
464         XMLReader JavaDoc reader = null;
465         try
466         {
467             reader =
468                 (XMLReader JavaDoc) instantiate(getPropDefault("xml.parser",
469                     "org.apache.xerces.parsers.SAXParser"),
470                     "org.xml.sax.XMLReader");
471             //reader = xmlFactory.newSAXParser().getXMLReader();
472
}
473         catch (Exception JavaDoc e)
474         {
475             reader =
476                 (XMLReader JavaDoc) instantiate(getPropDefault("xml.parser",
477                     "org.apache.xerces.parsers.SAXParser"),
478                     "org.xml.sax.XMLReader");
479         }
480         return reader;
481     }
482     
483     /**
484      * Creates the vector of alias strings.
485      *
486      *@param properties Description of Parameter
487      *@return The Alias value
488      */

489     public static Hashtable JavaDoc getAlias(Properties JavaDoc properties)
490     {
491         return getHashtable(properties, "alias.");
492     }
493     
494     /**
495      * Creates a vector of strings for all the properties that start with a
496      * common prefix.
497      *
498      * @param properties Description of Parameter
499      * @param name Description of Parameter
500      * @return The Vector value
501      */

502     public static Vector JavaDoc getVector(Properties JavaDoc properties, String JavaDoc name)
503     {
504         Vector JavaDoc v = new Vector JavaDoc();
505         Enumeration JavaDoc names = properties.keys();
506         while (names.hasMoreElements())
507         {
508             String JavaDoc prop = (String JavaDoc) names.nextElement();
509             if (prop.startsWith(name))
510             {
511                 v.addElement(properties.getProperty(prop));
512             }
513         }
514         return v;
515     }
516     
517     /**
518      * Creates a table of strings for all the properties that start with a
519      * common prefix.
520      *
521      * @param properties Description of Parameter
522      * @param name Description of Parameter
523      * @return The Hashtable value
524      */

525     public static Hashtable JavaDoc getHashtable(Properties JavaDoc properties, String JavaDoc name)
526     {
527         Hashtable JavaDoc t = new Hashtable JavaDoc();
528         Enumeration JavaDoc names = properties.keys();
529         while (names.hasMoreElements())
530         {
531             String JavaDoc prop = (String JavaDoc) names.nextElement();
532             if (prop.startsWith(name))
533             {
534                 t.put(
535                     prop.substring(name.length()),
536                     properties.getProperty(prop));
537             }
538         }
539         return t;
540     }
541     
542     /**
543      * Get a int value with default if not present.
544      *
545      *@param propName the name of the property.
546      *@param defaultVal the default value.
547      *@return The PropDefault value
548      */

549     public static int getPropDefault(String JavaDoc propName, int defaultVal)
550     {
551         int ans;
552         try
553         {
554             ans =
555                 (Integer
556                     .valueOf(
557                         appProperties
558                             .getProperty(propName, Integer.toString(defaultVal))
559                             .trim()))
560                     .intValue();
561         }
562         catch (Exception JavaDoc e)
563         {
564             ans = defaultVal;
565         }
566         return ans;
567     }
568     /**
569      * Get a boolean value with default if not present.
570      *
571      *@param propName the name of the property.
572      *@param defaultVal the default value.
573      *@return The PropDefault value
574      */

575     public static boolean getPropDefault(String JavaDoc propName, boolean defaultVal)
576     {
577         boolean ans;
578         try
579         {
580             String JavaDoc strVal =
581                 appProperties
582                     .getProperty(propName, JOrphanUtils.booleanToString(defaultVal))
583                     .trim();
584             if (strVal.equalsIgnoreCase("true")
585                 || strVal.equalsIgnoreCase("t"))
586             {
587                 ans = true;
588             }
589             else if (
590                 strVal.equalsIgnoreCase("false")
591                     || strVal.equalsIgnoreCase("f"))
592             {
593                 ans = false;
594             }
595             else
596             {
597                 ans = ((Integer.valueOf(strVal)).intValue() == 1);
598             }
599         }
600         catch (Exception JavaDoc e)
601         {
602             ans = defaultVal;
603         }
604         return ans;
605     }
606     /**
607      * Get a long value with default if not present.
608      *
609      *@param propName the name of the property.
610      *@param defaultVal the default value.
611      *@return The PropDefault value
612      */

613     public static long getPropDefault(String JavaDoc propName, long defaultVal)
614     {
615         long ans;
616         try
617         {
618             ans =
619                 (Long
620                     .valueOf(
621                         appProperties
622                             .getProperty(propName, Long.toString(defaultVal))
623                             .trim()))
624                     .longValue();
625         }
626         catch (Exception JavaDoc e)
627         {
628             ans = defaultVal;
629         }
630         return ans;
631     }
632     /**
633      * Get a String value with default if not present.
634      *
635      *@param propName the name of the property.
636      *@param defaultVal the default value.
637      *@return The PropDefault value
638      */

639     public static String JavaDoc getPropDefault(String JavaDoc propName, String JavaDoc defaultVal)
640     {
641         String JavaDoc ans;
642         try
643         {
644             ans = appProperties.getProperty(propName, defaultVal).trim();
645         }
646         catch (Exception JavaDoc e)
647         {
648             ans = defaultVal;
649         }
650         return ans;
651     }
652     /**
653      * Get a String value with NO default if not present.
654      *
655      *@param propName the name of the property.
656      *@return The PropDefault value
657      */

658     public static String JavaDoc getProperty(String JavaDoc propName)
659     {
660         String JavaDoc ans = null;
661         try
662         {
663             ans = appProperties.getProperty(propName);
664         }
665         catch (Exception JavaDoc e)
666         {
667             ans = null;
668         }
669         return ans;
670     }
671
672     /**
673      * Set a String value
674      *
675      *@param propName the name of the property.
676      *@param propValue the value of the property
677      *@return the previous value of the property
678      */

679     public static Object JavaDoc setProperty(String JavaDoc propName, String JavaDoc propValue)
680     {
681          return appProperties.setProperty(propName,propValue);
682     }
683
684     /**
685      * Sets the selection of the JComboBox to the Object 'name' from the list
686      * in namVec.
687      */

688     public static void selJComboBoxItem(
689         Properties JavaDoc properties,
690         JComboBox JavaDoc combo,
691         Vector JavaDoc namVec,
692         String JavaDoc name)
693     {
694         int idx = namVec.indexOf(name);
695         combo.setSelectedIndex(idx);
696         // Redisplay.
697
combo.updateUI();
698         return;
699     }
700
701     /**
702      * Instatiate an object and guarantee its class.
703      *
704      *@param className The name of the class to instantiate.
705      *@param impls The name of the class it subclases.
706      *@return Description of the Returned Value
707      */

708     public static Object JavaDoc instantiate(String JavaDoc className, String JavaDoc impls)
709     {
710         if (className != null)
711         {
712             className=className.trim();
713         }
714
715         if (impls != null)
716         {
717             impls=impls.trim();
718         }
719
720         try
721         {
722             Class JavaDoc c = Class.forName(impls);
723             try
724             {
725                 Class JavaDoc o = Class.forName(className);
726                 Object JavaDoc res = o.newInstance();
727                 if (c.isInstance(res))
728                 {
729                     return res;
730                 }
731                 else
732                 {
733                     throw new IllegalArgumentException JavaDoc(
734                         className + " is not an instance of " + impls);
735                 }
736             }
737             catch (ClassNotFoundException JavaDoc e)
738             {
739                 log.error(
740                     "Error loading class "
741                         + className
742                         + ": class is not found");
743             }
744             catch (IllegalAccessException JavaDoc e)
745             {
746                 log.error(
747                     "Error loading class "
748                         + className
749                         + ": does not have access");
750             }
751             catch (InstantiationException JavaDoc e)
752             {
753                 log.error(
754                     "Error loading class "
755                         + className
756                         + ": could not instantiate");
757             }
758             catch (NoClassDefFoundError JavaDoc e)
759             {
760                 log.error(
761                     "Error loading class "
762                         + className
763                         + ": couldn't find class "
764                         + e.getMessage());
765             }
766         }
767         catch (ClassNotFoundException JavaDoc e)
768         {
769             log.error("Error loading class " + impls + ": was not found.");
770         }
771         return null;
772     }
773     /**
774      * Instantiate a vector of classes
775      *
776      *@param v Description of Parameter
777      *@param className Description of Parameter
778      *@return Description of the Returned Value
779      */

780     public static Vector JavaDoc instantiate(Vector JavaDoc v, String JavaDoc className)
781     {
782         Vector JavaDoc i = new Vector JavaDoc();
783         try
784         {
785             Class JavaDoc c = Class.forName(className);
786             Enumeration JavaDoc elements = v.elements();
787             while (elements.hasMoreElements())
788     &