KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > values > types > EnvironmentType


1 /*
2  * (c) Rob Gordon 2005
3  */

4 package org.oddjob.values.types;
5
6
7 import java.io.BufferedReader JavaDoc;
8 import java.io.ByteArrayInputStream JavaDoc;
9 import java.io.ByteArrayOutputStream JavaDoc;
10 import java.io.IOException JavaDoc;
11 import java.io.InputStream JavaDoc;
12 import java.io.InputStreamReader JavaDoc;
13 import java.util.ArrayList JavaDoc;
14 import java.util.Collection JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import java.util.Iterator JavaDoc;
17 import java.util.List JavaDoc;
18 import java.util.Map JavaDoc;
19 import java.util.Set JavaDoc;
20
21 import org.apache.log4j.Logger;
22 import org.oddjob.jobs.ExecJob;
23 import org.oddjob.util.OddjobConfigException;
24
25 /**
26  * Capture this processes environment variables. This Type implements
27  * a map so that it can be merged into VariablesJob which otherwise
28  * wouldn't call valueFor because Constants.RTC_LEAVE_PROXY is set in
29  * the ArooaXMLContext during processing.
30  *
31  * @oddjob.description Capture an environment variable or
32  * all environment variables.
33  * <p>
34  * If no name is specified, this type can be used where ever a {@link MapType}
35  * can be used.
36  * <p>
37  * If a name is specified, this type behaves like a simple {@link ValueType}
38  *
39  * @oddjob.example
40  *
41  * Use environement to append the existing environment to an additional
42  * environment variable.
43  *
44  * <pre>
45  * &lt;exec command="env"&gt;
46  * &lt;environment&gt;
47  * &lt;value name="FRUIT" value="apple"/&gt;
48  * &lt;environment command="env"/>
49  * &lt;/variables&gt;
50  * &lt;environment/&gt;
51  * &lt;/exec&gt;
52  * </pre>
53  *
54  * @oddjob.example
55  *
56  * <pre>
57  * &lt;sequential&gt;
58  * &lt;variables id="vars"&gt;
59  * &lt;environment name="FRUIT" command="env"/>
60  * &lt;/variables&gt;
61  * &lt;echo text="Todays fruit is ${vars.FRUIT}"/&gt;
62  * &lt;/sequential&gt;
63  *</pre>
64  *
65  * </pre>
66  *
67  */

68 public class EnvironmentType implements Map JavaDoc {
69     private static final Logger logger = Logger.getLogger(EnvironmentType.class);
70
71     private static Map JavaDoc procEnvironment;
72     
73     private Map JavaDoc map;
74
75     /**
76      * @oddjob.property
77      * @oddjob.description The operating system specific command for returning
78      * an environment.
79      * @oddjob.required Yes.
80      */

81     private transient String JavaDoc command;
82     
83     /**
84      * @oddjob.property
85      * @oddjob.description The name of the environement varable.
86      * @oddjob.required No, if not supplied then all are returned.
87      */

88     private transient String JavaDoc name;
89         
90     /**
91      * The command used to get the environemnt, such as "cmd /c set" on windows
92      * or "env" on Linux.
93      *
94      * @param command
95      */

96     public void setCommand(String JavaDoc command) {
97         this.command = command;
98     }
99     
100     public void setName(String JavaDoc name) {
101         this.name = name;
102     }
103     
104     public Object JavaDoc valueFor(Class JavaDoc required) {
105         load();
106         if (name != null) {
107             return map.get(name);
108         }
109         return map;
110     }
111     
112     /**
113      * Find the list of environment variables for this process. More ripping
114      * off of Ant.
115      *
116      * @return A map of environment variables.
117      */

118     private synchronized void load() {
119         if (map != null) {
120             return;
121         }
122         if (procEnvironment != null) {
123             map = procEnvironment;
124             return;
125         }
126         if (command == null) {
127             throw new OddjobConfigException("A command property must be set to get the environment.");
128         }
129         ByteArrayOutputStream JavaDoc out = new ByteArrayOutputStream JavaDoc();
130         ExecJob exe = new ExecJob();
131         exe.setCommand(command);
132         exe.setStdout(out);
133         logger.debug("Getting environment...");
134         exe.run();
135         try {
136             procEnvironment = process(
137                 new ByteArrayInputStream JavaDoc(out.toString().getBytes()));
138         } catch (Exception JavaDoc exc) {
139             logger.warn("Failed parsing envionment [\n" +
140                 out.toString() + "]", exc);
141             // Just try to see how much we got
142
}
143         map = procEnvironment;
144         logger.debug("Loaded environment:\n" + MapType.propertiesFrom(map));
145     }
146
147     /**
148      * Process an InputStream of envionment output into a map.
149      *
150      * @param is The InputStream.
151      * @return The map.
152      *
153      * @throws IOException If reading the InputStream fails.
154      */

155     Map JavaDoc process(InputStream JavaDoc is ) throws IOException JavaDoc {
156         Map JavaDoc env = new HashMap JavaDoc();
157         BufferedReader JavaDoc in =
158             new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
159
160         String JavaDoc var = null;
161         String JavaDoc line, lineSep = System.getProperty("line.separator");
162         
163         List JavaDoc procEnvironment = new ArrayList JavaDoc();
164         while ((line = in.readLine()) != null) {
165             if (line.indexOf('=') == -1) {
166                 // Chunk part of previous env var (UNIX env vars can
167
// contain embedded new lines).
168
if (var == null) {
169                     var = lineSep + line;
170                 } else {
171                     var += lineSep + line;
172                 }
173             } else {
174                 // New env var...append the previous one if we have it.
175
if (var != null) {
176                     procEnvironment.add(var);
177                 }
178                 var = line;
179             }
180         }
181         // Since we "look ahead" before adding, there's one last env var.
182
if (var != null) {
183             procEnvironment.add(var);
184         }
185         
186         for (Iterator JavaDoc it = procEnvironment.iterator(); it.hasNext(); ) {
187             String JavaDoc entry = (String JavaDoc) it.next();
188             int pos = entry.indexOf('=');
189             if (pos == -1) {
190                 logger.warn("Ignoring: " + entry);
191             } else {
192                 env.put(entry.substring(0, pos),
193                         entry.substring(pos + 1));
194             }
195         }
196         
197         return env;
198     }
199         
200     /* (non-Javadoc)
201      * @see java.util.Map#clear()
202      */

203     public void clear() {
204         throw new UnsupportedOperationException JavaDoc("This map is read only!");
205     }
206
207     /* (non-Javadoc)
208      * @see java.util.Map#containsKey(java.lang.Object)
209      */

210     public boolean containsKey(Object JavaDoc key) {
211         load();
212         return map.containsKey(key);
213     }
214     
215     /* (non-Javadoc)
216      * @see java.util.Map#containsValue(java.lang.Object)
217      */

218     public boolean containsValue(Object JavaDoc value) {
219         load();
220         return map.containsValue(value);
221     }
222     
223     /* (non-Javadoc)
224      * @see java.util.Map#entrySet()
225      */

226     public Set JavaDoc entrySet() {
227         load();
228         return map.entrySet();
229     }
230         
231     /* (non-Javadoc)
232      * @see java.util.Map#get(java.lang.Object)
233      */

234     public Object JavaDoc get(Object JavaDoc key) {
235         load();
236         return map.get(key);
237     }
238         
239     /* (non-Javadoc)
240      * @see java.util.Map#isEmpty()
241      */

242     public boolean isEmpty() {
243         load();
244         return map.isEmpty();
245     }
246     
247     /* (non-Javadoc)
248      * @see java.util.Map#keySet()
249      */

250     public Set JavaDoc keySet() {
251         load();
252         return map.keySet();
253     }
254     
255     /* (non-Javadoc)
256      * @see java.util.Map#put(java.lang.Object, java.lang.Object)
257      */

258     public Object JavaDoc put(Object JavaDoc key, Object JavaDoc value) {
259         throw new UnsupportedOperationException JavaDoc("This map is read only!");
260     }
261     
262     /* (non-Javadoc)
263      * @see java.util.Map#putAll(java.util.Map)
264      */

265     public void putAll(Map JavaDoc t) {
266         throw new UnsupportedOperationException JavaDoc("This map is read only!");
267     }
268     
269     /* (non-Javadoc)
270      * @see java.util.Map#remove(java.lang.Object)
271      */

272     public Object JavaDoc remove(Object JavaDoc key) {
273         load();
274         return map.remove(key);
275     }
276     
277     /* (non-Javadoc)
278      * @see java.util.Map#size()
279      */

280     public int size() {
281         load();
282         return map.size();
283     }
284     
285     /* (non-Javadoc)
286      * @see java.util.Map#values()
287      */

288     public Collection JavaDoc values() {
289         load();
290         return map.values();
291     }
292     
293 }
294
Popular Tags