KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jruby > environment > OSEnvironment


1 /***** BEGIN LICENSE BLOCK *****
2  * Version: CPL 1.0/GPL 2.0/LGPL 2.1
3  *
4  * The contents of this file are subject to the Common Public
5  * License Version 1.0 (the "License"); you may not use this file
6  * except in compliance with the License. You may obtain a copy of
7  * the License at http://www.eclipse.org/legal/cpl-v10.html
8  *
9  * Software distributed under the License is distributed on an "AS
10  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
11  * implied. See the License for the specific language governing
12  * rights and limitations under the License.
13  *
14  * Copyright (C) 2006 Tim Azzopardi <tim@tigerfive.com>
15  *
16  * Alternatively, the contents of this file may be used under the terms of
17  * either of the GNU General Public License Version 2 or later (the "GPL"),
18  * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
19  * in which case the provisions of the GPL or the LGPL are applicable instead
20  * of those above. If you wish to allow use of your version of this file only
21  * under the terms of either the GPL or the LGPL, and not to allow others to
22  * use your version of this file under the terms of the CPL, indicate your
23  * decision by deleting the provisions above and replace them with the notice
24  * and other provisions required by the GPL or the LGPL. If you do not delete
25  * the provisions above, a recipient may use your version of this file under
26  * the terms of any one of the CPL, the GPL or the LGPL.
27  ***** END LICENSE BLOCK *****/

28
29 package org.jruby.environment;
30
31 import java.io.BufferedReader JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.security.AccessControlException JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.Set JavaDoc;
38
39 import org.jruby.Ruby;
40
41 public class OSEnvironment {
42
43
44     /**
45      * Handles exceptions from implementors of {@link IOSEnvironmentReader},
46      * converting the exception to a {@link OSEnvironmentReaderExcepton}
47      * @param e
48      */

49     void handleException(Exception JavaDoc e) {
50         throw (OSEnvironmentReaderExcepton)
51             new OSEnvironmentReaderExcepton().initCause(e);
52     }
53
54     /**
55     * Returns the OS environment variables as a Map<RubyString,RubyString>.
56     * If the Java system property "jruby.env.method" is set then
57     * the value is used as the classname of a class than implements the IOSEnvironmentReader
58     * interface and the environment is obtained via this class.
59     * If the "jruby.env.method" is "org.jruby.environment.OSEnvironmentReaderFromFile" then
60     * the java system property "jruby.envfile" should give the location of a file from which
61     * the environment variables can be loaded.
62     * Otherwise, other default implementations of IOSEnvironmentReader are tried
63     * to obtain the os environment variables.
64     * @param runtime
65     * @param System.getProperty("jruby.env.method")
66     * @throws OSEnvironmentReaderExcepton
67     */

68     public Map JavaDoc getEnvironmentVariableMap(Ruby runtime) {
69         Map JavaDoc envs = null;
70
71         if (runtime.getInstanceConfig().getEnvironment() != null) {
72             return getAsMapOfRubyStrings(runtime, runtime.getInstanceConfig().getEnvironment().entrySet());
73         }
74
75         // try/catch to fall back on empty env when security disallows environment var access (like in an applet)
76
try {
77             String JavaDoc jrubyEnvMethod = System.getProperty("jruby.env.method");
78
79             IOSEnvironmentReader reader;
80
81             if (jrubyEnvMethod == null || jrubyEnvMethod.length() < 1) {
82                 // Try to get environment from Java5 System.getenv()
83
reader = getAccessibleOSEnvironment(runtime, OSEnvironmentReaderFromJava5SystemGetenv.class.getName());
84                 // not Java5 so try getting environment using Runtime exec
85
if (reader == null) {
86                     reader = getAccessibleOSEnvironment(runtime, OSEnvironmentReaderFromRuntimeExec.class.getName());
87                     //runtime.getWarnings().warn("Getting environment variables using Runtime Exec");
88
} else {
89                     //runtime.getWarnings().warn("Getting environment variables using Java5 System.getenv()");
90
}
91             } else {
92                 // get environment from jruby command line property supplied class
93
runtime.getWarnings().warn("Getting environment variables using command line defined method: " + jrubyEnvMethod);
94                 reader = getAccessibleOSEnvironment(runtime, jrubyEnvMethod);
95             }
96
97             envs = null;
98             if (reader != null) {
99                 Map JavaDoc variables = null;
100                 variables = reader.getVariables(runtime);
101                 envs = getAsMapOfRubyStrings(runtime, variables.entrySet());
102             }
103         } catch (AccessControlException JavaDoc accessEx) {
104             // default to empty env
105
envs = new HashMap JavaDoc();
106         }
107
108         return envs;
109
110     }
111
112     /**
113     * Returns java system properties as a Map<RubyString,RubyString>.
114      * @param runtime
115      * @return the java system properties as a Map<RubyString,RubyString>.
116      */

117     public Map JavaDoc getSystemPropertiesMap(Ruby runtime) {
118         try {
119             return getAsMapOfRubyStrings(runtime, System.getProperties().entrySet());
120         } catch (AccessControlException JavaDoc accessEx) {
121             // default to empty env
122
return new HashMap JavaDoc();
123         }
124     }
125
126
127     private static IOSEnvironmentReader getAccessibleOSEnvironment(Ruby runtime, String JavaDoc classname) {
128         IOSEnvironmentReader osenvironment = null;
129         try {
130             osenvironment = (IOSEnvironmentReader)Class.forName(classname).newInstance();
131         } catch (Exception JavaDoc e) {
132             // This should only happen for a command line supplied IOSEnvironmentReader implementation
133
runtime.getWarnings().warn(e.getMessage());
134         }
135
136         if (osenvironment != null && osenvironment.isAccessible(runtime)) {
137             return osenvironment;
138         }
139         return null;
140     }
141
142
143
144     private static Map JavaDoc getAsMapOfRubyStrings(Ruby runtime, Set JavaDoc entrySet) {
145         Map JavaDoc envs = new HashMap JavaDoc();
146         for (Iterator JavaDoc iter = entrySet.iterator(); iter.hasNext();) {
147             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iter.next();
148             envs.put(runtime.newString((String JavaDoc)entry.getKey()),runtime.newString((String JavaDoc)entry.getValue()));
149         }
150         return envs;
151     }
152
153
154     /**
155      * Returns a Map of the variables found in the reader of form var=value
156      * @param reader
157      * @return Map<String,String> of variables found by reading lines from reader.
158      */

159     Map JavaDoc getVariablesFrom(BufferedReader JavaDoc reader) {
160         Map JavaDoc envs = new HashMap JavaDoc();
161         try {
162             String JavaDoc line, envVarName, envVarValue;
163             int equalsPos;
164             while ((line = reader.readLine()) != null) {
165                 equalsPos = line.indexOf('=');
166                 if (equalsPos >= 1) {
167                     envVarName = line.substring(0, equalsPos);
168                     envVarValue = line.substring(equalsPos + 1);
169                     envs.put(envVarName, envVarValue);
170                 }
171             }
172         } catch (IOException JavaDoc e) {
173             envs = null;
174             handleException(e);
175         } finally {
176             try {
177                 reader.close();
178             } catch (IOException JavaDoc e) {
179                 envs = null;
180                 handleException(e);
181             }
182         }
183         return envs;
184     }
185
186
187 }
188
Popular Tags