KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > knowgate > misc > Environment


1 /*
2   Copyright (C) 2003 Know Gate S.L. All rights reserved.
3                       C/Oņa, 107 1š2 28050 Madrid (Spain)
4
5   Redistribution and use in source and binary forms, with or without
6   modification, are permitted provided that the following conditions
7   are met:
8
9   1. Redistributions of source code must retain the above copyright
10      notice, this list of conditions and the following disclaimer.
11
12   2. The end-user documentation included with the redistribution,
13      if any, must include the following acknowledgment:
14      "This product includes software parts from hipergate
15      (http://www.hipergate.org/)."
16      Alternately, this acknowledgment may appear in the software itself,
17      if and wherever such third-party acknowledgments normally appear.
18
19   3. The name hipergate must not be used to endorse or promote products
20      derived from this software without prior written permission.
21      Products derived from this software may not be called hipergate,
22      nor may hipergate appear in their name, without prior written
23      permission.
24
25   This library is distributed in the hope that it will be useful,
26   but WITHOUT ANY WARRANTY; without even the implied warranty of
27   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
28
29   You should have received a copy of hipergate License with this code;
30   if not, visit http://www.hipergate.org or mail to info@hipergate.org
31 */

32
33 package com.knowgate.misc;
34
35 import java.io.IOException JavaDoc;
36 import java.io.InputStream JavaDoc;
37 import java.io.StringBufferInputStream JavaDoc;
38 import java.io.FileNotFoundException JavaDoc;
39 import java.io.File JavaDoc;
40 import java.io.FileInputStream JavaDoc;
41 import java.io.FileOutputStream JavaDoc;
42 import java.io.FileReader JavaDoc;
43 import java.io.FileWriter JavaDoc;
44
45 import java.lang.System JavaDoc;
46 import java.util.Properties JavaDoc;
47 import java.util.HashMap JavaDoc;
48 import java.util.Date JavaDoc;
49 import java.util.Set JavaDoc;
50 import java.text.SimpleDateFormat JavaDoc;
51
52 import com.knowgate.debug.*;
53
54 /**
55  * <p>Reads and keeps in memory properties from .cnf initialization files.</p>
56  * @author Sergio Montoro Ten
57  * @version 3.0
58  */

59
60 public class Environment {
61   public static String JavaDoc DEFAULT_PROFILES_DIR = (System.getProperty("os.name").equals("Windows XP") ? "C:\\Windows\\" : (System.getProperty("os.name").startsWith("Windows") ? "C:\\WINNT\\" : "/etc/"));
62
63   private Environment() { }
64
65   //-----------------------------------------------------------
66

67   private static String JavaDoc getEnvironmentDirectory() {
68     if (DEFAULT_PROFILES_DIR.equalsIgnoreCase("C:\\WINNT\\")) {
69       File JavaDoc oWinDir = new File JavaDoc("C:\\WINNT");
70       if (!oWinDir.exists()) {
71         oWinDir = new File JavaDoc ("C:\\WINDOWS");
72         if (oWinDir.exists()) {
73           DEFAULT_PROFILES_DIR = "C:\\WINDOWS\\";
74         }
75         else {
76           DEFAULT_PROFILES_DIR = getEnvVar("windir", getEnvVar("SystemRoot"));
77         }
78       }
79     } // fi (DEFAULT_PROFILES_DIR=="C:\WINNT"
80
return DEFAULT_PROFILES_DIR;
81   }
82
83   //-----------------------------------------------------------
84

85   private static void readEnvVars() throws java.lang.IllegalArgumentException JavaDoc {
86     envVars = new Properties JavaDoc();
87     Runtime JavaDoc oRT;
88     Process JavaDoc oPT;
89     InputStream JavaDoc oST;
90
91     final int ENV_BUFFER_SIZE = 131072;
92
93     try {
94       if (System.getProperty("os.name").startsWith("Windows")) {
95
96         if (DebugFile.trace) DebugFile.writeln ("Runtime.getRuntime()");
97
98         oRT = Runtime.getRuntime();
99
100         if (DebugFile.trace) DebugFile.writeln ("Runtime.exec(\"cmd.exe /cset\")");
101
102         oPT = oRT.exec("cmd.exe /cset");
103
104         oST = oPT.getInputStream();
105
106         byte[] byBuffer = new byte[ENV_BUFFER_SIZE];
107
108         int iReaded = oST.read (byBuffer, 0, ENV_BUFFER_SIZE);
109
110         oST.close();
111
112         oPT.destroy();
113
114         oRT = null;
115
116         // Double back slashes
117
byte[] byEnvVars = new byte[ENV_BUFFER_SIZE+4096];
118         int iEnvLength = 0;
119
120         for (int i=0; i<iReaded; i++) {
121           byEnvVars[iEnvLength++] = byBuffer[i];
122           if (92==byBuffer[i])
123             byEnvVars[iEnvLength++] = byBuffer[i];
124         } // next
125

126         byBuffer = null;
127
128         if (DebugFile.trace) DebugFile.writeln (new String JavaDoc(byEnvVars, 0, iEnvLength));
129
130         envVars.load (new StringBufferInputStream JavaDoc(new String JavaDoc(byEnvVars, 0, iEnvLength)));
131
132       }
133       else {
134
135         if (DebugFile.trace) DebugFile.writeln ("Runtime.getRuntime()");
136
137         oRT = Runtime.getRuntime();
138
139         if (DebugFile.trace) DebugFile.writeln ("Runtime.exec(\"/usr/bin/env\")");
140
141         oPT = oRT.exec("/usr/bin/env");
142
143         oST = oPT.getInputStream();
144
145         if (DebugFile.trace) DebugFile.writeln ("Properties.load(Process.getInputStream())");
146
147         envVars.load(oST);
148
149         oST.close();
150
151         oPT.destroy();
152
153         oRT = null;
154       }
155     }
156     catch (IOException JavaDoc ioe) {
157       if (DebugFile.trace) DebugFile.writeln ("Runtime.getRuntime().exec(...) IOException " + ioe.getMessage());
158     }
159     catch (NullPointerException JavaDoc npe) {
160       if (DebugFile.trace) DebugFile.writeln ("Runtime.getRuntime().exec(...) NullPointerException " + npe.getMessage());
161     }
162     finally {
163       if (null==envVars.getProperty("KNOWGATE_PROFILES")) {
164         if (DebugFile.trace) DebugFile.writeln ("KNOWGATE_PROFILES environment variable not found setting default to "+getEnvironmentDirectory());
165
166         envVars.setProperty("KNOWGATE_PROFILES", getEnvironmentDirectory());
167       }
168     }
169   } // readEnvVars
170

171   //-----------------------------------------------------------
172

173   /**
174    * <p>Get value for an environment variable.</p>
175    * This is not a Pure Java method since it uses the Runtime obeject for calling
176    * OS specific shell commands.
177    * @param sVarName Name of the variable to be readed.
178    * @return Value of variable or <b>null</b> if no environment variable with such name was found.
179    * @throws IllegalArgumentException If there is a Malformed \\uxxxx encoding or any other type of intrinsic error at the environment variables values
180    */

181
182   public static String JavaDoc getEnvVar(String JavaDoc sVarName)
183     throws IllegalArgumentException JavaDoc {
184
185     if (envVars==null) readEnvVars();
186
187     return envVars.getProperty(sVarName);
188   } // getEnvVar()
189

190   //-----------------------------------------------------------
191

192   /**
193    * <p>Get value for an environment variable.</p>
194    * This is not a Pure Java method since it uses the Runtime obeject for calling
195    * OS specific shell commands.
196    * @param sVarName Name of the variable to be readed.
197    * @return Value of variable or sDefault if no environment variable with such name was found.
198    */

199
200   public static String JavaDoc getEnvVar(String JavaDoc sVarName, String JavaDoc sDefault)
201     throws IllegalArgumentException JavaDoc {
202     if (envVars==null) readEnvVars();
203
204     String JavaDoc sRetVal = envVars.getProperty(sVarName);
205
206     if (sRetVal==null)
207       return sDefault;
208     else
209       return sRetVal;
210   } // getEnvVar()
211

212   //-----------------------------------------------------------
213

214   /**
215    * <P>Get temporary directory</P>
216    * @return For UNIX Sytems this function always return "/tmp/".<BR>
217    * For Windows Systems getTempDir() returns the value set at the environment
218    * variable "TEMP" or C:\\%WINDIR%\\TEMP\\ if TEMP variable is not set.
219    * @throws IllegalArgumentException
220    */

221   public static String JavaDoc getTempDir() throws IllegalArgumentException JavaDoc {
222     if (System.getProperty("os.name").startsWith("Windows")) {
223       String JavaDoc sTempDir = getEnvVar("TEMP");
224       if (null==sTempDir) {
225         File JavaDoc oWinDir;
226         oWinDir = new File JavaDoc("C:\\WINNT\\TEMP\\");
227         if (oWinDir.exists()) {
228           return "C:\\WINNT\\TEMP\\";
229         } else {
230           oWinDir = new File JavaDoc("C:\\WINDOWS\\TEMP\\");
231           if (oWinDir.exists()) {
232             return "C:\\WINDOWS\\TEMP\\";
233           } else {
234             return "C:\\TEMP\\";
235           }
236         }
237       } else {
238         return sTempDir;
239       }
240     } else { // Unix
241
return "/tmp/";
242     }
243   } // getTempDir()
244

245   //-----------------------------------------------------------
246

247   /**
248    * <p>Get a Properties collection from a .CNF file</p>
249    * Property files must be in the directory pointed by a operating system environment variable names
250    * <b>KNOWGATE_PROFILES</b>. If KNOWGATE_PROFILES environment variable is not found, the files will
251    * be seeked by default on C:\WINNT\ or C:\WINDOWS\ on Window Systems and /etc/ on UNIX systems.
252    * @param sProfile Properties file to read (for example "hipergate.cnf")
253    * @since v2.2 The behaviour of this function has changed: it first tries to get KNOWGATE_PROFILES
254    * from Java environment variables as set on startup "java -DKNOWGATE_PROFILES=..." if there is no
255    * Java property named KNOWGATE_PROFILES then operating system environment variabled are scanned and
256    * last if neither is found the default C:\WINNT\ C:\WINDOWS\ or /etc/ is returned
257    */

258   public static Properties JavaDoc getProfile(String JavaDoc sProfile) {
259     String JavaDoc sProfilesHome;
260     Properties JavaDoc oProfile;
261
262     if (DebugFile.trace) DebugFile.writeln("Begin Environment.getProfile()");
263
264     oProfile = (Properties JavaDoc ) profiles.get(sProfile);
265
266     if (oProfile==null) {
267
268       try {
269         sProfilesHome = System.getProperty("KNOWGATE_PROFILES", getEnvVar("KNOWGATE_PROFILES"));
270       }
271       catch (java.lang.IllegalArgumentException JavaDoc iae) {
272         sProfilesHome = getEnvironmentDirectory();
273
274         if (DebugFile.trace) DebugFile.writeln("Environment.getEnvVar(KNOWGATE_PROFILES) IllegalArgumentException " + iae.getMessage());
275       }
276
277       if (DebugFile.trace) DebugFile.writeln(" KNOWGATE_PROFILES=" + sProfilesHome);
278
279       if (!sProfilesHome.endsWith(System.getProperty("file.separator")))
280         sProfilesHome += System.getProperty("file.separator");
281
282       oProfile = loadProfile(sProfile, sProfilesHome + (sProfile.endsWith(".cnf") ? sProfile : sProfile + ".cnf"));
283
284     } // fi (oProfile)
285

286     if (DebugFile.trace) DebugFile.writeln("End Environment.getProfile()");
287
288     return oProfile;
289   } // getProfile()
290

291   //-----------------------------------------------------------
292

293   /**
294    * <p>Load a Profile from a Properties file</p>
295    * <p>The loaded Profile is cached in memory and will be returned in
296    * future calls to getProfile()</p>
297    * <p>If profile had been already loaded, then it is overwritten.</p>
298    * @param sProfile Profile name, for example "hipergate"
299    * @param sPath Full path to properties file, fo example "/etc/knowgate/hipergate.cnf"
300    */

301   public static Properties JavaDoc loadProfile(String JavaDoc sProfile, String JavaDoc sPath) {
302     FileInputStream JavaDoc oFileStream;
303     Properties JavaDoc oProfile;
304
305     if (DebugFile.trace) DebugFile.writeln("Begin Environment.loadProfile(" + sProfile + "," + sPath + ")");
306
307     if (profiles.containsKey(sProfile))
308       profiles.remove(sProfile);
309
310     oProfile = new Properties JavaDoc();
311     try {
312       oFileStream = new FileInputStream JavaDoc(sPath);
313
314       oProfile.load(oFileStream);
315       oFileStream.close();
316
317       profiles.put(sProfile, oProfile);
318     }
319     catch (FileNotFoundException JavaDoc nfe) {
320       if (DebugFile.trace) DebugFile.writeln("FileNotFoundException " + sPath + " " + nfe.getMessage());
321     }
322     catch (IOException JavaDoc ioe) {
323       if (DebugFile.trace) DebugFile.writeln("IOException " + sPath + " " + ioe.getMessage());
324     }
325
326     if (DebugFile.trace) DebugFile.writeln("End Environment.loadProfile()");
327
328     return oProfile;
329   } // loadProfile
330

331   //-----------------------------------------------------------
332

333   /**
334    * Get a Set with all loaded profiles names
335    * @return Set of profile names
336    */

337   public static Set JavaDoc getProfilesSet() {
338     return profiles.keySet();
339   }
340
341   //-----------------------------------------------------------
342

343   /**
344    * <p>Get a single property from a .CNF file.</p>
345    * <p>Properties are readed once from disk and then cached in memory.
346    * If .CNF file is changed, refresh() method must be called for refreshing
347    * in-memory cached values.</p>
348    * @param sProfile .CNF file name
349    * @param sVarName Property Name
350    * @return Value of property or <b>null</b> if no property with such name was found.
351    */

352   public static String JavaDoc getProfileVar(String JavaDoc sProfile, String JavaDoc sVarName) {
353     String JavaDoc sRetVal;
354     Properties JavaDoc oProfile;
355
356     //if (DebugFile.trace) DebugFile.writeln("Begin Environment.getProfileVar(" + sProfile + "," + sVarName + ")");
357

358     oProfile = getProfile(sProfile);
359
360     if (oProfile==null)
361       sRetVal = null;
362     else
363       sRetVal = oProfile.getProperty(sVarName);
364     // fi (oProfile)
365

366     //if (DebugFile.trace) DebugFile.writeln("End Environment.getProfileVar() : " + (sRetVal!=null ? sRetVal : "null"));
367

368     return sRetVal;
369   } // getProfileVar()
370

371   //-----------------------------------------------------------
372

373   /**
374    * Get names of all properties in a profile
375    * @param sProfile Profile Name
376    * @return Set of property names
377    */

378   public static Set JavaDoc getProfileVarSet(String JavaDoc sProfile) {
379
380     Set JavaDoc oRetVal;
381     Properties JavaDoc oProfile;
382
383     //if (DebugFile.trace) DebugFile.writeln("Begin Environment.getProfileVarSet(" + sProfile + ")");
384

385     oProfile = getProfile(sProfile);
386
387     if (oProfile==null)
388       oRetVal = null;
389     else
390       oRetVal = oProfile.keySet();
391     // fi (oProfile)
392

393     /*
394     if (DebugFile.trace)
395       if (null==oRetVal)
396         DebugFile.writeln("End Environment.getProfileVarSet() : null");
397       else
398         DebugFile.writeln("End Environment.getProfileVarSet() : " + String.valueOf(oRetVal.size()));
399     */

400
401     return oRetVal;
402
403   } // getProfileVarSet
404

405   //-----------------------------------------------------------
406

407   /**
408    * <p>Get a property from a .CNF file representing a file path.</p>
409    * <p>This method is equivalent to getProfileVar except that a
410    * file separator is always appended to the end of the readed value.</p>
411    * @param sProfile .CNF file name
412    * @param sVarName Property Name
413    * @return Value terminated with a file separator or <b>null</b> if no property with such name was found.
414    */

415
416   public static String JavaDoc getProfilePath(String JavaDoc sProfile, String JavaDoc sVarName) {
417     String JavaDoc sPath = getProfileVar(sProfile, sVarName);
418     return Gadgets.chomp(sPath, System.getProperty("file.separator"));
419   }
420
421   //-----------------------------------------------------------
422

423   /**
424    * <p>Get a single property from a .CNF file.</p>
425    * @param sProfile .CNF file name
426    * @param sVarName Property Name
427    * @param sDefault Default Value
428    * @return Value of property or sDefault if no property with such name was found.
429    */

430
431   public static String JavaDoc getProfileVar(String JavaDoc sProfile, String JavaDoc sVarName, String JavaDoc sDefault) {
432     String JavaDoc sRetVal;
433     Properties JavaDoc oProfile;
434
435     //if (DebugFile.trace) DebugFile.writeln("Begin Environment.getProfileVar(" + sProfile + "," + sVarName + "," + sDefault + ")");
436

437     oProfile = getProfile(sProfile);
438
439     if (oProfile==null)
440       sRetVal = null;
441     else
442       sRetVal = oProfile.getProperty(sVarName);
443     // fi (oProfile)
444

445     //if (DebugFile.trace) DebugFile.writeln("End Environment.getProfileVar() : " + (sRetVal!=null ? sRetVal : sDefault));
446

447     return (null!=sRetVal ? sRetVal : sDefault);
448   } // getProfileVar()
449

450   //-----------------------------------------------------------
451

452   /**
453    * <p>Set value for a profile property</p>
454    * Value is change in memory cache but not saved to disk.
455    * @param sProfile Profile Name
456    * @param sVarName Property Name
457    * @param sVarValue Prioperty Value
458    */

459   public static void setProfileVar(String JavaDoc sProfile, String JavaDoc sVarName, String JavaDoc sVarValue) {
460     Properties JavaDoc oProfile = Environment.getProfile(sProfile);
461
462     oProfile.setProperty(sVarName, sVarValue);
463   } // setProfileVar()
464

465   //-----------------------------------------------------------
466

467   private static boolean execCommand(String JavaDoc sCmd) {
468     boolean bRetVal=true;
469
470     try {
471       Runtime.getRuntime().exec(sCmd);
472     }
473     catch (IOException JavaDoc ioe) {
474       bRetVal=false;
475     }
476
477     return bRetVal;
478   } // execCommand
479

480   //-----------------------------------------------------------
481

482   /**
483    * <p>Refresh in-memory cached properties by re-reading then from disk files.</p>
484    */

485
486   public static void refresh() {
487     envVars = null;
488     profiles = new HashMap JavaDoc();
489   }
490
491   //-----------------------------------------------------------
492

493   /**
494    * <p>Update system time</p>
495    * <p>This is an alpha testing method, do not use in production environments.</p>
496    * @param lTime New System Date
497    */

498
499   public static void updateSystemTime(long lTime) {
500     try
501     {
502         String JavaDoc system = System.getProperty("os.name");
503         String JavaDoc cmdDate = "";
504         String JavaDoc cmdTime = "";
505         Date JavaDoc curDate = new Date JavaDoc();
506         curDate.setTime(lTime);
507         SimpleDateFormat JavaDoc fmt = new SimpleDateFormat JavaDoc(getProfileVar("hipergate", "dateformat", "dd-MM-yyyy"));
508         //SimpleTimeZone atz = null;
509
//fmt.setCalendar(new GregorianCalendar(atz));
510
String JavaDoc actDate = fmt.format(curDate);
511         fmt.applyPattern("HH:mm:ss");
512         String JavaDoc actTime = fmt.format(curDate);
513         if (system.startsWith("Windows NT") || system.startsWith("Windows 2000")) {
514             execCommand("cmd /c date " + actDate);
515             cmdTime = "cmd /c time " + actTime;
516             execCommand(cmdTime);
517         } else
518         // Win 95/98. Dirty skunk. Doesn't tell us about who it is in real
519
if (system.indexOf("Windows") == 0) {
520             fmt.applyPattern("MM.dd.yyyy");
521             actDate = fmt.format(curDate);
522             execCommand("c:\\command.com /c date " + actDate);
523             fmt.applyPattern("dd-MM-yyyy");
524             actDate = fmt.format(curDate);
525             execCommand("c:\\command /c date " + actDate);
526             fmt.applyPattern("yyyy-MM-dd");
527             actDate = fmt.format(curDate);
528             execCommand("c:\\command /c date " + actDate);
529             cmdTime = "c:\\command.com /c time " + actTime;
530             execCommand(cmdTime);
531         } else
532         //if ((system.toUpperCase().indexOf("UNIX") == 0) || (system.toUpperCase().indexOf("LINUX") == 0))
533
{
534             fmt.applyPattern("MM/dd/yyyy HH:mm:ss");
535             actDate = fmt.format(curDate);
536             cmdDate = "date -u -s'" + actDate + "' +'%D %T'";
537             execCommand(cmdDate);
538         }
539     }
540     catch (Exception JavaDoc e) {
541     }
542   } // updateSystemTime
543

544   //-----------------------------------------------------------
545

546   private static Properties JavaDoc envVars = null;
547   private static HashMap JavaDoc profiles = new HashMap JavaDoc();
548
549 } // Environment
550
Popular Tags