KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ca > commons > cbutil > CBSystemProperties


1 package com.ca.commons.cbutil;
2
3 import java.io.*;
4 import java.util.Enumeration JavaDoc;
5 import java.util.logging.*;
6
7 /**
8  * <p>Sun, in their fairly limited wisdom, decided to disable
9  * the ability to get system environment variables in java.
10  * (Apart from a couple that they kindly decided to let through
11  * that are fairly useless). Apparently it wasn't platform
12  * independent enough, and might have screwed up their revenue
13  * stream. Or something.</p>
14  * <p/>
15  * <p>Anyway, this class contains a filthy hack to get the
16  * information anyway, come hell, Sun, or high water.
17  * basically it shells a 'set' command, and attempts to do
18  * this on both unix and windows.</p>
19  * <p/>
20  * <p>This is needed by some JX plugins, that rely on user-set system
21  * environment variables to do stuff.</p>
22  */

23
24 public class CBSystemProperties
25 {
26     private static Logger log = Logger.getLogger(CBSystemProperties.class.getName());
27
28     /**
29      * A simple minded test to see if we are running on a windows machine.
30      *
31      * @return true if on windows, false if not.
32      */

33
34     public static boolean isWindows()
35     {
36         String JavaDoc os = System.getProperty("os.name");
37         if (os != null && os.toLowerCase().indexOf("windows") > -1)
38         {
39             log.fine("this is a windows machine.");
40             return true;
41         }
42
43         log.fine("this is a unix machine.");
44         return false;
45     }
46
47
48     /**
49      * This writes a file called 'runset.bat' (or 'runset.sh' on unix)
50      * that can then be 'exec'-ed to read the system property list.
51      *
52      * @param batchFileName - the name of the batch file to create, e.g. 'runset.bat' or 'runset.sh'
53      */

54
55     private static void writeBatchFile(String JavaDoc batchFileName)
56             throws IOException
57     {
58         File setBatch = new File(batchFileName);
59         
60         // only write the batch file once.
61
if (setBatch.exists() == false)
62         {
63             FileWriter out = new FileWriter(setBatch);
64             out.write("set", 0, 3);
65             out.flush();
66             out.close();
67         }
68     }
69
70     /**
71      * Cleans up - deletes the batch file afterwards...
72      *
73      * @param batchFileName - the name of the batch file to delete, e.g. 'runset.bat' or 'runset.sh'
74      */

75
76     private static void deleteBatchFile(String JavaDoc batchFileName)
77     {
78         File setBatch = new File(batchFileName);
79         
80         // nb. - catch exception locally, since this is not
81
// fatal; if everything else has worked we probably
82
// don't care if we can't clean up.
83
try
84         {
85             setBatch.delete();
86         }
87         catch (Exception JavaDoc e)
88         {
89             log.log(Level.WARNING, "unable to delete batch file " + batchFileName, e);
90         }
91     }
92
93     /**
94      * This takes the batch file generated by writeBatchFile() and
95      * exec()s it to read the system dependent list of properties.
96      * (which is then added to the java system properties list...)
97      *
98      * @param batchFileName - the name of the batch file to use, e.g. 'runset.bat' or 'runset.sh'
99      */

100
101     private static void readSystemProperties(String JavaDoc batchFileName)
102             throws IOException
103     {
104         // use the batch file...
105
Process JavaDoc bloop = Runtime.getRuntime().exec(batchFileName);
106
107         BufferedReader input = new BufferedReader(new InputStreamReader(bloop.getInputStream()));
108         BufferedReader errors = new BufferedReader(new InputStreamReader(bloop.getErrorStream()));
109         
110         // run through the batch file, spliting names and value on the '=' sign
111
// (e.g DXHOME=c:\dxserver => DXHOME and 'c:\dxserver' )
112

113         String JavaDoc line = "";
114
115         log.fine("reading output from batch file");
116
117         setSystemPropertiesFromBufferedReader(input);
118
119         while ((line = errors.readLine()) != null)
120         {
121             System.out.println("ERRORS: " + line);
122         }
123
124
125     }
126
127     private static void setSystemPropertiesFromBufferedReader(BufferedReader input) throws IOException
128     {
129         String JavaDoc line;
130         int pos;
131         String JavaDoc name;
132         String JavaDoc value;
133         while ((line = input.readLine()) != null)
134         {
135             log.finest("read raw line: " + line);
136
137             if ((pos = line.indexOf('=')) > 0)
138             {
139                 name = line.substring(0, pos);
140                 if (line.length() > pos)
141                     value = line.substring(pos + 1).trim();
142                 else
143                     value = "";
144
145
146                 if (System.getProperty(name) == null)
147                 {
148                     System.setProperty(name, value);
149                     log.fine("SET setting property '" + name + "' equal '" + value + "'");
150                 }
151                 else
152                     log.fine("skipping existing value for: " + name);
153
154             }
155         }
156     }
157
158     /**
159      * for debugging - dumps the full system properties list at level 'fine' or better...
160      */

161
162     // XXX can't figure out how to get the active level from Sun's logging library - so
163
// XXX we gather all the data before knowing if we want to log it. *pffft*.
164
private static void dumpProperties()
165     {
166
167         Enumeration JavaDoc keys = System.getProperties().propertyNames();
168         while (keys.hasMoreElements())
169         {
170             String JavaDoc key = (String JavaDoc) keys.nextElement();
171             log.fine("SYSPROPS: " + key + " : " + System.getProperty(key));
172         }
173     }
174
175     /**
176      * This method relies on the system properties having been pre-written to
177      * a particular file (in the normal 'property=value' format used by both
178      * java properties files, and the results of 'set' on unix and windows).
179      * If it fails to find this property file, it will revert to trying to
180      * automatically run 'set' using the other 'loadSystemProperties()'
181      * method below.
182      */

183     public static boolean loadSystemProperties(File propertiesListFile)
184     {
185         if (propertiesListFile.exists() == false)
186         {
187             log.warning("Unable to find system properties file: '" + propertiesListFile.toString() + "' - attempting batch load instead");
188             return loadSystemProperties();
189         }
190
191         try
192         {
193             setSystemPropertiesFromBufferedReader(new BufferedReader(new FileReader(propertiesListFile)));
194             dumpProperties();
195
196             return true;
197         }
198         catch (IOException e)
199         {
200             log.log(Level.WARNING, "Error trying to load system properties file '" + propertiesListFile.toString() + "' - - attempting batch load instead.", e);
201             return loadSystemProperties();
202         }
203     }
204
205     /**
206      * This method reads the system environment property list,
207      * and adds them directly to the System.getProperties()
208      * global property list.
209      *
210      * @return whether the operation was successfull, or
211      * whether an error (usually an IOException) occurred.
212      */

213
214     public static boolean loadSystemProperties()
215     {
216         try
217         {
218             // get a batch (or shell) script name
219
// nb - don't call it 'set.bat' -> fails on nt!
220
String JavaDoc batchFileName = isWindows() ? "runset.bat" : "runset.sh";
221             
222             
223             // write it out with the single command 'set' inside...
224
writeBatchFile(batchFileName);
225             
226             // execute it, to read the system properties, and append
227
// them to the global system list...
228
readSystemProperties(batchFileName);
229     
230             // for debugging, dump the list of read properties...
231
dumpProperties();
232                 
233             // cleanup - delete the file...
234
deleteBatchFile(batchFileName);
235
236             return true;
237         }
238         catch (Exception JavaDoc e)
239         {
240             log.log(Level.SEVERE, "Error reading system properties...\n", e);
241             // In this case calling programs should either make
242
// inspired guesses, or prompt users for missing values.
243

244             return false;
245         }
246     }
247
248     /**
249      * Main method for stand alone testing.
250      *
251      * @param argsv - not used.
252      */

253
254     public static void main(String JavaDoc argsv[])
255     {
256         log.addHandler(new ConsoleHandler());
257         log.setLevel(Level.FINEST);
258         log.fine("CBSystemProperties log active");
259
260         loadSystemProperties();
261     }
262
263 }
Popular Tags