01: /*
02: * MCS Media Computer Software Copyright (c) 2005 by MCS
03: * -------------------------------------- Created on 16.01.2004 by w.klaas
04: *
05: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
06: * use this file except in compliance with the License. You may obtain a copy of
07: * the License at
08: *
09: * 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, WITHOUT
13: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14: * License for the specific language governing permissions and limitations under
15: * the License.
16: */
17: package de.mcs.utils;
18:
19: import java.io.BufferedReader;
20: import java.io.IOException;
21: import java.io.InputStreamReader;
22: import java.util.HashMap;
23:
24: /**
25: * Environment class simulates the System.getenv() method which is deprecated on
26: * java 1.4.2.
27: *
28: * @author v-josp
29: */
30: public final class GetEnviroment {
31: /** prevent instancing. */
32: private GetEnviroment() {
33: }
34:
35: /** result of all enviornment variables. */
36: private static BufferedReader commandResult;
37:
38: /** map with all commands. */
39: private static HashMap<String, String> commandList;
40: static {
41: String cmd = null;
42: String os = null;
43:
44: // getting the OS name
45: os = System.getProperty("os.name").toLowerCase();
46:
47: // according to OS set the command to execute
48: if (os.startsWith("windows")) {
49: cmd = "cmd /c SET";
50: } else {
51: cmd = "env";
52: }
53:
54: try {
55: // execute the command and get the result in the form of InputStream
56: Process p = Runtime.getRuntime().exec(cmd);
57:
58: // parse the InputStream data
59: InputStreamReader isr = new InputStreamReader(p
60: .getInputStream());
61: commandResult = new BufferedReader(isr);
62: } catch (Exception e) {
63: System.out.println("OSEnvironment.class error: " + cmd
64: + ":" + e);
65: }
66: commandList = new HashMap<String, String>();
67:
68: String line = null;
69: try {
70: while ((line = commandResult.readLine()) != null) {
71: String key = line.substring(0, line.indexOf('='));
72: String value = line.substring(line.indexOf('=') + 1);
73: commandList.put(key, value);
74: }
75: } catch (IOException e) {
76: e.printStackTrace();
77: }
78: }
79:
80: /**
81: * This method is used to get the path of the given enviornment variable.
82: * This method tries to simulates the System.getenv() which is deprecated on
83: * java 1.4.2
84: *
85: * @param envName
86: * name of the environment variable
87: * @param defaultValue
88: * default value
89: * @return String
90: */
91: public static String getenv(final String envName,
92: final String defaultValue) {
93: String value = defaultValue;
94: if (commandList.containsKey(envName)) {
95: value = (String) commandList.get(envName);
96: }
97: return value;
98: }
99: }
|