/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

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