PageRenderTime 72ms CodeModel.GetById 42ms RepoModel.GetById 0ms app.codeStats 0ms

/cruisecontrol/main/src/net/sourceforge/cruisecontrol/util/OSEnvironment.java

https://github.com/builddoctor/cruisecontrol
Java | 316 lines | 98 code | 20 blank | 198 comment | 16 complexity | 4c46164e47857931a684d3101aacce6f MD5 | raw file
  1. /********************************************************************************
  2. * CruiseControl, a Continuous Integration Toolkit
  3. * Copyright (c) 2001-2003, ThoughtWorks, Inc.
  4. * 200 E. Randolph, 25th Floor
  5. * Chicago, IL 60601 USA
  6. * All rights reserved.
  7. *
  8. * Redistribution and use in source and binary forms, with or without
  9. * modification, are permitted provided that the following conditions
  10. * are met:
  11. *
  12. * + Redistributions of source code must retain the above copyright
  13. * notice, this list of conditions and the following disclaimer.
  14. *
  15. * + Redistributions in binary form must reproduce the above
  16. * copyright notice, this list of conditions and the following
  17. * disclaimer in the documentation and/or other materials provided
  18. * with the distribution.
  19. *
  20. * + Neither the name of ThoughtWorks, Inc., CruiseControl, nor the
  21. * names of its contributors may be used to endorse or promote
  22. * products derived from this software without specific prior
  23. * written permission.
  24. *
  25. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  26. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  27. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  28. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR
  29. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  30. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  31. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  32. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  33. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  34. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  35. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  36. ********************************************************************************/
  37. /*
  38. * The Apache Software License, Version 1.1
  39. *
  40. * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
  41. * reserved.
  42. *
  43. * Redistribution and use in source and binary forms, with or without
  44. * modification, are permitted provided that the following conditions
  45. * are met:
  46. *
  47. * 1. Redistributions of source code must retain the above copyright
  48. * notice, this list of conditions and the following disclaimer.
  49. *
  50. * 2. Redistributions in binary form must reproduce the above copyright
  51. * notice, this list of conditions and the following disclaimer in
  52. * the documentation and/or other materials provided with the
  53. * distribution.
  54. *
  55. * 3. The end-user documentation included with the redistribution, if
  56. * any, must include the following acknowlegement:
  57. * "This product includes software developed by the
  58. * Apache Software Foundation (http://www.apache.org/)."
  59. * Alternately, this acknowlegement may appear in the software itself,
  60. * if and wherever such third-party acknowlegements normally appear.
  61. *
  62. * 4. The names "The Jakarta Project", "Ant", and "Apache Software
  63. * Foundation" must not be used to endorse or promote products derived
  64. * from this software without prior written permission. For written
  65. * permission, please contact apache@apache.org.
  66. *
  67. * 5. Products derived from this software may not be called "Apache"
  68. * nor may "Apache" appear in their names without prior written
  69. * permission of the Apache Group.
  70. *
  71. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
  72. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  73. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  74. * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
  75. * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  76. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  77. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  78. * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  79. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  80. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  81. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  82. * SUCH DAMAGE.
  83. * ====================================================================
  84. *
  85. * This software consists of voluntary contributions made by many
  86. * individuals on behalf of the Apache Software Foundation. For more
  87. * information on the Apache Software Foundation, please see
  88. * <http://www.apache.org/>.
  89. */
  90. package net.sourceforge.cruisecontrol.util;
  91. import java.io.BufferedReader;
  92. import java.io.InputStreamReader;
  93. import java.util.ArrayList;
  94. import java.util.Enumeration;
  95. import java.util.List;
  96. import java.util.Properties;
  97. import org.apache.log4j.Logger;
  98. /**
  99. * A simple utility class for obtaining and parsing system environment
  100. * variables. It has been tested on Windows 2000, Windows XP, Solaris, and
  101. * HP-UX, though it should work with any Win32 (95+) or Unix based palatform.
  102. *
  103. * @author <a href="mailto:rjmpsmith@hotmail.com">Robert J. Smith </a>
  104. */
  105. public class OSEnvironment {
  106. private static final Logger LOG = Logger.getLogger(OSEnvironment.class);
  107. /**
  108. * Internal representation of the system environment
  109. */
  110. private final Properties variables = new Properties();
  111. /**
  112. * Constructor
  113. *
  114. * Creates an instance of OSEnvironment, queries the OS to discover it's
  115. * environment variables and makes them available through the getter methods
  116. */
  117. public OSEnvironment() {
  118. parse();
  119. }
  120. /**
  121. * Parses the OS environment and makes the environment variables available
  122. * through the getter methods
  123. */
  124. private void parse() {
  125. final String command;
  126. // Detemine the correct command to run based on OS name
  127. final String os = System.getProperty("os.name").toLowerCase();
  128. if (isWindows9x(os)) {
  129. command = "command.com /c set";
  130. } else if ((os.indexOf("nt") > -1) || (os.indexOf("windows") > -1)
  131. || (os.indexOf("os/2") > -1)) {
  132. command = "cmd.exe /c set";
  133. } else {
  134. // should work for just about any Unix variant
  135. command = "env";
  136. }
  137. // Get our environment
  138. try {
  139. final Process p = Runtime.getRuntime().exec(command);
  140. p.getOutputStream().close();
  141. // Capture the output of the command
  142. final BufferedReader stdoutStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
  143. final BufferedReader stderrStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
  144. try {
  145. // Parse the output
  146. String line;
  147. String key = null;
  148. while ((line = stdoutStream.readLine()) != null) {
  149. int idx = line.indexOf('=');
  150. String value;
  151. if (idx == -1) {
  152. if (key == null) {
  153. continue;
  154. }
  155. // potential multi-line property. Let's rebuild it
  156. value = variables.getProperty(key);
  157. value += "\n" + line;
  158. } else {
  159. key = line.substring(0, idx);
  160. value = line.substring(idx + 1);
  161. }
  162. variables.setProperty(key, value);
  163. }
  164. } finally {
  165. // Close down our streams
  166. stdoutStream.close();
  167. stderrStream.close();
  168. }
  169. } catch (Exception e) {
  170. LOG.error("Failed to parse the OS environment.", e);
  171. }
  172. }
  173. private boolean isWindows9x(String os) {
  174. return os.indexOf("windows 9") > -1;
  175. }
  176. /**
  177. * Gets the value of an environment variable. The variable name is case
  178. * sensitive.
  179. *
  180. * @param variable
  181. * The variable for which you wish the value
  182. *
  183. * @return The value of the variable, or <code>null</code> if not found
  184. *
  185. * @see #getVariable(String variable, String defaultValue)
  186. */
  187. public String getVariable(String variable) {
  188. return variables.getProperty(variable);
  189. }
  190. /**
  191. * Gets the value of an environment variable. The variable name is case
  192. * sensitive.
  193. *
  194. * @param variable
  195. * the variable for which you wish the value
  196. *
  197. * @param defaultValue
  198. * The value to return if the variable is not set in the
  199. * environment.
  200. *
  201. * @return The value of the variable. If the variable is not found, the
  202. * defaultValue is returned.
  203. */
  204. public String getVariable(String variable, String defaultValue) {
  205. return variables.getProperty(variable, defaultValue);
  206. }
  207. /**
  208. * Gets the value of an environment variable. The variable name is NOT case
  209. * sensitive. If more than one variable matches the pattern provided, the
  210. * result is unpredictable. You are greatly encouraged to use
  211. * <code>getVariable()</code> instead.
  212. *
  213. * @param variable
  214. * the variable for which you wish the value
  215. *
  216. * @return the value of an environment variable
  217. *
  218. * @see #getVariable(String variable)
  219. * @see #getVariable(String variable, String defaultValue)
  220. */
  221. public String getVariableIgnoreCase(final String variable) {
  222. final Enumeration keys = variables.keys();
  223. while (keys.hasMoreElements()) {
  224. final String key = (String) keys.nextElement();
  225. if (key.equalsIgnoreCase(variable)) {
  226. return variables.getProperty(key);
  227. }
  228. }
  229. return null;
  230. }
  231. /**
  232. * Adds a variable to this representation of the environment. If the
  233. * variable already existed, the value will be replaced.
  234. *
  235. * @param variable
  236. * the variable to set
  237. * @param value
  238. * the value of the variable
  239. */
  240. public void add(String variable, String value) {
  241. variables.setProperty(variable, value);
  242. }
  243. /**
  244. * Deletes a variable from this representation of the environment. If the
  245. * variable does not exist, it is ignored.
  246. *
  247. * @param variable
  248. * the variable to delete
  249. */
  250. public void del(final String variable) {
  251. variables.remove(variable);
  252. }
  253. /**
  254. * Returns all environment variables which were set at the time the class
  255. * was instantiated, as well as any which have been added programatically.
  256. *
  257. * @return a <code>List</code> of all environment variables. The
  258. * <code>List</code> is made up of <code>String</code>s of the
  259. * form "variable=value".
  260. *
  261. * @see #toArray()
  262. */
  263. public List<String> getEnvironment() {
  264. final List<String> env = new ArrayList<String>();
  265. Enumeration keys = variables.keys();
  266. while (keys.hasMoreElements()) {
  267. String key = (String) keys.nextElement();
  268. env.add(key + "=" + variables.getProperty(key));
  269. }
  270. return env;
  271. }
  272. /**
  273. * Returns all environment variables which were set at the time the class
  274. * was instantiated, as well as any which have been added programatically.
  275. *
  276. * @return a <code>String[]</code> containing all environment variables.
  277. * The <code>String</code>s are of the form "variable=value".
  278. * This is the format expected by
  279. * <code>java.lang.Runtime.exec()</code>.
  280. *
  281. * @see java.lang.Runtime
  282. */
  283. public String[] toArray() {
  284. final List<String> list = getEnvironment();
  285. return list.toArray(new String[list.size()]);
  286. }
  287. /**
  288. * Returns a <code>String<code> representation of the
  289. * environment.
  290. *
  291. * @return A <code>String<code> representation of the environment
  292. */
  293. public String toString() {
  294. return variables.toString();
  295. }
  296. }