PageRenderTime 20ms CodeModel.GetById 1ms app.highlight 13ms RepoModel.GetById 2ms app.codeStats 0ms

/src/org/ooc/utils/ReadEnv.java

http://github.com/nddrylliog/ooc
Java | 71 lines | 42 code | 10 blank | 19 comment | 12 complexity | 3e20b33605f5a78989eaa3eb2851e1b8 MD5 | raw file
 1package org.ooc.utils;
 2
 3import java.io.BufferedReader;
 4import java.io.IOException;
 5import java.io.InputStreamReader;
 6import java.util.HashMap;
 7import java.util.Map;
 8
 9/**
10 * Utility class to read environment variables even under GCJ/GNU classpath
11 * The System.getenv() method has been deprecated in Java 1.4 and reinstated
12 * in 1.5, but apparently 
13 * 
14 * Taken from http://www.rgagnon.com/javadetails/java-0150.html
15 * 
16 * @author Amos Wenger
17 */
18public class ReadEnv {
19
20	/**
21	 * @return a property object containing all the environment variables
22	 * @throws IOException 
23	 * @throws Throwable
24	 */
25	public static Map<String, String> getEnv() {
26		
27		Map<String, String> getenv = System.getenv();
28		if(!getenv.isEmpty()) return getenv;
29		
30		Process p = null;
31		Map<String, String> envVars = new HashMap<String, String>();
32		Runtime r = Runtime.getRuntime();
33		String OS = System.getProperty("os.name").toLowerCase();
34		
35		try {
36		
37		//System.out.println("OS: "+OS);
38		if (OS.indexOf("windows 9") > -1) {
39			p = r.exec("command.com /c set");
40		} else if ((OS.indexOf("nt") > -1) || (OS.indexOf("windows 20") > -1)
41				|| (OS.indexOf("windows xp") > -1)) {
42			// thanks to JuanFran for the xp fix!
43			p = r.exec("cmd.exe /c set");
44		} else {
45			// our last hope, we assume Unix (thanks to H. Ware for the fix)
46			p = r.exec("env");
47		}
48		BufferedReader br = new BufferedReader(new InputStreamReader(p
49				.getInputStream()));
50		String line;
51		while ((line = br.readLine()) != null) {
52			int idx = line.indexOf('=');
53			if(idx != -1) {
54				String key = line.substring(0, idx);
55				String value = line.substring(idx + 1);
56				envVars.put(key, value);
57				//System.out.println( key + " = " + value );
58			} else {
59				//System.out.println("While trying to get environment variables, got: " + line + "\n");
60			}
61		}
62		br.close();
63		
64		} catch(IOException e) {
65			e.printStackTrace();
66		}
67		
68		return envVars;
69	}
70
71}