KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jahia > opentools > advancedapprunner > SysEnvPropertiesProvider


1 /* ==========================================================================
2  * Copyright 2003-2004 Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  * =========================================================================
16  */

17 package com.jahia.opentools.advancedapprunner;
18
19 import java.io.BufferedReader JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.InputStreamReader JavaDoc;
22 import java.util.Properties JavaDoc;
23 import java.util.ArrayList JavaDoc;
24 import java.util.Iterator JavaDoc;
25
26 /**
27  * Default implementation of SysEnvProvider, will execute an external process and
28  * get the system environment variables. Is operating system dependent.
29  * @author Milos Kleint
30  * @author Serge Huber
31  */

32 public class SysEnvPropertiesProvider {
33
34     private Properties JavaDoc envProperties;
35
36     private boolean loaded;
37     private Object JavaDoc LOCK = new Object JavaDoc();
38     private static SysEnvPropertiesProvider singletonInstance = null;
39
40     private SysEnvPropertiesProvider() {
41         loaded = false;
42     }
43
44     public static SysEnvPropertiesProvider getInstance() {
45         if (singletonInstance == null) {
46             singletonInstance = new SysEnvPropertiesProvider();
47         }
48         return singletonInstance;
49     }
50
51     private void loadEnvironment() {
52         try {
53             envProperties = getEnvVars();
54         } catch (Exception JavaDoc exc) {
55             envProperties = new Properties JavaDoc();
56         }
57     }
58
59     public String JavaDoc getProperty(String JavaDoc name) {
60         checkLoaded();
61         return envProperties.getProperty(name);
62     }
63
64     public void setProperty(String JavaDoc name, String JavaDoc value) {
65         checkLoaded();
66         envProperties.setProperty(name, value);
67     }
68
69     private void checkLoaded() {
70         if (!loaded) {
71             synchronized (LOCK) {
72                 if (!loaded) {
73                     loadEnvironment();
74                     loaded = true;
75                 }
76             }
77         }
78     }
79
80     /**
81      * Matches the longest property that starts at the beginning of the input
82      * string. This is used to lookup properties in the environment, as the
83      * syntax of property names can be anything. Basically what this method
84      * does is iterate through all properties, by matching with increasing
85      * length of a substring of the input string, until only one (or zero)
86      * matches are found.
87      * For example if the input string looks like this :
88      * JAVA_HOME/bin/bootstrap.jar
89      * This will match the following environment property :
90      * JAVA_HOME or JAVA_HOME/bin or JAVA_HOME/b
91      * but this will NOT match :
92      * JAVA_HOME_ENV
93      * JAVAHOME
94      *
95      * @param input String the input string that we will match the beginning
96      * of against a property in the environment
97      * @return String the found environment property name, or null if none
98      * was found.
99      */

100     public String JavaDoc matchLongestProperty(String JavaDoc input) {
101         if (input == null) {
102             return null;
103         }
104         checkLoaded();
105         if (envProperties.size() == 0) {
106             return null;
107         }
108         if (envProperties.size() == 1) {
109             String JavaDoc singleProperty = (String JavaDoc) envProperties.keySet().iterator().next();
110             if (input.indexOf(singleProperty) != -1) {
111                 return singleProperty;
112             } else {
113                 return null;
114             }
115         }
116         ArrayList JavaDoc matchCandidates = new ArrayList JavaDoc(envProperties.keySet());
117         int curLen = 1;
118         while (matchCandidates.size() > 1) {
119             String JavaDoc partialInput = input.substring(0, curLen);
120             Iterator JavaDoc candidatesIter = matchCandidates.iterator();
121             ArrayList JavaDoc newCandidates = new ArrayList JavaDoc();
122             while (candidatesIter.hasNext()) {
123                 String JavaDoc curCandidateName = (String JavaDoc) candidatesIter.next();
124                 if (curCandidateName.startsWith(partialInput)) {
125                     newCandidates.add(curCandidateName);
126                 }
127             }
128             matchCandidates = newCandidates;
129             curLen++;
130         }
131         if (matchCandidates.size() == 0) {
132             return null;
133         }
134         return (String JavaDoc) matchCandidates.get(0);
135     }
136
137     /**
138      * Given an input string containing environment variable references in the
139      * form : $ENV_VARIABLE_NAME, it will replace the references with the
140      * corresponding environment variable value if it exists. If it cannot
141      * find the environment variable, the reference is not replaced, and the
142      * string is inserted as such.
143      * @param input String the input String containing the variable references
144      * that we want to be replaced with the environment variable values
145      * @return String the result string
146      */

147     public String JavaDoc replaceEnvVariables(String JavaDoc input) {
148         int curPos = 0;
149         String JavaDoc result = new String JavaDoc(input);
150         int envStartPos = result.indexOf("$", curPos);
151         while (envStartPos != -1) {
152             curPos = envStartPos;
153             // found environment variable markers, let's replace them if
154
// we can find them in the current environment.
155
String JavaDoc propertyName = matchLongestProperty(result.substring(envStartPos+1));
156             if (propertyName != null) {
157                 String JavaDoc leftOfProperty = result.substring(0, envStartPos);
158                 String JavaDoc rightOfProperty = result.substring(envStartPos +
159                     1 + propertyName.length());
160                 result = leftOfProperty + getProperty(propertyName) + rightOfProperty;
161             } else {
162                 curPos++;
163             }
164
165             // let's look for the next marker
166
envStartPos = result.indexOf("$", curPos);
167         }
168         return result;
169     }
170
171
172     private static Properties JavaDoc getEnvVars() throws IOException JavaDoc {
173         Process JavaDoc p = null;
174         Properties JavaDoc envVars = new Properties JavaDoc();
175         Runtime JavaDoc r = Runtime.getRuntime();
176         String JavaDoc os = System.getProperty("os.name").toLowerCase();
177         // System.out.println(OS);
178
if (os.indexOf("windows") > -1) {
179             if (os.indexOf("windows 9") > -1) {
180                 // old Win9X stuff..
181
p = r.exec("command.com /c set");
182             } else {
183                 // for everything else (XP, 2000, NT
184
p = r.exec("cmd.exe /c set");
185             }
186         } else {
187             // let's assume what is not windows is unix..
188
p = r.exec("sh -l -c env");
189         }
190         BufferedReader JavaDoc br = new BufferedReader JavaDoc
191             (new InputStreamReader JavaDoc(p.getInputStream()));
192         String JavaDoc line;
193         while ( (line = br.readLine()) != null) {
194             int idx = line.indexOf('=');
195             if (idx > 0) {
196                 String JavaDoc key = line.substring(0, idx);
197                 String JavaDoc value = line.substring(idx + 1);
198                 envVars.setProperty(key, value);
199             } else {
200                 //what now? wrong line format?
201
}
202         }
203         return envVars;
204     }
205 }
206
Popular Tags