KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sourceforge > cruisecontrol > util > OSEnvironment


1 /********************************************************************************
2  * CruiseControl, a Continuous Integration Toolkit
3  * Copyright (c) 2001-2003, ThoughtWorks, Inc.
4  * 651 W Washington Ave. Suite 600
5  * Chicago, IL 60661 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
92 import java.io.BufferedReader JavaDoc;
93 import java.io.InputStreamReader JavaDoc;
94 import java.util.ArrayList JavaDoc;
95 import java.util.Enumeration JavaDoc;
96 import java.util.List JavaDoc;
97 import java.util.Properties JavaDoc;
98
99 import org.apache.log4j.Logger;
100
101 /**
102  * A simple utility class for obtaining and parsing system environment
103  * variables. It has been tested on Windows 2000, Windows XP, Solaris, and
104  * HP-UX, though it should work with any Win32 (95+) or Unix based palatform.
105  *
106  * @author <a HREF="mailto:rjmpsmith@hotmail.com">Robert J. Smith </a>
107  */

108 public class OSEnvironment {
109
110     private static final Logger LOG = Logger.getLogger(OSEnvironment.class);
111     
112     /**
113      * Internal representation of the system environment
114      */

115     private Properties JavaDoc variables = new Properties JavaDoc();
116
117     /**
118      * Constructor
119      *
120      * Creates an instance of OSEnvironment, queries the
121      * OS to discover it's environment variables and makes
122      * them available through the getter methods
123      */

124     public OSEnvironment() {
125         parse();
126     }
127
128     /**
129      * Parses the OS environment and makes the environment
130      * variables available through the getter methods
131      */

132     private void parse() {
133
134         String JavaDoc command;
135
136         // Detemine the correct command to run based on OS name
137
String JavaDoc os = System.getProperty("os.name").toLowerCase();
138         if (os.indexOf("windows 9") > -1) {
139             command = "command.com /c set";
140         } else if (
141             (os.indexOf("nt") > -1)
142                 || (os.indexOf("windows 200") > -1)
143                 || (os.indexOf("windows xp") > -1)
144                 || (os.indexOf("os/2") > -1)) {
145             command = "cmd.exe /c set";
146         } else {
147             // should work for just about any Unix variant
148
command = "env";
149         }
150
151         //Get our environment
152
try {
153             Process JavaDoc p = Runtime.getRuntime().exec(command);
154             
155             // Capture the output of the command
156
BufferedReader JavaDoc stdoutStream = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(
157                     p.getInputStream()));
158             BufferedReader JavaDoc stderrStream = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(
159                     p.getErrorStream()));
160
161             // Parse the output
162
String JavaDoc line;
163             String JavaDoc key = null;
164             while ((line = stdoutStream.readLine()) != null) {
165                 int idx = line.indexOf('=');
166                 String JavaDoc value;
167                 if (idx == -1) {
168                      if (key == null) {
169                          continue;
170                      }
171                      // potential multi-line property. Let's rebuild it
172
value = variables.getProperty(key);
173                      value += "\n" + line;
174                 } else {
175                   key = line.substring(0, idx);
176                   value = line.substring(idx + 1);
177                 }
178                 variables.setProperty(key, value);
179             }
180             
181             // Close down our streams
182
stdoutStream.close();
183             stderrStream.close();
184             
185         } catch (Exception JavaDoc e) {
186             LOG.error("Failed to parse the OS environment.", e);
187         }
188     }
189
190
191     /**
192      * Gets the value of an environment variable. The variable
193      * name is case sensitive.
194      *
195      * @param variable The variable for which you wish the value
196      *
197      * @return The value of the variable, or <code>null</code>
198      * if not found
199      *
200      * @see #getVariable(String variable, String defaultValue)
201      */

202     public String JavaDoc getVariable(String JavaDoc variable) {
203         return variables.getProperty(variable);
204     }
205
206
207     /**
208      * Gets the value of an environment variable. The variable
209      * name is case sensitive.
210      *
211      * @param variable the variable for which you wish the value
212      *
213      * @param defaultValue The value to return if the variable is not set in the environment.
214      *
215      * @return The value of the variable. If the variable is not
216      * found, the defaultValue is returned.
217      */

218     public String JavaDoc getVariable(String JavaDoc variable, String JavaDoc defaultValue) {
219         return variables.getProperty(variable, defaultValue);
220     }
221
222
223     /**
224      * Gets the value of an environment variable. The variable
225      * name is NOT case sensitive. If more than one variable
226      * matches the pattern provided, the result is unpredictable.
227      * You are greatly encouraged to use <code>getVariable()</code>
228      * instead.
229      *
230      * @param variable the variable for which you wish the value
231      *
232      * @see #getVariable(String variable)
233      * @see #getVariable(String variable, String defaultValue)
234      */

235     public String JavaDoc getVariableIgnoreCase(String JavaDoc variable) {
236         Enumeration JavaDoc keys = variables.keys();
237         while (keys.hasMoreElements()) {
238             String JavaDoc key = (String JavaDoc) keys.nextElement();
239             if (key.equalsIgnoreCase(variable)) {
240                 return variables.getProperty(key);
241             }
242         }
243         return null;
244     }
245
246
247     /**
248      * Adds a variable to this representation of the
249      * environment. If the variable already existed, the
250      * value will be replaced.
251      *
252      * @param variable the variable to set
253      * @param value the value of the variable
254      */

255     public void add(String JavaDoc variable, String JavaDoc value) {
256         variables.setProperty(variable, value);
257     }
258
259     
260     /**
261      * Returns all environment variables which were set at
262      * the time the class was instantiated, as well as any
263      * which have been added programatically.
264      *
265      * @return a <code>List</code> of all environment variables.
266      * The <code>List</code> is made up of <code>String</code>s
267      * of the form "variable=value".
268      *
269      * @see #toArray()
270      */

271     public List JavaDoc getEnvironment() {
272         List JavaDoc env = new ArrayList JavaDoc();
273         Enumeration JavaDoc keys = variables.keys();
274         while (keys.hasMoreElements()) {
275             String JavaDoc key = (String JavaDoc) keys.nextElement();
276             env.add(key + "=" + variables.getProperty(key));
277         }
278         return env;
279     }
280
281     /**
282      * Returns all environment variables which were set at
283      * the time the class was instantiated, as well as any
284      * which have been added programatically.
285      *
286      * @return a <code>String[]</code> containing all
287      * environment variables. The <code>String</code>s
288      * are of the form "variable=value". This is the
289      * format expected by <code>java.lang.Runtime.exec()</code>.
290      *
291      * @see java.lang.Runtime
292      */

293     public String JavaDoc[] toArray() {
294         List JavaDoc list = getEnvironment();
295         return (String JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
296     }
297
298
299     /**
300      * Returns a <code>String<code> representation of the
301      * environment.
302      *
303      * @return A <code>String<code> representation of the environment
304      */

305     public String JavaDoc toString() {
306         return variables.toString();
307     }
308 }
309
Popular Tags