e.g. Calendar Search Help
You must enter a value before pressing Search
jmeter

Class: org.apache.jmeter.util.JMeterUtils   ©

 OK to copy?
0001 // $Header: /home/cvs/jakarta-jmeter/src/core/org/apache/jmeter/util/JMeterUtils.java,v 1.66.2.2 2004/09/25 20:58:15 sebb Exp $
0002 /*
0003  * Copyright 2001-2004 The Apache Software Foundation.
0004  *
0005  * Licensed under the Apache License, Version 2.0 (the "License");
0006  * you may not use this file except in compliance with the License.
0007  * You may obtain a copy of the License at
0008  *
0009  *   http://www.apache.org/licenses/LICENSE-2.0
0010  *
0011  * Unless required by applicable law or agreed to in writing, software
0012  * distributed under the License is distributed on an "AS IS" BASIS,
0013  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
0014  * See the License for the specific language governing permissions and
0015  * limitations under the License.
0016  * 
0017 */
0018 
0019 package org.apache.jmeter.util;
0020 
0021 import java.awt.Dimension;
0022 import java.awt.event.ActionListener;
0023 import java.io.BufferedReader;
0024 import java.io.File;
0025 import java.io.FileInputStream;
0026 import java.io.IOException;
0027 import java.io.InputStream;
0028 import java.io.InputStreamReader;
0029 import java.util.Enumeration;
0030 import java.util.Hashtable;
0031 import java.util.Iterator;
0032 import java.util.Locale;
0033 import java.util.MissingResourceException;
0034 import java.util.Properties;
0035 import java.util.Random;
0036 import java.util.ResourceBundle;
0037 import java.util.StringTokenizer;
0038 import java.util.Vector;
0039 
0040 import javax.swing.ImageIcon;
0041 import javax.swing.JButton;
0042 import javax.swing.JComboBox;
0043 import javax.swing.JOptionPane;
0044 //import javax.xml.parsers.SAXParserFactory;
0045 
0046 import org.apache.jmeter.gui.GuiPackage;
0047 import org.apache.jorphan.logging.LoggingManager;
0048 import org.apache.jorphan.test.UnitTestManager;
0049 import org.apache.jorphan.util.JOrphanUtils;
0050 import org.apache.log.Logger;
0051 import org.apache.oro.text.PatternCacheLRU;
0052 import org.apache.oro.text.regex.Perl5Compiler;
0053 import org.apache.oro.text.regex.Perl5Matcher;
0054 import org.xml.sax.XMLReader;
0055 
0056 /**
0057  * This class contains the static utility methods used by JMeter.
0058  * 
0059  * @version $Revision: 1.66.2.2 $ updated on $Date: 2004/09/25 20:58:15 $
0060  */
0061 public class JMeterUtils implements UnitTestManager
0062 {
0063     private static PatternCacheLRU patternCache =
0064         new PatternCacheLRU(1000, new Perl5Compiler());
0065 
0066     transient private static Logger log = LoggingManager.getLoggerForClass();
0067     
0068     private static final String EXPERT_MODE_PROPERTY="jmeter.expertMode";
0069 
0070     // Not used currently
0071 //    private static final SAXParserFactory xmlFactory;
0072 //    static {
0073 //        SAXParserFactory temp = null;
0074 //        try
0075 //        {
0076 //            temp = SAXParserFactory.newInstance();
0077 //        }
0078 //        catch (Exception e)
0079 //        {
0080 //            log.error("", e);
0081 //            temp = null;
0082 //        }
0083 //        xmlFactory = temp;
0084 //    }
0085     private static Properties appProperties;
0086     private static Vector localeChangeListeners = new Vector();
0087     private static Locale locale;
0088     private static ResourceBundle resources;
0089 
0090     private static ThreadLocal localMatcher = new ThreadLocal()
0091     {
0092         protected Object initialValue()
0093         {
0094             return new Perl5Matcher();
0095         }
0096     };
0097 
0098     //Provide Random numbers to whomever wants one
0099     private static Random rand = new Random();
0100 
0101     /**
0102      * Gets Perl5Matcher for this thread.
0103      */
0104     public static Perl5Matcher getMatcher()
0105     {
0106         return (Perl5Matcher) localMatcher.get();
0107     }
0108 
0109     /**
0110      * This method is used by the init method to load the property file that
0111      * may even reside in the user space, or in the classpath under
0112      * org.apache.jmeter.jmeter.properties.
0113      *
0114      *@param  file  the file to load 
0115      *@return       the Properties from the file
0116      */
0117     public static Properties getProperties(String file)
0118     {
0119         Properties p = new Properties(System.getProperties());
0120         try
0121         {
0122             File f = new File(file);
0123             p.load(new FileInputStream(f));
0124         }
0125         catch (Exception e)
0126         {
0127             try
0128             {
0129                 InputStream is = ClassLoader.getSystemResourceAsStream(
0130                     "org/apache/jmeter/jmeter.properties");
0131                 if (is == null) throw new RuntimeException("Could not read JMeter properties file"); 
0132                 p.load(is);
0133             }
0134             catch (IOException ex)
0135             {
0136                 // JMeter.fail("Could not read internal resource. " +
0137                 //             "Archive is broken.");
0138             }
0139         }
0140         appProperties = p;
0141         LoggingManager.initializeLogging(appProperties);
0142         log = LoggingManager.getLoggerForClass();
0143         String loc = appProperties.getProperty("language");
0144         if (loc != null)
0145         {
0146             setLocale(new Locale(loc, ""));
0147         }
0148         else
0149         {
0150             setLocale(Locale.getDefault());
0151         }
0152         return p;
0153     }
0154 
0155     public static PatternCacheLRU getPatternCache()
0156     {
0157         return patternCache;
0158     }
0159 
0160     public void initializeProperties(String file)
0161     {
0162         System.out.println("Initializing Properties: " + file);
0163         getProperties(file);
0164         String home;
0165         int pathend=file.lastIndexOf("/");
0166         if (pathend == -1){// No path separator found, must be in current directory
0167             home = ".";
0168         } else {
0169             home = file.substring(0, pathend);
0170         }
0171         home = new File(home + "/..").getAbsolutePath();
0172         System.out.println("Setting JMeter home: " + home);
0173         setJMeterHome(home);
0174     }
0175     public static String[] getSearchPaths()
0176     {
0177         String p= JMeterUtils.getPropDefault("search_paths", null);
0178         String[] result= new String[1];
0179         
0180         if (p!=null) {
0181             String[] paths= JOrphanUtils.split(p,";");// was p.split(";") - JDK1.4
0182             result= new String[paths.length+1];
0183             for (int i=1; i<result.length; i++)
0184             {
0185                 result[i]= paths[i-1];
0186             }
0187         }
0188         result[0]= getJMeterHome() + "/lib/ext";
0189         return result;
0190     }
0191 
0192     /**
0193      * Provide random numbers
0194      * @param r - the upper bound (exclusive)
0195      */
0196     public static int getRandomInt(int r)
0197     {
0198         return rand.nextInt(r);
0199     }
0200 
0201     /**
0202      * Changes the current locale: re-reads resource strings and notifies
0203      * listeners.
0204      *
0205      * author Oliver Rossmueller
0206      * @param loc - new locale
0207      */
0208     public static void setLocale(Locale loc)
0209     {
0210         locale = loc;
0211         resources =
0212             ResourceBundle.getBundle(
0213                 "org.apache.jmeter.resources.messages",
0214                 locale);
0215         notifyLocaleChangeListeners();
0216     }
0217 
0218     /**
0219      * Gets the current locale.
0220      *
0221      * author Oliver Rossmueller
0222      * @return current locale
0223      */
0224     public static Locale getLocale()
0225     {
0226         return locale;
0227     }
0228 
0229     /**
0230      * author Oliver Rossmueller
0231      */
0232     public static void addLocaleChangeListener(LocaleChangeListener listener)
0233     {
0234         localeChangeListeners.add(listener);
0235     }
0236 
0237     /**
0238      * author Oliver Rossmueller
0239      */
0240     public static void removeLocaleChangeListener(LocaleChangeListener listener)
0241     {
0242         localeChangeListeners.remove(listener);
0243     }
0244 
0245     /**
0246      * Notify all listeners interested in locale changes.
0247      *
0248      * author Oliver Rossmueller
0249      */
0250     private static void notifyLocaleChangeListeners()
0251     {
0252         LocaleChangeEvent event =
0253             new LocaleChangeEvent(JMeterUtils.class, locale);
Rate0254         Iterator iterator = ((Vector)localeChangeListeners.clone()).iterator();
0255 
0256         while (iterator.hasNext())
0257         {
0258             LocaleChangeListener listener =
0259                 (LocaleChangeListener) iterator.next();
0260             listener.localeChanged(event);
0261         }
0262     }
0263 
0264     /**
0265      * Gets the resource string for this key.
0266      * 
0267      * If the resource is not found, a warning is logged
0268      * 
0269      * @param key the key in the resource file
0270      * @return    the resource string if the key is found; otherwise, return
0271      *            "[res_key="+key+"]"
0272      */
0273     public static String getResString(String key)
0274     {
0275         return getResStringDefault(key,RES_KEY_PFX+key+"]");
0276     }
0277     public static final String RES_KEY_PFX="[res_key=";
0278     
0279     /**
0280      * Gets the resource string for this key.
0281      * 
0282      * If the resource is not found, a warning is logged
0283      * 
0284      * @param key the key in the resource file
0285      * @param defaultValue - the default value
0286      * 
0287      * @return    the resource string if the key is found;
0288      *             otherwise, return the default
0289      * @deprecated Only intended for use in development; use getResString(String) normally
0290      */
0291     public static String getResString(String key, String defaultValue)
0292     {
0293         return getResStringDefault(key,defaultValue);
0294     }
0295     
0296     /*
0297      * Helper method to do the actual work of fetching resources;
0298      * allows getResString(S,S) to be deprecated without affecting getResString(S);
0299      */
0300     private static String getResStringDefault(String key, String defaultValue)
0301     {
0302         if (key == null)
0303         {
0304             return null;
0305         }
0306         key = key.replace(' ', '_');
0307         key = key.toLowerCase();
0308         String resString = null;
0309         try
0310         {
0311             resString = resources.getString(key);
0312         }
0313         catch (MissingResourceException mre)
0314         {
0315             log.warn("ERROR! Resource string not found: [" + key + "]");
0316             resString = defaultValue;
0317         }
0318         return resString;
0319     }
0320     /**
0321      * This gets the currently defined appProperties. It can only be called
0322      * after the {@link #getProperties(String)} method is called.
0323      *
0324      * @return    The JMeterProperties value
0325      */
0326     public static Properties getJMeterProperties()
0327     {
0328         return appProperties;
0329     }
0330     /**
0331      *  This looks for the requested image in the classpath under
0332      *  org.apache.jmeter.images. <name>
0333      *
0334      * @param  name  Description of Parameter
0335      * @return       The Image value
0336      */
0337     public static ImageIcon getImage(String name)
0338     {
0339         try
0340         {
0341             return new ImageIcon(
0342                 JMeterUtils.class.getClassLoader().getResource(
0343                     "org/apache/jmeter/images/" + name.trim()));
0344         }
0345         catch (NullPointerException e)
0346         {
0347             log.warn("no icon for " + name);
0348             return null;
0349         }
0350     }
0351     public static String getResourceFileAsText(String name)
0352     {
0353         try
0354         {
0355             String lineEnd = System.getProperty("line.separator");
0356             BufferedReader fileReader =
0357                 new BufferedReader(
0358                     new InputStreamReader(
0359                         JMeterUtils.class.getClassLoader().getResourceAsStream(
0360                             name)));
0361             StringBuffer text = new StringBuffer();
0362             String line = "NOTNULL";
0363             while (line != null)
0364             {
0365                 line = fileReader.readLine();
0366                 if (line != null)
0367                 {
0368                     text.append(line);
0369                     text.append(lineEnd);
0370                 }
0371             }
0372             fileReader.close();
0373             return text.toString();
0374         }
0375         catch (NullPointerException e) // Cannot find file
0376         {
0377             return "";
0378         }
0379         catch (IOException e)
0380         {
0381             return "";
0382         }
0383     }
0384     /**
0385      *  Creates the vector of Timers plugins.
0386      *
0387      *@param  properties  Description of Parameter
0388      *@return             The Timers value
0389      */
0390     public static Vector getTimers(Properties properties)
0391     {
0392         return instantiate(
0393             getVector(properties, "timer."),
0394             "org.apache.jmeter.timers.Timer");
0395     }
0396     /**
0397      *  Creates the vector of visualizer plugins.
0398      *
0399      *@param  properties  Description of Parameter
0400      *@return             The Visualizers value
0401      */
0402     public static Vector getVisualizers(Properties properties)
0403     {
0404         return instantiate(
0405             getVector(properties, "visualizer."),
0406             "org.apache.jmeter.visualizers.Visualizer");
0407     }
0408     /**
0409      *  Creates a vector of SampleController plugins.
0410      *
0411      *@param  properties  The properties with information about the samplers
0412      *@return             The Controllers value
0413      */
0414     //TODO - does not appear to be called directly
0415     public static Vector getControllers(Properties properties)
0416     {
0417         String name = "controller.";
0418         Vector v = new Vector();
0419         Enumeration names = properties.keys();
0420         while (names.hasMoreElements())
0421         {
0422             String prop = (String) names.nextElement();
0423             if (prop.startsWith(name))
0424             {
0425                 Object o =
0426                     instantiate(
0427                         properties.getProperty(prop),
0428                         "org.apache.jmeter.control.SamplerController");
0429                 v.addElement(o);
0430             }
0431         }
0432         return v;
0433     }
0434     /**
0435      *  Create a string of class names for a particular SamplerController
0436      *
0437      *@param  properties  The properties with info about the samples.
0438      *@param  name        The name of the sampler controller.
0439      *@return             The TestSamples value
0440      */
0441     public static String[] getTestSamples(Properties properties, String name)
0442     {
0443         return (String[]) getVector(properties, name + ".testsample").toArray(
0444             new String[0]);
0445     }
0446     /**
0447      *  Create an instance of an org.xml.sax.Parser
0448      *
0449      * @deprecated use the plain version instead.  We are using JAXP!
0450      *@param  properties  The properties file containing the parser's class name
0451      *@return             The XMLParser value
0452      */
0453     public static XMLReader getXMLParser(Properties properties)
0454     {
0455         return getXMLParser();
0456     }
0457     /**
0458      *  Create an instance of an org.xml.sax.Parser based on the default props.
0459      *
0460      *@return    The XMLParser value
0461      */
0462     public static XMLReader getXMLParser()
0463     {
0464         XMLReader reader = null;
0465         try
0466         {
0467             reader =
0468                 (XMLReader) instantiate(getPropDefault("xml.parser",
0469                     "org.apache.xerces.parsers.SAXParser"),
0470                     "org.xml.sax.XMLReader");
0471             //reader = xmlFactory.newSAXParser().getXMLReader();
0472         }
0473         catch (Exception e)
0474         {
0475             reader =
0476                 (XMLReader) instantiate(getPropDefault("xml.parser",
0477                     "org.apache.xerces.parsers.SAXParser"),
0478                     "org.xml.sax.XMLReader");
0479         }
0480         return reader;
0481     }
0482     
0483     /**
0484      *  Creates the vector of alias strings.
0485      *
0486      *@param  properties  Description of Parameter
0487      *@return             The Alias value
0488      */
0489     public static Hashtable getAlias(Properties properties)
0490     {
0491         return getHashtable(properties, "alias.");
0492     }
0493     
0494     /**
0495      * Creates a vector of strings for all the properties that start with a
0496      * common prefix.
0497      *
0498      * @param  properties  Description of Parameter
0499      * @param  name        Description of Parameter
0500      * @return             The Vector value
0501      */
0502     public static Vector getVector(Properties properties, String name)
0503     {
0504         Vector v = new Vector();
0505         Enumeration names = properties.keys();
0506         while (names.hasMoreElements())
0507         {
0508             String prop = (String) names.nextElement();
0509             if (prop.startsWith(name))
0510             {
0511                 v.addElement(properties.getProperty(prop));
0512             }
0513         }
0514         return v;
0515     }
0516     
0517     /**
0518      * Creates a table of strings for all the properties that start with a
0519      * common prefix.
0520      *
0521      * @param  properties  Description of Parameter
0522      * @param  name        Description of Parameter
0523      * @return             The Hashtable value
0524      */
0525     public static Hashtable getHashtable(Properties properties, String name)
0526     {
0527         Hashtable t = new Hashtable();
0528         Enumeration names = properties.keys();
0529         while (names.hasMoreElements())
0530         {
0531             String prop = (String) names.nextElement();
0532             if (prop.startsWith(name))
0533             {
0534                 t.put(
0535                     prop.substring(name.length()),
0536                     properties.getProperty(prop));
0537             }
0538         }
0539         return t;
0540     }
0541     
0542     /**
0543      *  Get a int value with default if not present.
0544      *
0545      *@param  propName    the name of the property.
0546      *@param  defaultVal  the default value.
0547      *@return             The PropDefault value
0548      */
0549     public static int getPropDefault(String propName, int defaultVal)
0550     {
0551         int ans;
0552         try
0553         {
0554             ans =
0555                 (Integer
0556                     .valueOf(
0557                         appProperties
0558                             .getProperty(propName, Integer.toString(defaultVal))
0559                             .trim()))
0560                     .intValue();
0561         }
0562         catch (Exception e)
0563         {
0564             ans = defaultVal;
0565         }
0566         return ans;
0567     }
0568     /**
0569      *  Get a boolean value with default if not present.
0570      *
0571      *@param  propName    the name of the property.
0572      *@param  defaultVal  the default value.
0573      *@return             The PropDefault value
0574      */
0575     public static boolean getPropDefault(String propName, boolean defaultVal)
0576     {
0577         boolean ans;
0578         try
0579         {
0580             String strVal =
0581                 appProperties
0582                     .getProperty(propName, JOrphanUtils.booleanToString(defaultVal))
0583                     .trim();
0584             if (strVal.equalsIgnoreCase("true")
0585                 || strVal.equalsIgnoreCase("t"))
0586             {
0587                 ans = true;
0588             }
0589             else if (
0590                 strVal.equalsIgnoreCase("false")
0591                     || strVal.equalsIgnoreCase("f"))
0592             {
0593                 ans = false;
0594             }
0595             else
0596             {
0597                 ans = ((Integer.valueOf(strVal)).intValue() == 1);
0598             }
0599         }
0600         catch (Exception e)
0601         {
0602             ans = defaultVal;
0603         }
0604         return ans;
0605     }
0606     /**
0607      *  Get a long value with default if not present.
0608      *
0609      *@param  propName    the name of the property.
0610      *@param  defaultVal  the default value.
0611      *@return             The PropDefault value
0612      */
0613     public static long getPropDefault(String propName, long defaultVal)
0614     {
0615         long ans;
0616         try
0617         {
0618             ans =
0619                 (Long
0620                     .valueOf(
0621                         appProperties
0622                             .getProperty(propName, Long.toString(defaultVal))
0623                             .trim()))
0624                     .longValue();
0625         }
0626         catch (Exception e)
0627         {
0628             ans = defaultVal;
0629         }
0630         return ans;
0631     }
0632     /**
0633      *  Get a String value with default if not present.
0634      *
0635      *@param  propName    the name of the property.
0636      *@param  defaultVal  the default value.
0637      *@return             The PropDefault value
0638      */
0639     public static String getPropDefault(String propName, String defaultVal)
0640     {
0641         String ans;
0642         try
0643         {
0644             ans = appProperties.getProperty(propName, defaultVal).trim();
0645         }
0646         catch (Exception e)
0647         {
0648             ans = defaultVal;
0649         }
0650         return ans;
0651     }
0652     /**
0653      *  Get a String value with NO default if not present.
0654      *
0655      *@param  propName    the name of the property.
0656      *@return             The PropDefault value
0657      */
0658     public static String getProperty(String propName)
0659     {
0660         String ans = null;
0661         try
0662         {
0663             ans = appProperties.getProperty(propName);
0664         }
0665         catch (Exception e)
0666         {
0667             ans = null;
0668         }
0669         return ans;
0670     }
0671 
0672     /**
0673      *  Set a String value
0674      *
0675      *@param  propName    the name of the property.
0676      *@param propValue    the value of the property
0677      *@return             the previous value of the property
0678      */
0679     public static Object setProperty(String propName, String propValue)
0680     {
0681          return appProperties.setProperty(propName,propValue);
0682     }
0683 
0684     /**
0685      * Sets the selection of the JComboBox to the Object 'name' from the list
0686      * in namVec.
0687      */
0688     public static void selJComboBoxItem(
0689         Properties properties,
0690         JComboBox combo,
0691         Vector namVec,
0692         String name)
0693     {
0694         int idx = namVec.indexOf(name);
0695         combo.setSelectedIndex(idx);
0696         // Redisplay.
0697         combo.updateUI();
0698         return;
0699     }
0700 
0701     /**
0702      *  Instatiate an object and guarantee its class.
0703      *
0704      *@param  className  The name of the class to instantiate.
0705      *@param  impls      The name of the class it subclases.
0706      *@return            Description of the Returned Value
0707      */
0708     public static Object instantiate(String className, String impls)
0709     {
0710         if (className != null)
0711         {
0712             className=className.trim();
0713         }
0714 
0715         if (impls != null)
0716         {   
0717             impls=impls.trim();
0718         }
0719 
0720         try
0721         {
0722             Class c = Class.forName(impls);
0723             try
0724             {
0725                 Class o = Class.forName(className);
0726                 Object res = o.newInstance();
0727                 if (c.isInstance(res))
0728                 {
0729                     return res;
0730                 }
0731                 else
0732                 {
0733                     throw new IllegalArgumentException(
0734                         className + " is not an instance of " + impls);
0735                 }
0736             }
0737             catch (ClassNotFoundException e)
0738             {
0739                 log.error(
0740                     "Error loading class "
0741                         + className
0742                         + ": class is not found");
0743             }
0744             catch (IllegalAccessException e)
0745             {
0746                 log.error(
0747                     "Error loading class "
0748                         + className
0749                         + ": does not have access");
0750             }
0751             catch (InstantiationException e)
0752             {
0753                 log.error(
0754                     "Error loading class "
0755                         + className
0756                         + ": could not instantiate");
0757             }
0758             catch (NoClassDefFoundError e)
0759             {
0760                 log.error(
0761                     "Error loading class "
0762                         + className
0763                         + ": couldn't find class "
0764                         + e.getMessage());
0765             }
0766         }
0767         catch (ClassNotFoundException e)
0768         {
0769             log.error("Error loading class " + impls + ": was not found.");
0770         }
0771         return null;
0772     }
0773     /**
0774      *  Instantiate a vector of classes
0775      *
0776      *@param  v          Description of Parameter
0777      *@param  className  Description of Parameter
0778      *@return            Description of the Returned Value
0779      */
0780     public static Vector instantiate(Vector v, String className)
0781     {
0782         Vector i = new Vector();
0783         try
0784         {
0785             Class c = Class.forName(className);
0786             Enumeration elements = v.elements();
0787             while (elements.hasMoreElements())
0788             {
0789                 String name = (String) elements.nextElement();
0790                 try
0791                 {
0792                     Object o = Class.forName(name).newInstance();
0793                     if (c.isInstance(o))
0794                     {
0795                         i.addElement(o);
0796                     }
0797                 }
0798                 catch (ClassNotFoundException e)
0799                 {
0800                     log.error(
0801                         "Error loading class " + name + ": class is not found");
0802                 }
0803                 catch (IllegalAccessException e)
0804                 {
0805                     log.error(
0806                         "Error loading class "
0807                             + name
0808                             + ": does not have access");
0809                 }
0810                 catch (InstantiationException e)
0811                 {
0812                     log.error(
0813                         "Error loading class "
0814                             + name
0815                             + ": could not instantiate");
0816                 }
0817                 catch (NoClassDefFoundError e)
0818                 {
0819                     log.error(
0820                         "Error loading class "
0821                             + name
0822                             + ": couldn't find class "
0823                             + e.getMessage());
0824                 }
0825             }
0826         }
0827         catch (ClassNotFoundException e)
0828         {
0829             log.error(
0830                 "Error loading class " + className + ": class is not found");
0831         }
0832         return i;
0833     }
0834     /**
0835      *  Tokenize a string into a vector of tokens
0836      *
0837      *@param  string     Description of Parameter
0838      *@param  separator  Description of Parameter
0839      *@return            Description of the Returned Value
0840      */
0841     public static Vector tokenize(String string, String separator)
0842     {
0843         Vector v = new Vector();
0844         StringTokenizer s = new StringTokenizer(string, separator);
0845         while (s.hasMoreTokens())
0846         {
0847             v.addElement(s.nextToken());
0848         }
0849         return v;
0850     }
0851     /**
0852      *  Create a button with the netscape style
0853      *
0854      *@param  name      Description of Parameter
0855      *@param  listener  Description of Parameter
0856      *@return           Description of the Returned Value
0857      */
0858     public static JButton createButton(String name, ActionListener listener)
0859     {
0860         JButton button = new JButton(getImage(name + ".on.gif"));
0861         button.setDisabledIcon(getImage(name + ".off.gif"));
0862         button.setRolloverIcon(getImage(name + ".over.gif"));
0863         button.setPressedIcon(getImage(name + ".down.gif"));
0864         button.setActionCommand(name);
0865         button.addActionListener(listener);
0866         button.setRolloverEnabled(true);
0867         button.setFocusPainted(false);
0868         button.setBorderPainted(false);
0869         button.setOpaque(false);
0870         button.setPreferredSize(new Dimension(24, 24));
0871         return button;
0872     }
0873     /**
0874      *  Create a button with the netscape style
0875      *
0876      *@param  name      Description of Parameter
0877      *@param  listener  Description of Parameter
0878      *@return           Description of the Returned Value
0879      */
0880     public static JButton createSimpleButton(
0881         String name,
0882         ActionListener listener)
0883     {
0884         JButton button = new JButton(getImage(name + ".gif"));
0885         button.setActionCommand(name);
0886         button.addActionListener(listener);
0887         button.setFocusPainted(false);
0888         button.setBorderPainted(false);
0889         button.setOpaque(false);
0890         button.setPreferredSize(new Dimension(25, 25));
0891         return button;
0892     }
0893 
0894     /**
0895      *  Takes a String and a tokenizer character, and returns a new array of
0896      *  strings of the string split by the tokenizer character.
0897      *
0898      * @param  splittee   String to be split
0899      * @param  splitChar  Character to split the string on
0900      * @param  def        Default value to place between two split chars that
0901      *                    have nothing between them
0902      * @return            Array of all the tokens.
0903      */
0904     public static String[] split(String splittee, String splitChar, String def)
0905     {
0906         if (splittee == null || splitChar == null)
0907         {
0908             return new String[0];
0909         }
0910         int spot;
0911         while ((spot = splittee.indexOf(splitChar + splitChar)) != -1)
0912         {
0913             splittee =
0914                 splittee.substring(0, spot + splitChar.length())
0915                     + def
0916                     + splittee.substring(
0917                         spot + 1 * splitChar.length(),
0918                         splittee.length());
0919         }
0920         Vector returns = new Vector();
0921         int start = 0;
0922         int length = splittee.length();
0923         spot = 0;
0924         while (start < length
0925             && (spot = splittee.indexOf(splitChar, start)) > -1)
0926         {
0927             if (spot > 0)
0928             {
0929                 returns.addElement(splittee.substring(start, spot));
0930             }
0931             start = spot + splitChar.length();
0932         }
0933         if (start < length)
0934         {
0935             returns.add(splittee.substring(start));
0936         }
0937         String[] values = new String[returns.size()];
0938         returns.copyInto(values);
0939         return values;
0940     }
0941     
0942     /**
0943      *  Report an error through a dialog box.
0944      *
0945      *@param  errorMsg  the error message.
0946      */
0947     public static void reportErrorToUser(String errorMsg)
0948     {
0949         if (errorMsg == null)
0950         {
0951             errorMsg = "Unknown error - see log file";
0952             log.warn("Unknown error", new Throwable("errorMsg == null"));
0953         }
0954         try
0955         {
0956             JOptionPane.showMessageDialog(
0957                 GuiPackage.getInstance().getMainFrame(),
0958                 errorMsg,
0959                 "Error",
0960                 JOptionPane.ERROR_MESSAGE);
0961         }
0962         catch (RuntimeException e)
0963         {
0964             if (e.getClass().getName().equals("java.awt.HeadlessException")) //JDK1.4:
0965             {
0966                 //System.out.println(errorMsg+"[HeadlessException]");
0967                 //throw e;
0968                 log.warn("reportErrorToUser(\""+errorMsg+"\") caused",e);
0969             }
0970             else
0971             {
0972                 throw e;
0973             }
0974         }
0975     }
0976     /**
0977      *  Finds a string in an array of strings and returns the
0978      *
0979      *@param  array  Array of strings.
0980      *@param  value  String to compare to array values.
0981      *@return        Index of value in array, or -1 if not in array.
0982      */
0983     public static int findInArray(String[] array, String value)
0984     {
0985         int count = -1;
0986         int index = -1;
0987         if (array != null && value != null)
0988         {
0989             while (++count < array.length)
0990             {
0991                 if (array[count] != null && array[count].equals(value))
0992                 {
0993                     index = count;
0994                     break;
0995                 }
0996             }
0997         }
0998         return index;
0999     }
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 unsplit(Object[] splittee, Object splitChar)
1011     {
1012         StringBuffer retVal = new StringBuffer("");
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 unsplit(
1040         Object[] splittee,
1041         Object splitChar,
1042         String def)
1043     {
1044         StringBuffer retVal = new StringBuffer("");
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 getJMeterHome()
1065     {
1066         return jmDir;
1067     }
1068     public static void setJMeterHome(String home)
1069     {
1070         jmDir = home;
1071     }
1072     private static String jmDir;
1073     public static final String JMETER = "jmeter";
1074     public static final String ENGINE = "jmeter.engine";
1075     public static final String ELEMENTS = "jmeter.elements";
1076     public static final String GUI = "jmeter.gui";
1077     public static final String UTIL = "jmeter.util";
1078     public static final String CLASSFINDER = "jmeter.util.classfinder";
1079     public static final String TEST = "jmeter.test";
1080     public static final String HTTP = "jmeter.protocol.http";
1081     public static final String JDBC = "jmeter.protocol.jdbc";
1082     public static final String FTP = "jmeter.protocol.ftp";
1083     public static final String JAVA = "jmeter.protocol.java";
1084     public static final String PROPERTIES = "jmeter.elements.properties";
1085     /**
1086      * Gets the JMeter Version.
1087      * @return the JMeter version string
1088      */
1089     public static String getJMeterVersion()
1090     {
1091         return JMeterVersion.VERSION;
1092     }
1093 
1094     /**
1095      * Gets the JMeter copyright.
1096      * @return the JMeter copyright string
1097      */
1098     public static String 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 getExtendedFrameTitle(String 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 temp = fname.replace('\\','/');
1122         String 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 }

            
All Examples in File:
Example
Line
Rating (found
useful by...)
254 0% of 0