source: src/main/java/weka/core/Environment.java @ 27

Last change on this file since 27 was 4, checked in by gnappo, 14 years ago

Import di weka.

File size: 5.7 KB
Line 
1/*
2 *    This program is free software; you can redistribute it and/or modify
3 *    it under the terms of the GNU General Public License as published by
4 *    the Free Software Foundation; either version 2 of the License, or
5 *    (at your option) any later version.
6 *
7 *    This program is distributed in the hope that it will be useful,
8 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
9 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10 *    GNU General Public License for more details.
11 *
12 *    You should have received a copy of the GNU General Public License
13 *    along with this program; if not, write to the Free Software
14 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15 */
16
17/*
18 *    Environment.java
19 *    Copyright (C) 2008 University of Waikato, Hamilton, New Zealand
20 *
21 */
22
23package weka.core;
24
25import java.util.Enumeration;
26import java.util.Iterator;
27import java.util.Map;
28import java.util.Properties;
29import java.util.Set;
30import java.util.TreeMap;
31
32/**
33 * This class encapsulates a map of all environment and java system properties.
34 * There are methods for adding and removing variables as well as a method for
35 * replacing key names (enclosed by ${}) with their associated value in Strings.
36 *
37 * @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
38 * @version $Revision: 5987 $
39 */
40public class Environment implements RevisionHandler {
41 
42  private static Environment m_systemWide = new Environment();
43 
44  // Map to hold all the system environment variables + java properties
45  private Map<String,String> m_envVars = new TreeMap<String,String>();
46 
47  public Environment() {
48    // get the env variables first
49    Map<String,String> env = System.getenv();
50    Set<String> keys = env.keySet();
51    Iterator<String> i = keys.iterator();
52    while (i.hasNext()) {
53      String kv = i.next();
54      String value = env.get(kv);
55      m_envVars.put(kv, value);
56    }
57
58    // get the java properties
59    Properties jvmProps = System.getProperties();
60    Enumeration pKeys = jvmProps.propertyNames();
61    while (pKeys.hasMoreElements()) {
62      String kv = (String)pKeys.nextElement();
63      String value = jvmProps.getProperty(kv);
64      m_envVars.put(kv, value);
65    }
66    m_envVars.put("weka.version", Version.VERSION);
67  }
68 
69  /**
70   * Get the singleton system-wide (visible to every
71   * class in the running VM) set of environment
72   * variables.
73   *
74   * @return the system-wide set of environment variables.
75   */
76  public static Environment getSystemWide() {
77    return m_systemWide;
78  }
79 
80  /**
81   * Tests for the presence of environment variables.
82   *
83   * @param source the string to test
84   * @return true if the argument contains one or more environment
85   * variables
86   */
87  public static boolean containsEnvVariables(String source) {
88    return (source.indexOf("${") >= 0);
89  }
90
91  /**
92   * Substitute a variable names for their values in the given string.
93   *
94   * @param source the source string to replace variables in
95   * @return a String with all variable names replaced with their values
96   * @throws Exception if an unknown variable name is encountered
97   */
98  public String substitute(String source) throws Exception {
99    // Grab each variable out of the string
100    int index = source.indexOf("${");
101
102    while (index >= 0) {
103      index += 2;
104      int endIndex = source.indexOf('}');
105      if (endIndex >= 0 && endIndex > index +1) {
106        String key = source.substring(index, endIndex);
107
108        // look this sucker up
109        String replace = m_envVars.get(key);
110        if (replace != null) {
111          String toReplace = "${" + key + "}";
112          source = source.replace(toReplace, replace);
113        } else {
114          throw new Exception("[Environment] Variable " 
115                              + key + " doesn't seem to be set.");
116        }
117      } else {
118        break;
119      }
120      index = source.indexOf("${");
121    }
122    return source;
123  }
124
125  /**
126   * Add a variable to the internal map.
127   *
128   * @param key the name of the variable
129   * @param value its value
130   */
131  public void addVariable(String key, String value) {
132    m_envVars.put(key, value);
133  }
134
135  /**
136   * Remove a named variable from the map.
137   *
138   * @param key the name of the varaible to remove.
139   */
140  public void removeVariable(String key) {
141    m_envVars.remove(key);
142  }
143 
144  /**
145   * Get the names of the variables (keys) stored in the
146   * internal map.
147   *
148   * @return a Set of variable names (keys)
149   */
150  public Set<String> getVariableNames() {
151    return m_envVars.keySet();
152  }
153
154  /**
155   * Get the value for a particular variable.
156   *
157   * @param key the name of the variable to get
158   * @return the associated value or null if this variable
159   * is not in the internal map
160   */
161  public String getVariableValue(String key) {
162    return m_envVars.get(key);
163  }
164 
165  /**
166   * Main method for testing this class.
167   *
168   * @param args a list of strings to replace variables in
169   * (e.g. "\${os.name} "\${java.version}")
170   */
171  public static void main(String[] args) {
172    Environment t = new Environment();
173    //    String test = "Here is a string with the variable ${java.version} and ${os.name} in it";
174
175    if (args.length == 0) {
176      System.err.println("Usage: java weka.core.Environment <string> <string> ...");
177    } else {
178      try {
179        for (int i = 0; i < args.length; i++) {
180          String newS = t.substitute(args[i]);
181          System.out.println("Original string:\n" + args[i] +"\n\nNew string:\n" + newS);
182        }
183      } catch (Exception ex) {
184        ex.printStackTrace();
185      }
186    }
187  }
188
189  /**
190   * Returns the revision string.
191   *
192   * @return            the revision
193   */
194  public String getRevision() {
195    return RevisionUtils.extract("$Revision: 5987 $");
196  }
197}
Note: See TracBrowser for help on using the repository browser.