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             {
789                 String JavaDoc name = (String JavaDoc) elements.nextElement();
790                 try
791                 {
792                     Object JavaDoc o = Class.forName(name).newInstance();
793                     if (c.isInstance(o))
794                     {
795                         i.addElement(o);
796                     }
797                 }
798                 catch (ClassNotFoundException JavaDoc e)
799                 {
800                     log.error(
801                         "Error loading class " + name + ": class is not found");
802                 }
803                 catch (IllegalAccessException JavaDoc e)
804                 {
805                     log.error(
806                         "Error loading class "
807                             + name
808                             + ": does not have access");
809                 }
810                 catch (InstantiationException JavaDoc e)
811                 {
812                     log.error(
813                         "Error loading class "
814                             + name
815                             + ": could not instantiate");
816                 }
817                 catch (NoClassDefFoundError JavaDoc e)
818                 {
819                     log.error(
820                         "Error loading class "
821                             + name
822                             + ": couldn't find class "
823                             + e.getMessage());
824                 }
825             }
826         }
827         catch (ClassNotFoundException JavaDoc e)
828         {
829             log.error(
830                 "Error loading class " + className + ": class is not found");
831         }
832         return i;
833     }
834     /**
835      * Tokenize a string into a vector of tokens
836      *
837      *@param string Description of Parameter
838      *@param separator Description of Parameter
839      *@return Description of the Returned Value
840      */

841     public static Vector JavaDoc tokenize(String JavaDoc string, String JavaDoc separator)
842     {
843         Vector JavaDoc v = new Vector JavaDoc();
844         StringTokenizer JavaDoc s = new StringTokenizer JavaDoc(string, separator);
845         while (s.hasMoreTokens())
846         {
847             v.addElement(s.nextToken());
848         }
849         return v;
850     }
851     /**
852      * Create a button with the netscape style
853      *
854      *@param name Description of Parameter
855      *@param listener Description of Parameter
856      *@return Description of the Returned Value
857      */

858     public static JButton JavaDoc createButton(String JavaDoc name, ActionListener JavaDoc listener)
859     {
860         JButton JavaDoc button = new JButton JavaDoc(getImage(name + ".on.gif"));
861         button.setDisabledIcon(getImage(name + ".off.gif"));
862         button.setRolloverIcon(getImage(name + ".over.gif"));
863         button.setPressedIcon(getImage(name + ".down.gif"));
864         button.setActionCommand(name);
865         button.addActionListener(listener);
866         button.setRolloverEnabled(true);
867         button.setFocusPainted(false);
868         button.setBorderPainted(false);
869         button.setOpaque(false);
870         button.setPreferredSize(new Dimension JavaDoc(24, 24));
871         return button;
872     }
873     /**
874      * Create a button with the netscape style
875      *
876      *@param name Description of Parameter
877      *@param listener Description of Parameter
878      *@return Description of the Returned Value
879      */

880     public static JButton JavaDoc createSimpleButton(
881         String JavaDoc name,
882         ActionListener JavaDoc listener)
883     {
884         JButton JavaDoc button = new JButton JavaDoc(getImage(name + ".gif"));
885         button.setActionCommand(name);
886         button.addActionListener(listener);
887         button.setFocusPainted(false);
888         button.setBorderPainted(false);
889         button.setOpaque(false);
890         button.setPreferredSize(new Dimension JavaDoc(25, 25));
891         return button;
892     }
893
894     /**
895      * Takes a String and a tokenizer character, and returns a new array of
896      * strings of the string split by the tokenizer character.
897      *
898      * @param splittee String to be split
899      * @param splitChar Character to split the string on
900      * @param def Default value to place between two split chars that
901      * have nothing between them
902      * @return Array of all the tokens.
903      */

904     public static String JavaDoc[] split(String JavaDoc splittee, String JavaDoc splitChar, String JavaDoc def)
905     {
906         if (splittee == null || splitChar == null)
907         {
908             return new String JavaDoc[0];
909         }
910         int spot;
911         while ((spot = splittee.indexOf(splitChar + splitChar)) != -1)
912         {
913             splittee =
914                 splittee.substring(0, spot + splitChar.length())
915                     + def
916                     + splittee.substring(
917                         spot + 1 * splitChar.length(),
918                         splittee.length());
919         }
920         Vector JavaDoc returns = new Vector JavaDoc();
921         int start = 0;
922         int length = splittee.length();
923         spot = 0;
924         while (start < length
925             && (spot = splittee.indexOf(splitChar, start)) > -1)
926         {
927             if (spot > 0)
928             {
929                 returns.addElement(splittee.substring(start, spot));
930             }
931             start = spot + splitChar.length();
932         }
933         if (start < length)
934         {
935             returns.add(splittee.substring(start));
936         }
937         String JavaDoc[] values = new String JavaDoc[returns.size()];
938         returns.copyInto(values);
939         return values;
940     }
941     
942     /**
943      * Report an error through a dialog box.
944      *
945      *@param errorMsg the error message.
946      */

947     public static void reportErrorToUser(String JavaDoc errorMsg)
948     {
949         if (errorMsg == null)
950         {
951             errorMsg = "Unknown error - see log file";
952             log.warn("Unknown error", new Throwable JavaDoc("errorMsg == null"));
953         }
954         try
955         {
956             JOptionPane.showMessageDialog(
957                 GuiPackage.getInstance().getMainFrame(),
958                 errorMsg,
959                 "Error",
960                 JOptionPane.ERROR_MESSAGE);
961         }
962         catch (RuntimeException JavaDoc e)
963         {
964             if (e.getClass().getName().equals("java.awt.HeadlessException")) //JDK1.4:
965
{
966                 //System.out.println(errorMsg+"[HeadlessException]");
967
//throw e;
968
log.warn("reportErrorToUser(\""+errorMsg+"\") caused",e);
969             }
970             else
971             {
972                 throw e;
973             }
974         }
975     }
976     /**
977      * Finds a string in an array of strings and returns the
978      *
979      *@param array Array of strings.
980      *@param value String to compare to array values.
981      *@return Index of value in array, or -1 if not in array.
982      */

983     public static int findInArray(String JavaDoc[] array, String JavaDoc value)
984     {
985         int count = -1;
986         int index = -1;
987         if (array != null && value != null)
988         {
989             while (++count < array.length)
990             {
991                 if (array[count] != null && array[count].equals(value))
992                 {
993                     index = count;
994                     break;
995                 }
996             }
997         }
998         return index;
999     }
1000    
1001    /**
1002     * Takes an array of strings and a tokenizer character, and returns a
1003     * string of all the strings concatenated with the tokenizer string in
1004     * between each one.
1005     *
1006     * @param splittee Array of Objects to be concatenated.
1007     * @param splitChar Object to unsplit the strings with.
1008     * @return Array of all the tokens.
1009     */

1010    public static String JavaDoc unsplit(Object JavaDoc[] splittee, Object JavaDoc splitChar)
1011    {
1012        StringBuffer JavaDoc retVal = new StringBuffer JavaDoc("");
1013        int count = -1;
1014        while (++count < splittee.length)
1015        {
1016            if (splittee[count] != null)
1017            {
1018                retVal.append(splittee[count]);
1019            }
1020            if (count + 1 < splittee.length && splittee[count + 1] != null)
1021            {
1022                retVal.append(splitChar);
1023            }
1024        }
1025        return retVal.toString();
1026    }
1027    // End Method
1028

1029    /**
1030     * Takes an array of strings and a tokenizer character, and returns a
1031     * string of all the strings concatenated with the tokenizer string in
1032     * between each one.
1033     *
1034     * @param splittee Array of Objects to be concatenated.
1035     * @param splitChar Object to unsplit the strings with.
1036     * @param def Default value to replace null values in array.
1037     * @return Array of all the tokens.
1038     */

1039    public static String JavaDoc unsplit(
1040        Object JavaDoc[] splittee,
1041        Object JavaDoc splitChar,
1042        String JavaDoc def)
1043    {
1044        StringBuffer JavaDoc retVal = new StringBuffer JavaDoc("");
1045        int count = -1;
1046        while (++count < splittee.length)
1047        {
1048            if (splittee[count] != null)
1049            {
1050                retVal.append(splittee[count]);
1051            }
1052            else
1053            {
1054                retVal.append(def);
1055            }
1056            if (count + 1 < splittee.length)
1057            {
1058                retVal.append(splitChar);
1059            }
1060        }
1061        return retVal.toString();
1062    }
1063    // End Method
1064
public static String JavaDoc getJMeterHome()
1065    {
1066        return jmDir;
1067    }
1068    public static void setJMeterHome(String JavaDoc home)
1069    {
1070        jmDir = home;
1071    }
1072    private static String JavaDoc jmDir;
1073    public static final String JavaDoc JMETER = "jmeter";
1074    public static final String JavaDoc ENGINE = "jmeter.engine";
1075    public static final String JavaDoc ELEMENTS = "jmeter.elements";
1076    public static final String JavaDoc GUI = "jmeter.gui";
1077    public static final String JavaDoc UTIL = "jmeter.util";
1078    public static final String JavaDoc CLASSFINDER = "jmeter.util.classfinder";
1079    public static final String JavaDoc TEST = "jmeter.test";
1080    public static final String JavaDoc HTTP = "jmeter.protocol.http";
1081    public static final String JavaDoc JDBC = "jmeter.protocol.jdbc";
1082    public static final String JavaDoc FTP = "jmeter.protocol.ftp";
1083    public static final String JavaDoc JAVA = "jmeter.protocol.java";
1084    public static final String JavaDoc PROPERTIES = "jmeter.elements.properties";
1085    /**
1086     * Gets the JMeter Version.
1087     * @return the JMeter version string
1088     */

1089    public static String JavaDoc getJMeterVersion()
1090    {
1091        return JMeterVersion.getVERSION();
1092    }
1093
1094    /**
1095     * Gets the JMeter copyright.
1096     * @return the JMeter copyright string
1097     */

1098    public static String JavaDoc getJMeterCopyright()
1099    {
1100        return JMeterVersion.COPYRIGHT;
1101    }
1102
1103    /**
1104    * Builds the string used as the main frame title
1105    *
1106    * @param fname the fully qualified name of the current working file
1107    *
1108    * @return a string of the form "FileName (<full path>/FileName) - Apache JMeter".
1109    * If fname is null, returns "Apache JMeter".
1110    */

1111    public static String JavaDoc getExtendedFrameTitle(String JavaDoc fname)
1112    {
1113        // file New operation may set to null, so just return
1114
// app name
1115
if (fname == null)
1116        {
1117            return "Apache JMeter";
1118        }
1119
1120        // allow for windows / chars in filename
1121
String JavaDoc temp = fname.replace('\\','/');
1122        String JavaDoc simpleName = temp.substring(temp.lastIndexOf("/") + 1);
1123        return simpleName + " (" + fname + ") - Apache JMeter";
1124    }
1125    
1126    /**
1127     * Determine whether we are in 'expert' mode. Certain features may be
1128     * hidden from user's view unless in expert mode.
1129     *
1130     * @return true iif we're in expert mode
1131     */

1132    public static boolean isExpertMode()
1133    {
1134        return JMeterUtils.getPropDefault(EXPERT_MODE_PROPERTY, false);
1135    }
1136}
1137
Popular Tags