PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/projects/jmeter-2.5.1/src/core/org/apache/jmeter/util/JMeterUtils.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 1240 lines | 666 code | 92 blank | 482 comment | 91 complexity | 4c37f4513e0872258cfd8b6fad9231fb MD5 | raw file
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with
  4. * this work for additional information regarding copyright ownership.
  5. * The ASF licenses this file to You under the Apache License, Version 2.0
  6. * (the "License"); you may not use this file except in compliance with
  7. * the License. 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. package org.apache.jmeter.util;
  19. import java.awt.Dimension;
  20. import java.awt.HeadlessException;
  21. import java.awt.event.ActionListener;
  22. import java.io.BufferedReader;
  23. import java.io.File;
  24. import java.io.FileInputStream;
  25. import java.io.IOException;
  26. import java.io.InputStream;
  27. import java.io.InputStreamReader;
  28. import java.net.InetAddress;
  29. import java.net.URL;
  30. import java.net.UnknownHostException;
  31. import java.util.Enumeration;
  32. import java.util.Hashtable;
  33. import java.util.Iterator;
  34. import java.util.LinkedHashMap;
  35. import java.util.List;
  36. import java.util.Locale;
  37. import java.util.MissingResourceException;
  38. import java.util.Properties;
  39. import java.util.Random;
  40. import java.util.ResourceBundle;
  41. import java.util.StringTokenizer;
  42. import java.util.Vector;
  43. import javax.swing.ImageIcon;
  44. import javax.swing.JButton;
  45. import javax.swing.JComboBox;
  46. import javax.swing.JOptionPane;
  47. import org.apache.commons.io.IOUtils;
  48. import org.apache.jmeter.gui.GuiPackage;
  49. import org.apache.jorphan.logging.LoggingManager;
  50. import org.apache.jorphan.reflect.ClassFinder;
  51. import org.apache.jorphan.test.UnitTestManager;
  52. import org.apache.jorphan.util.JOrphanUtils;
  53. import org.apache.log.Logger;
  54. import org.apache.oro.text.PatternCacheLRU;
  55. import org.apache.oro.text.regex.Pattern;
  56. import org.apache.oro.text.regex.Perl5Compiler;
  57. import org.apache.oro.text.regex.Perl5Matcher;
  58. import org.xml.sax.XMLReader;
  59. /**
  60. * This class contains the static utility methods used by JMeter.
  61. *
  62. */
  63. public class JMeterUtils implements UnitTestManager {
  64. private static final Logger log = LoggingManager.getLoggerForClass();
  65. private static final PatternCacheLRU patternCache = new PatternCacheLRU(
  66. getPropDefault("oro.patterncache.size",1000), // $NON-NLS-1$
  67. new Perl5Compiler());
  68. private static final String EXPERT_MODE_PROPERTY = "jmeter.expertMode"; // $NON-NLS-1$
  69. private static final String ENGLISH_LANGUAGE = Locale.ENGLISH.getLanguage();
  70. private static volatile Properties appProperties;
  71. private static final Vector<LocaleChangeListener> localeChangeListeners = new Vector<LocaleChangeListener>();
  72. private static volatile Locale locale;
  73. private static volatile ResourceBundle resources;
  74. // What host am I running on?
  75. //@GuardedBy("this")
  76. private static String localHostIP = null;
  77. //@GuardedBy("this")
  78. private static String localHostName = null;
  79. //@GuardedBy("this")
  80. private static String localHostFullName = null;
  81. private static volatile boolean ignoreResorces = false; // Special flag for use in debugging resources
  82. private static final ThreadLocal<Perl5Matcher> localMatcher = new ThreadLocal<Perl5Matcher>() {
  83. @Override
  84. protected Perl5Matcher initialValue() {
  85. return new Perl5Matcher();
  86. }
  87. };
  88. // Provide Random numbers to whomever wants one
  89. private static final Random rand = new Random();
  90. /**
  91. * Gets Perl5Matcher for this thread.
  92. */
  93. public static Perl5Matcher getMatcher() {
  94. return localMatcher.get();
  95. }
  96. /**
  97. * This method is used by the init method to load the property file that may
  98. * even reside in the user space, or in the classpath under
  99. * org.apache.jmeter.jmeter.properties.
  100. *
  101. * The method also initialises logging and sets up the default Locale
  102. *
  103. * TODO - perhaps remove?
  104. * [still used
  105. *
  106. * @param file
  107. * the file to load
  108. * @return the Properties from the file
  109. */
  110. public static Properties getProperties(String file) {
  111. loadJMeterProperties(file);
  112. initLogging();
  113. initLocale();
  114. return appProperties;
  115. }
  116. /**
  117. * Initialise JMeter logging
  118. */
  119. public static void initLogging() {
  120. LoggingManager.initializeLogging(appProperties);
  121. }
  122. /**
  123. * Initialise the JMeter Locale
  124. */
  125. public static void initLocale() {
  126. String loc = appProperties.getProperty("language"); // $NON-NLS-1$
  127. if (loc != null) {
  128. String []parts = JOrphanUtils.split(loc,"_");// $NON-NLS-1$
  129. if (parts.length==2) {
  130. setLocale(new Locale(parts[0], parts[1]));
  131. } else {
  132. setLocale(new Locale(loc, "")); // $NON-NLS-1$
  133. }
  134. } else {
  135. setLocale(Locale.getDefault());
  136. }
  137. }
  138. /**
  139. * Load the JMeter properties file; if not found, then
  140. * default to "org/apache/jmeter/jmeter.properties" from the classpath
  141. *
  142. * c.f. loadProperties
  143. *
  144. */
  145. public static void loadJMeterProperties(String file) {
  146. Properties p = new Properties(System.getProperties());
  147. InputStream is = null;
  148. try {
  149. File f = new File(file);
  150. is = new FileInputStream(f);
  151. p.load(is);
  152. } catch (IOException e) {
  153. try {
  154. is =
  155. ClassLoader.getSystemResourceAsStream("org/apache/jmeter/jmeter.properties"); // $NON-NLS-1$
  156. if (is == null) {
  157. throw new RuntimeException("Could not read JMeter properties file");
  158. }
  159. p.load(is);
  160. } catch (IOException ex) {
  161. // JMeter.fail("Could not read internal resource. " +
  162. // "Archive is broken.");
  163. }
  164. } finally {
  165. JOrphanUtils.closeQuietly(is);
  166. }
  167. appProperties = p;
  168. }
  169. /**
  170. * This method loads a property file that may reside in the user space, or
  171. * in the classpath
  172. *
  173. * @param file
  174. * the file to load
  175. * @return the Properties from the file
  176. */
  177. public static Properties loadProperties(String file) {
  178. Properties p = new Properties();
  179. InputStream is = null;
  180. try {
  181. File f = new File(file);
  182. is = new FileInputStream(f);
  183. p.load(is);
  184. } catch (IOException e) {
  185. try {
  186. final URL resource = JMeterUtils.class.getClassLoader().getResource(file);
  187. if (resource == null) {
  188. log.warn("Cannot find " + file);
  189. return null;
  190. }
  191. is = resource.openStream();
  192. if (is == null) {
  193. log.warn("Cannot open " + file);
  194. return null;
  195. }
  196. p.load(is);
  197. } catch (IOException ex) {
  198. log.warn("Error reading " + file + " " + ex.toString());
  199. return null;
  200. }
  201. } finally {
  202. JOrphanUtils.closeQuietly(is);
  203. }
  204. return p;
  205. }
  206. public static PatternCacheLRU getPatternCache() {
  207. return patternCache;
  208. }
  209. /**
  210. * Get a compiled expression from the pattern cache (READ_ONLY).
  211. *
  212. * @param expression
  213. * @return compiled pattern
  214. *
  215. * @throws org.apache.oro.text.regex.MalformedPatternException (Runtime)
  216. * This should be caught for expressions that may vary (e.g. user input)
  217. *
  218. */
  219. public static Pattern getPattern(String expression){
  220. return getPattern(expression, Perl5Compiler.READ_ONLY_MASK);
  221. }
  222. /**
  223. * Get a compiled expression from the pattern cache.
  224. *
  225. * @param expression RE
  226. * @param options e.g. READ_ONLY_MASK
  227. * @return compiled pattern
  228. *
  229. * @throws org.apache.oro.text.regex.MalformedPatternException (Runtime)
  230. * This should be caught for expressions that may vary (e.g. user input)
  231. *
  232. */
  233. public static Pattern getPattern(String expression, int options){
  234. return patternCache.getPattern(expression, options);
  235. }
  236. public void initializeProperties(String file) {
  237. System.out.println("Initializing Properties: " + file);
  238. getProperties(file);
  239. }
  240. /**
  241. * Convenience method for
  242. * {@link ClassFinder#findClassesThatExtend(String[], Class[], boolean)}
  243. * with the option to include inner classes in the search set to false
  244. * and the path list is derived from JMeterUtils.getSearchPaths().
  245. *
  246. * @param superClass - single class to search for
  247. * @return List of Strings containing discovered class names.
  248. */
  249. public static List<String> findClassesThatExtend(Class<?> superClass)
  250. throws IOException {
  251. return ClassFinder.findClassesThatExtend(getSearchPaths(), new Class[]{superClass}, false);
  252. }
  253. /**
  254. * Generate a list of paths to search.
  255. * The output array always starts with
  256. * JMETER_HOME/lib/ext
  257. * and is followed by any paths obtained from the "search_paths" JMeter property.
  258. *
  259. * @return array of path strings
  260. */
  261. public static String[] getSearchPaths() {
  262. String p = JMeterUtils.getPropDefault("search_paths", null); // $NON-NLS-1$
  263. String[] result = new String[1];
  264. if (p != null) {
  265. String[] paths = p.split(";"); // $NON-NLS-1$
  266. result = new String[paths.length + 1];
  267. for (int i = 1; i < result.length; i++) {
  268. result[i] = paths[i - 1];
  269. }
  270. }
  271. result[0] = getJMeterHome() + "/lib/ext"; // $NON-NLS-1$
  272. return result;
  273. }
  274. /**
  275. * Provide random numbers
  276. *
  277. * @param r -
  278. * the upper bound (exclusive)
  279. */
  280. public static int getRandomInt(int r) {
  281. return rand.nextInt(r);
  282. }
  283. /**
  284. * Changes the current locale: re-reads resource strings and notifies
  285. * listeners.
  286. *
  287. * @param loc -
  288. * new locale
  289. */
  290. public static void setLocale(Locale loc) {
  291. log.info("Setting Locale to " + loc.toString());
  292. /*
  293. * See bug 29920. getBundle() defaults to the property file for the
  294. * default Locale before it defaults to the base property file, so we
  295. * need to change the default Locale to ensure the base property file is
  296. * found.
  297. */
  298. Locale def = null;
  299. boolean isDefault = false; // Are we the default language?
  300. if (loc.getLanguage().equals(ENGLISH_LANGUAGE)) {
  301. isDefault = true;
  302. def = Locale.getDefault();
  303. // Don't change locale from en_GB to en
  304. if (!def.getLanguage().equals(ENGLISH_LANGUAGE)) {
  305. Locale.setDefault(Locale.ENGLISH);
  306. } else {
  307. def = null; // no need to reset Locale
  308. }
  309. }
  310. if (loc.toString().equals("ignoreResources")){ // $NON-NLS-1$
  311. log.warn("Resource bundles will be ignored");
  312. ignoreResorces = true;
  313. // Keep existing settings
  314. } else {
  315. ignoreResorces = false;
  316. ResourceBundle resBund = ResourceBundle.getBundle("org.apache.jmeter.resources.messages", loc); // $NON-NLS-1$
  317. resources = resBund;
  318. locale = loc;
  319. final Locale resBundLocale = resBund.getLocale();
  320. if (isDefault || resBundLocale.equals(loc)) {// language change worked
  321. // Check if we at least found the correct language:
  322. } else if (resBundLocale.getLanguage().equals(loc.getLanguage())) {
  323. log.warn("Could not find resources for '"+loc.toString()+"', using '"+resBundLocale.toString()+"'");
  324. } else {
  325. log.error("Could not find resources for '"+loc.toString()+"'");
  326. }
  327. }
  328. notifyLocaleChangeListeners();
  329. /*
  330. * Reset Locale if necessary so other locales are properly handled
  331. */
  332. if (def != null) {
  333. Locale.setDefault(def);
  334. }
  335. }
  336. /**
  337. * Gets the current locale.
  338. *
  339. * @return current locale
  340. */
  341. public static Locale getLocale() {
  342. return locale;
  343. }
  344. public static void addLocaleChangeListener(LocaleChangeListener listener) {
  345. localeChangeListeners.add(listener);
  346. }
  347. public static void removeLocaleChangeListener(LocaleChangeListener listener) {
  348. localeChangeListeners.remove(listener);
  349. }
  350. /**
  351. * Notify all listeners interested in locale changes.
  352. *
  353. */
  354. private static void notifyLocaleChangeListeners() {
  355. LocaleChangeEvent event = new LocaleChangeEvent(JMeterUtils.class, locale);
  356. @SuppressWarnings("unchecked") // clone will produce correct type
  357. Iterator<LocaleChangeListener> iterator = ((Vector<LocaleChangeListener>) localeChangeListeners.clone()).iterator();
  358. while (iterator.hasNext()) {
  359. LocaleChangeListener listener = iterator.next();
  360. listener.localeChanged(event);
  361. }
  362. }
  363. /**
  364. * Gets the resource string for this key.
  365. *
  366. * If the resource is not found, a warning is logged
  367. *
  368. * @param key
  369. * the key in the resource file
  370. * @return the resource string if the key is found; otherwise, return
  371. * "[res_key="+key+"]"
  372. */
  373. public static String getResString(String key) {
  374. return getResStringDefault(key, RES_KEY_PFX + key + "]"); // $NON-NLS-1$
  375. }
  376. public static final String RES_KEY_PFX = "[res_key="; // $NON-NLS-1$
  377. /**
  378. * Gets the resource string for this key.
  379. *
  380. * If the resource is not found, a warning is logged
  381. *
  382. * @param key
  383. * the key in the resource file
  384. * @param defaultValue -
  385. * the default value
  386. *
  387. * @return the resource string if the key is found; otherwise, return the
  388. * default
  389. * @deprecated Only intended for use in development; use
  390. * getResString(String) normally
  391. */
  392. @Deprecated
  393. public static String getResString(String key, String defaultValue) {
  394. return getResStringDefault(key, defaultValue);
  395. }
  396. /*
  397. * Helper method to do the actual work of fetching resources; allows
  398. * getResString(S,S) to be deprecated without affecting getResString(S);
  399. */
  400. private static String getResStringDefault(String key, String defaultValue) {
  401. if (key == null) {
  402. return null;
  403. }
  404. // Resource keys cannot contain spaces, and are forced to lower case
  405. String resKey = key.replace(' ', '_'); // $NON-NLS-1$ // $NON-NLS-2$
  406. resKey = resKey.toLowerCase(java.util.Locale.ENGLISH);
  407. String resString = null;
  408. try {
  409. resString = resources.getString(resKey);
  410. if (ignoreResorces ){ // Special mode for debugging resource handling
  411. return "["+key+"]";
  412. }
  413. } catch (MissingResourceException mre) {
  414. if (ignoreResorces ){ // Special mode for debugging resource handling
  415. return "[?"+key+"?]";
  416. }
  417. log.warn("ERROR! Resource string not found: [" + resKey + "]", mre);
  418. resString = defaultValue;
  419. }
  420. return resString;
  421. }
  422. /**
  423. * To get I18N label from properties file
  424. *
  425. * @param key
  426. * in messages.properties
  427. * @return I18N label without (if exists) last colon ':' and spaces
  428. */
  429. public static String getParsedLabel(String key) {
  430. String value = JMeterUtils.getResString(key);
  431. return value.replaceFirst("(?m)\\s*?:\\s*$", ""); // $NON-NLS-1$ $NON-NLS-2$
  432. }
  433. /**
  434. * Get the locale name as a resource.
  435. * Does not log an error if the resource does not exist.
  436. * This is needed to support additional locales, as they won't be in existing messages files.
  437. *
  438. * @param locale name
  439. * @return the locale display name as defined in the current Locale or the original string if not present
  440. */
  441. public static String getLocaleString(String locale){
  442. // All keys in messages.properties are lowercase (historical reasons?)
  443. String resKey = locale.toLowerCase(java.util.Locale.ENGLISH);
  444. try {
  445. return resources.getString(resKey);
  446. } catch (MissingResourceException e) {
  447. }
  448. return locale;
  449. }
  450. /**
  451. * This gets the currently defined appProperties. It can only be called
  452. * after the {@link #getProperties(String)} method is called.
  453. *
  454. * @return The JMeterProperties value
  455. */
  456. public static Properties getJMeterProperties() {
  457. return appProperties;
  458. }
  459. /**
  460. * This looks for the requested image in the classpath under
  461. * org.apache.jmeter.images. <name>
  462. *
  463. * @param name
  464. * Description of Parameter
  465. * @return The Image value
  466. */
  467. public static ImageIcon getImage(String name) {
  468. try {
  469. return new ImageIcon(JMeterUtils.class.getClassLoader().getResource(
  470. "org/apache/jmeter/images/" + name.trim())); // $NON-NLS-1$
  471. } catch (NullPointerException e) {
  472. log.warn("no icon for " + name);
  473. return null;
  474. } catch (NoClassDefFoundError e) {// Can be returned by headless hosts
  475. log.info("no icon for " + name + " " + e.getMessage());
  476. return null;
  477. } catch (InternalError e) {// Can be returned by headless hosts
  478. log.info("no icon for " + name + " " + e.getMessage());
  479. return null;
  480. }
  481. }
  482. /**
  483. * This looks for the requested image in the classpath under
  484. * org.apache.jmeter.images. <name>, and also sets the description
  485. * of the image, which is useful if the icon is going to be placed
  486. * on the clipboard.
  487. *
  488. * @param name
  489. * the name of the image
  490. * @param description
  491. * the description of the image
  492. * @return The Image value
  493. */
  494. public static ImageIcon getImage(String name, String description) {
  495. ImageIcon icon = getImage(name);
  496. if(icon != null) {
  497. icon.setDescription(description);
  498. }
  499. return icon;
  500. }
  501. public static String getResourceFileAsText(String name) {
  502. BufferedReader fileReader = null;
  503. try {
  504. String lineEnd = System.getProperty("line.separator"); // $NON-NLS-1$
  505. fileReader = new BufferedReader(new InputStreamReader(JMeterUtils.class.getClassLoader()
  506. .getResourceAsStream(name)));
  507. StringBuilder text = new StringBuilder();
  508. String line = "NOTNULL"; // $NON-NLS-1$
  509. while (line != null) {
  510. line = fileReader.readLine();
  511. if (line != null) {
  512. text.append(line);
  513. text.append(lineEnd);
  514. }
  515. }
  516. // Done by finally block: fileReader.close();
  517. return text.toString();
  518. } catch (NullPointerException e) // Cannot find file
  519. {
  520. return ""; // $NON-NLS-1$
  521. } catch (IOException e) {
  522. return ""; // $NON-NLS-1$
  523. } finally {
  524. IOUtils.closeQuietly(fileReader);
  525. }
  526. }
  527. /**
  528. * Creates the vector of Timers plugins.
  529. *
  530. * @param properties
  531. * Description of Parameter
  532. * @return The Timers value
  533. */
  534. public static Vector<Object> getTimers(Properties properties) {
  535. return instantiate(getVector(properties, "timer."), // $NON-NLS-1$
  536. "org.apache.jmeter.timers.Timer"); // $NON-NLS-1$
  537. }
  538. /**
  539. * Creates the vector of visualizer plugins.
  540. *
  541. * @param properties
  542. * Description of Parameter
  543. * @return The Visualizers value
  544. */
  545. public static Vector<Object> getVisualizers(Properties properties) {
  546. return instantiate(getVector(properties, "visualizer."), // $NON-NLS-1$
  547. "org.apache.jmeter.visualizers.Visualizer"); // $NON-NLS-1$
  548. }
  549. /**
  550. * Creates a vector of SampleController plugins.
  551. *
  552. * @param properties
  553. * The properties with information about the samplers
  554. * @return The Controllers value
  555. */
  556. // TODO - does not appear to be called directly
  557. public static Vector<Object> getControllers(Properties properties) {
  558. String name = "controller."; // $NON-NLS-1$
  559. Vector<Object> v = new Vector<Object>();
  560. Enumeration<?> names = properties.keys();
  561. while (names.hasMoreElements()) {
  562. String prop = (String) names.nextElement();
  563. if (prop.startsWith(name)) {
  564. Object o = instantiate(properties.getProperty(prop),
  565. "org.apache.jmeter.control.SamplerController"); // $NON-NLS-1$
  566. v.addElement(o);
  567. }
  568. }
  569. return v;
  570. }
  571. /**
  572. * Create a string of class names for a particular SamplerController
  573. *
  574. * @param properties
  575. * The properties with info about the samples.
  576. * @param name
  577. * The name of the sampler controller.
  578. * @return The TestSamples value
  579. */
  580. public static String[] getTestSamples(Properties properties, String name) {
  581. return getVector(properties, name + ".testsample").toArray(new String[0]); // $NON-NLS-1$
  582. }
  583. /**
  584. * Create an instance of an org.xml.sax.Parser based on the default props.
  585. *
  586. * @return The XMLParser value
  587. */
  588. public static XMLReader getXMLParser() {
  589. XMLReader reader = null;
  590. try {
  591. reader = (XMLReader) instantiate(getPropDefault("xml.parser", // $NON-NLS-1$
  592. "org.apache.xerces.parsers.SAXParser"), // $NON-NLS-1$
  593. "org.xml.sax.XMLReader"); // $NON-NLS-1$
  594. // reader = xmlFactory.newSAXParser().getXMLReader();
  595. } catch (Exception e) {
  596. reader = (XMLReader) instantiate(getPropDefault("xml.parser", // $NON-NLS-1$
  597. "org.apache.xerces.parsers.SAXParser"), // $NON-NLS-1$
  598. "org.xml.sax.XMLReader"); // $NON-NLS-1$
  599. }
  600. return reader;
  601. }
  602. /**
  603. * Creates the vector of alias strings.
  604. *
  605. * @param properties
  606. * @return The Alias value
  607. */
  608. public static Hashtable<String, String> getAlias(Properties properties) {
  609. return getHashtable(properties, "alias."); // $NON-NLS-1$
  610. }
  611. /**
  612. * Creates a vector of strings for all the properties that start with a
  613. * common prefix.
  614. *
  615. * @param properties
  616. * Description of Parameter
  617. * @param name
  618. * Description of Parameter
  619. * @return The Vector value
  620. */
  621. public static Vector<String> getVector(Properties properties, String name) {
  622. Vector<String> v = new Vector<String>();
  623. Enumeration<?> names = properties.keys();
  624. while (names.hasMoreElements()) {
  625. String prop = (String) names.nextElement();
  626. if (prop.startsWith(name)) {
  627. v.addElement(properties.getProperty(prop));
  628. }
  629. }
  630. return v;
  631. }
  632. /**
  633. * Creates a table of strings for all the properties that start with a
  634. * common prefix.
  635. *
  636. * @param properties input to search
  637. * @param prefix to match against properties
  638. * @return a Hashtable where the keys are the original keys with the prefix removed
  639. */
  640. public static Hashtable<String, String> getHashtable(Properties properties, String prefix) {
  641. Hashtable<String, String> t = new Hashtable<String, String>();
  642. Enumeration<?> names = properties.keys();
  643. final int length = prefix.length();
  644. while (names.hasMoreElements()) {
  645. String prop = (String) names.nextElement();
  646. if (prop.startsWith(prefix)) {
  647. t.put(prop.substring(length), properties.getProperty(prop));
  648. }
  649. }
  650. return t;
  651. }
  652. /**
  653. * Get a int value with default if not present.
  654. *
  655. * @param propName
  656. * the name of the property.
  657. * @param defaultVal
  658. * the default value.
  659. * @return The PropDefault value
  660. */
  661. public static int getPropDefault(String propName, int defaultVal) {
  662. int ans;
  663. try {
  664. ans = (Integer.valueOf(appProperties.getProperty(propName, Integer.toString(defaultVal)).trim()))
  665. .intValue();
  666. } catch (Exception e) {
  667. ans = defaultVal;
  668. }
  669. return ans;
  670. }
  671. /**
  672. * Get a boolean value with default if not present.
  673. *
  674. * @param propName
  675. * the name of the property.
  676. * @param defaultVal
  677. * the default value.
  678. * @return The PropDefault value
  679. */
  680. public static boolean getPropDefault(String propName, boolean defaultVal) {
  681. boolean ans;
  682. try {
  683. String strVal = appProperties.getProperty(propName, Boolean.toString(defaultVal)).trim();
  684. if (strVal.equalsIgnoreCase("true") || strVal.equalsIgnoreCase("t")) { // $NON-NLS-1$ // $NON-NLS-2$
  685. ans = true;
  686. } else if (strVal.equalsIgnoreCase("false") || strVal.equalsIgnoreCase("f")) { // $NON-NLS-1$ // $NON-NLS-2$
  687. ans = false;
  688. } else {
  689. ans = ((Integer.valueOf(strVal)).intValue() == 1);
  690. }
  691. } catch (Exception e) {
  692. ans = defaultVal;
  693. }
  694. return ans;
  695. }
  696. /**
  697. * Get a long value with default if not present.
  698. *
  699. * @param propName
  700. * the name of the property.
  701. * @param defaultVal
  702. * the default value.
  703. * @return The PropDefault value
  704. */
  705. public static long getPropDefault(String propName, long defaultVal) {
  706. long ans;
  707. try {
  708. ans = (Long.valueOf(appProperties.getProperty(propName, Long.toString(defaultVal)).trim())).longValue();
  709. } catch (Exception e) {
  710. ans = defaultVal;
  711. }
  712. return ans;
  713. }
  714. /**
  715. * Get a String value with default if not present.
  716. *
  717. * @param propName
  718. * the name of the property.
  719. * @param defaultVal
  720. * the default value.
  721. * @return The PropDefault value
  722. */
  723. public static String getPropDefault(String propName, String defaultVal) {
  724. String ans;
  725. try {
  726. ans = appProperties.getProperty(propName, defaultVal).trim();
  727. } catch (Exception e) {
  728. ans = defaultVal;
  729. }
  730. return ans;
  731. }
  732. /**
  733. * Get the value of a JMeter property.
  734. *
  735. * @param propName
  736. * the name of the property.
  737. * @return the value of the JMeter property, or null if not defined
  738. */
  739. public static String getProperty(String propName) {
  740. String ans = null;
  741. try {
  742. ans = appProperties.getProperty(propName);
  743. } catch (Exception e) {
  744. ans = null;
  745. }
  746. return ans;
  747. }
  748. /**
  749. * Set a String value
  750. *
  751. * @param propName
  752. * the name of the property.
  753. * @param propValue
  754. * the value of the property
  755. * @return the previous value of the property
  756. */
  757. public static Object setProperty(String propName, String propValue) {
  758. return appProperties.setProperty(propName, propValue);
  759. }
  760. /**
  761. * Sets the selection of the JComboBox to the Object 'name' from the list in
  762. * namVec.
  763. * NOTUSED?
  764. */
  765. public static void selJComboBoxItem(Properties properties, JComboBox combo, Vector<?> namVec, String name) {
  766. int idx = namVec.indexOf(name);
  767. combo.setSelectedIndex(idx);
  768. // Redisplay.
  769. combo.updateUI();
  770. return;
  771. }
  772. /**
  773. * Instatiate an object and guarantee its class.
  774. *
  775. * @param className
  776. * The name of the class to instantiate.
  777. * @param impls
  778. * The name of the class it subclases.
  779. * @return Description of the Returned Value
  780. */
  781. public static Object instantiate(String className, String impls) {
  782. if (className != null) {
  783. className = className.trim();
  784. }
  785. if (impls != null) {
  786. impls = impls.trim();
  787. }
  788. try {
  789. Class<?> c = Class.forName(impls);
  790. try {
  791. Class<?> o = Class.forName(className);
  792. Object res = o.newInstance();
  793. if (c.isInstance(res)) {
  794. return res;
  795. }
  796. throw new IllegalArgumentException(className + " is not an instance of " + impls);
  797. } catch (ClassNotFoundException e) {
  798. log.error("Error loading class " + className + ": class is not found");
  799. } catch (IllegalAccessException e) {
  800. log.error("Error loading class " + className + ": does not have access");
  801. } catch (InstantiationException e) {
  802. log.error("Error loading class " + className + ": could not instantiate");
  803. } catch (NoClassDefFoundError e) {
  804. log.error("Error loading class " + className + ": couldn't find class " + e.getMessage());
  805. }
  806. } catch (ClassNotFoundException e) {
  807. log.error("Error loading class " + impls + ": was not found.");
  808. }
  809. return null;
  810. }
  811. /**
  812. * Instantiate a vector of classes
  813. *
  814. * @param v
  815. * Description of Parameter
  816. * @param className
  817. * Description of Parameter
  818. * @return Description of the Returned Value
  819. */
  820. public static Vector<Object> instantiate(Vector<String> v, String className) {
  821. Vector<Object> i = new Vector<Object>();
  822. try {
  823. Class<?> c = Class.forName(className);
  824. Enumeration<String> elements = v.elements();
  825. while (elements.hasMoreElements()) {
  826. String name = elements.nextElement();
  827. try {
  828. Object o = Class.forName(name).newInstance();
  829. if (c.isInstance(o)) {
  830. i.addElement(o);
  831. }
  832. } catch (ClassNotFoundException e) {
  833. log.error("Error loading class " + name + ": class is not found");
  834. } catch (IllegalAccessException e) {
  835. log.error("Error loading class " + name + ": does not have access");
  836. } catch (InstantiationException e) {
  837. log.error("Error loading class " + name + ": could not instantiate");
  838. } catch (NoClassDefFoundError e) {
  839. log.error("Error loading class " + name + ": couldn't find class " + e.getMessage());
  840. }
  841. }
  842. } catch (ClassNotFoundException e) {
  843. log.error("Error loading class " + className + ": class is not found");
  844. }
  845. return i;
  846. }
  847. /**
  848. * Tokenize a string into a vector of tokens
  849. *
  850. * @param string
  851. * Description of Parameter
  852. * @param separator
  853. * Description of Parameter
  854. * @return Description of the Returned Value
  855. */
  856. //TODO move to JOrphanUtils ?
  857. public static Vector<String> tokenize(String string, String separator) {
  858. Vector<String> v = new Vector<String>();
  859. StringTokenizer s = new StringTokenizer(string, separator);
  860. while (s.hasMoreTokens()) {
  861. v.addElement(s.nextToken());
  862. }
  863. return v;
  864. }
  865. /**
  866. * Create a button with the netscape style
  867. *
  868. * @param name
  869. * Description of Parameter
  870. * @param listener
  871. * Description of Parameter
  872. * @return Description of the Returned Value
  873. */
  874. public static JButton createButton(String name, ActionListener listener) {
  875. JButton button = new JButton(getImage(name + ".on.gif")); // $NON-NLS-1$
  876. button.setDisabledIcon(getImage(name + ".off.gif")); // $NON-NLS-1$
  877. button.setRolloverIcon(getImage(name + ".over.gif")); // $NON-NLS-1$
  878. button.setPressedIcon(getImage(name + ".down.gif")); // $NON-NLS-1$
  879. button.setActionCommand(name);
  880. button.addActionListener(listener);
  881. button.setRolloverEnabled(true);
  882. button.setFocusPainted(false);
  883. button.setBorderPainted(false);
  884. button.setOpaque(false);
  885. button.setPreferredSize(new Dimension(24, 24));
  886. return button;
  887. }
  888. /**
  889. * Create a button with the netscape style
  890. *
  891. * @param name
  892. * Description of Parameter
  893. * @param listener
  894. * Description of Parameter
  895. * @return Description of the Returned Value
  896. */
  897. public static JButton createSimpleButton(String name, ActionListener listener) {
  898. JButton button = new JButton(getImage(name + ".gif")); // $NON-NLS-1$
  899. button.setActionCommand(name);
  900. button.addActionListener(listener);
  901. button.setFocusPainted(false);
  902. button.setBorderPainted(false);
  903. button.setOpaque(false);
  904. button.setPreferredSize(new Dimension(25, 25));
  905. return button;
  906. }
  907. /**
  908. * Report an error through a dialog box.
  909. * Title defaults to "error_title" resource string
  910. * @param errorMsg - the error message.
  911. */
  912. public static void reportErrorToUser(String errorMsg) {
  913. reportErrorToUser(errorMsg, JMeterUtils.getResString("error_title")); // $NON-NLS-1$
  914. }
  915. /**
  916. * Report an error through a dialog box.
  917. *
  918. * @param errorMsg - the error message.
  919. * @param titleMsg - title string
  920. */
  921. public static void reportErrorToUser(String errorMsg, String titleMsg) {
  922. if (errorMsg == null) {
  923. errorMsg = "Unknown error - see log file";
  924. log.warn("Unknown error", new Throwable("errorMsg == null"));
  925. }
  926. GuiPackage instance = GuiPackage.getInstance();
  927. if (instance == null) {
  928. System.out.println(errorMsg);
  929. return; // Done
  930. }
  931. try {
  932. JOptionPane.showMessageDialog(instance.getMainFrame(),
  933. errorMsg,
  934. titleMsg,
  935. JOptionPane.ERROR_MESSAGE);
  936. } catch (HeadlessException e) {
  937. log.warn("reportErrorToUser(\"" + errorMsg + "\") caused", e);
  938. }
  939. }
  940. /**
  941. * Finds a string in an array of strings and returns the
  942. *
  943. * @param array
  944. * Array of strings.
  945. * @param value
  946. * String to compare to array values.
  947. * @return Index of value in array, or -1 if not in array.
  948. */
  949. //TODO - move to JOrphanUtils?
  950. public static int findInArray(String[] array, String value) {
  951. int count = -1;
  952. int index = -1;
  953. if (array != null && value != null) {
  954. while (++count < array.length) {
  955. if (array[count] != null && array[count].equals(value)) {
  956. index = count;
  957. break;
  958. }
  959. }
  960. }
  961. return index;
  962. }
  963. /**
  964. * Takes an array of strings and a tokenizer character, and returns a string
  965. * of all the strings concatenated with the tokenizer string in between each
  966. * one.
  967. *
  968. * @param splittee
  969. * Array of Objects to be concatenated.
  970. * @param splitChar
  971. * Object to unsplit the strings with.
  972. * @return Array of all the tokens.
  973. */
  974. //TODO - move to JOrphanUtils?
  975. public static String unsplit(Object[] splittee, Object splitChar) {
  976. StringBuilder retVal = new StringBuilder();
  977. int count = -1;
  978. while (++count < splittee.length) {
  979. if (splittee[count] != null) {
  980. retVal.append(splittee[count]);
  981. }
  982. if (count + 1 < splittee.length && splittee[count + 1] != null) {
  983. retVal.append(splitChar);
  984. }
  985. }
  986. return retVal.toString();
  987. }
  988. // End Method
  989. /**
  990. * Takes an array of strings and a tokenizer character, and returns a string
  991. * of all the strings concatenated with the tokenizer string in between each
  992. * one.
  993. *
  994. * @param splittee
  995. * Array of Objects to be concatenated.
  996. * @param splitChar
  997. * Object to unsplit the strings with.
  998. * @param def
  999. * Default value to replace null values in array.
  1000. * @return Array of all the tokens.
  1001. */
  1002. //TODO - move to JOrphanUtils?
  1003. public static String unsplit(Object[] splittee, Object splitChar, String def) {
  1004. StringBuilder retVal = new StringBuilder();
  1005. int count = -1;
  1006. while (++count < splittee.length) {
  1007. if (splittee[count] != null) {
  1008. retVal.append(splittee[count]);
  1009. } else {
  1010. retVal.append(def);
  1011. }
  1012. if (count + 1 < splittee.length) {
  1013. retVal.append(splitChar);
  1014. }
  1015. }
  1016. return retVal.toString();
  1017. }
  1018. /**
  1019. * Get the JMeter home directory - does not include the trailing separator.
  1020. *
  1021. * @return the home directory
  1022. */
  1023. public static String getJMeterHome() {
  1024. return jmDir;
  1025. }
  1026. /**
  1027. * Get the JMeter bin directory - does not include the trailing separator.
  1028. *
  1029. * @return the bin directory
  1030. */
  1031. public static String getJMeterBinDir() {
  1032. return jmBin;
  1033. }
  1034. public static void setJMeterHome(String home) {
  1035. jmDir = home;
  1036. jmBin = jmDir + File.separator + "bin"; // $NON-NLS-1$
  1037. }
  1038. // TODO needs to be synch? Probably not changed after threads have started
  1039. private static String jmDir; // JMeter Home directory (excludes trailing separator)
  1040. private static String jmBin; // JMeter bin directory (excludes trailing separator)
  1041. /**
  1042. * Gets the JMeter Version.
  1043. *
  1044. * @return the JMeter version string
  1045. */
  1046. public static String getJMeterVersion() {
  1047. return JMeterVersion.getVERSION();
  1048. }
  1049. /**
  1050. * Gets the JMeter copyright.
  1051. *
  1052. * @return the JMeter copyright string
  1053. */
  1054. public static String getJMeterCopyright() {
  1055. return JMeterVersion.COPYRIGHT;
  1056. }
  1057. /**
  1058. * Determine whether we are in 'expert' mode. Certain features may be hidden
  1059. * from user's view unless in expert mode.
  1060. *
  1061. * @return true iif we're in expert mode
  1062. */
  1063. public static boolean isExpertMode() {
  1064. return JMeterUtils.getPropDefault(EXPERT_MODE_PROPERTY, false);
  1065. }
  1066. /**
  1067. * Find a file in the current directory or in the JMeter bin directory.
  1068. *
  1069. * @param fileName
  1070. * @return File object
  1071. */
  1072. public static File findFile(String fileName){
  1073. File f =new File(fileName);
  1074. if (!f.exists()){
  1075. f=new File(getJMeterBinDir(),fileName);
  1076. }
  1077. return f;
  1078. }
  1079. /**
  1080. * Returns the cached result from calling
  1081. * InetAddress.getLocalHost().getHostAddress()
  1082. *
  1083. * @return String representation of local IP address
  1084. */
  1085. public static synchronized String getLocalHostIP(){
  1086. if (localHostIP == null) {
  1087. getLocalHostDetails();
  1088. }
  1089. return localHostIP;
  1090. }
  1091. /**
  1092. * Returns the cached result from calling
  1093. * InetAddress.getLocalHost().getHostName()
  1094. *
  1095. * @return local host name
  1096. */
  1097. public static synchronized String getLocalHostName(){
  1098. if (localHostName == null) {
  1099. getLocalHostDetails();
  1100. }
  1101. return localHostName;
  1102. }
  1103. /**
  1104. * Returns the cached result from calling
  1105. * InetAddress.getLocalHost().getCanonicalHostName()
  1106. *
  1107. * @return local host name in canonical form
  1108. */
  1109. public static synchronized String getLocalHostFullName(){
  1110. if (localHostFullName == null) {
  1111. getLocalHostDetails();
  1112. }
  1113. return localHostFullName;
  1114. }
  1115. private static void getLocalHostDetails(){
  1116. InetAddress localHost=null;
  1117. try {
  1118. localHost = InetAddress.getLocalHost();
  1119. } catch (UnknownHostException e1) {
  1120. log.error("Unable to get local host IP address.");
  1121. return; // TODO - perhaps this should be a fatal error?
  1122. }
  1123. localHostIP=localHost.getHostAddress();
  1124. localHostName=localHost.getHostName();
  1125. localHostFullName=localHost.getCanonicalHostName();
  1126. }
  1127. /**
  1128. * Split line into name/value pairs and remove colon ':'
  1129. *
  1130. * @param headers
  1131. * multi-line string headers
  1132. * @return a map name/value for each header
  1133. */
  1134. public static LinkedHashMap<String, String> parseHeaders(String headers) {
  1135. LinkedHashMap<String, String> linkedHeaders = new LinkedHashMap<String, String>();
  1136. String[] list = headers.split("\n"); // $NON-NLS-1$
  1137. for (String header : list) {
  1138. int colon = header.indexOf(':'); // $NON-NLS-1$
  1139. if (colon <= 0) {
  1140. linkedHeaders.put(header, ""); // Empty value // $NON-NLS-1$
  1141. } else {
  1142. linkedHeaders.put(header.substring(0, colon).trim(), header
  1143. .substring(colon + 1).trim());
  1144. }
  1145. }
  1146. return linkedHeaders;
  1147. }
  1148. }