001: /*
002: Copyright (C) 2003 Know Gate S.L. All rights reserved.
003: C/Oņa, 107 1š2 28050 Madrid (Spain)
004:
005: Redistribution and use in source and binary forms, with or without
006: modification, are permitted provided that the following conditions
007: are met:
008:
009: 1. Redistributions of source code must retain the above copyright
010: notice, this list of conditions and the following disclaimer.
011:
012: 2. The end-user documentation included with the redistribution,
013: if any, must include the following acknowledgment:
014: "This product includes software parts from hipergate
015: (http://www.hipergate.org/)."
016: Alternately, this acknowledgment may appear in the software itself,
017: if and wherever such third-party acknowledgments normally appear.
018:
019: 3. The name hipergate must not be used to endorse or promote products
020: derived from this software without prior written permission.
021: Products derived from this software may not be called hipergate,
022: nor may hipergate appear in their name, without prior written
023: permission.
024:
025: This library is distributed in the hope that it will be useful,
026: but WITHOUT ANY WARRANTY; without even the implied warranty of
027: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
028:
029: You should have received a copy of hipergate License with this code;
030: if not, visit http://www.hipergate.org or mail to info@hipergate.org
031: */
032:
033: package com.knowgate.misc;
034:
035: import java.io.IOException;
036: import java.io.InputStream;
037: import java.io.StringBufferInputStream;
038: import java.io.FileNotFoundException;
039: import java.io.File;
040: import java.io.FileInputStream;
041: import java.io.FileOutputStream;
042: import java.io.FileReader;
043: import java.io.FileWriter;
044:
045: import java.lang.System;
046: import java.util.Properties;
047: import java.util.HashMap;
048: import java.util.Date;
049: import java.util.Set;
050: import java.text.SimpleDateFormat;
051:
052: import com.knowgate.debug.*;
053:
054: /**
055: * <p>Reads and keeps in memory properties from .cnf initialization files.</p>
056: * @author Sergio Montoro Ten
057: * @version 3.0
058: */
059:
060: public class Environment {
061: public static String DEFAULT_PROFILES_DIR = (System.getProperty(
062: "os.name").equals("Windows XP") ? "C:\\Windows\\"
063: : (System.getProperty("os.name").startsWith("Windows") ? "C:\\WINNT\\"
064: : "/etc/"));
065:
066: private Environment() {
067: }
068:
069: //-----------------------------------------------------------
070:
071: private static String getEnvironmentDirectory() {
072: if (DEFAULT_PROFILES_DIR.equalsIgnoreCase("C:\\WINNT\\")) {
073: File oWinDir = new File("C:\\WINNT");
074: if (!oWinDir.exists()) {
075: oWinDir = new File("C:\\WINDOWS");
076: if (oWinDir.exists()) {
077: DEFAULT_PROFILES_DIR = "C:\\WINDOWS\\";
078: } else {
079: DEFAULT_PROFILES_DIR = getEnvVar("windir",
080: getEnvVar("SystemRoot"));
081: }
082: }
083: } // fi (DEFAULT_PROFILES_DIR=="C:\WINNT"
084: return DEFAULT_PROFILES_DIR;
085: }
086:
087: //-----------------------------------------------------------
088:
089: private static void readEnvVars()
090: throws java.lang.IllegalArgumentException {
091: envVars = new Properties();
092: Runtime oRT;
093: Process oPT;
094: InputStream oST;
095:
096: final int ENV_BUFFER_SIZE = 131072;
097:
098: try {
099: if (System.getProperty("os.name").startsWith("Windows")) {
100:
101: if (DebugFile.trace)
102: DebugFile.writeln("Runtime.getRuntime()");
103:
104: oRT = Runtime.getRuntime();
105:
106: if (DebugFile.trace)
107: DebugFile
108: .writeln("Runtime.exec(\"cmd.exe /cset\")");
109:
110: oPT = oRT.exec("cmd.exe /cset");
111:
112: oST = oPT.getInputStream();
113:
114: byte[] byBuffer = new byte[ENV_BUFFER_SIZE];
115:
116: int iReaded = oST.read(byBuffer, 0, ENV_BUFFER_SIZE);
117:
118: oST.close();
119:
120: oPT.destroy();
121:
122: oRT = null;
123:
124: // Double back slashes
125: byte[] byEnvVars = new byte[ENV_BUFFER_SIZE + 4096];
126: int iEnvLength = 0;
127:
128: for (int i = 0; i < iReaded; i++) {
129: byEnvVars[iEnvLength++] = byBuffer[i];
130: if (92 == byBuffer[i])
131: byEnvVars[iEnvLength++] = byBuffer[i];
132: } // next
133:
134: byBuffer = null;
135:
136: if (DebugFile.trace)
137: DebugFile.writeln(new String(byEnvVars, 0,
138: iEnvLength));
139:
140: envVars.load(new StringBufferInputStream(new String(
141: byEnvVars, 0, iEnvLength)));
142:
143: } else {
144:
145: if (DebugFile.trace)
146: DebugFile.writeln("Runtime.getRuntime()");
147:
148: oRT = Runtime.getRuntime();
149:
150: if (DebugFile.trace)
151: DebugFile.writeln("Runtime.exec(\"/usr/bin/env\")");
152:
153: oPT = oRT.exec("/usr/bin/env");
154:
155: oST = oPT.getInputStream();
156:
157: if (DebugFile.trace)
158: DebugFile
159: .writeln("Properties.load(Process.getInputStream())");
160:
161: envVars.load(oST);
162:
163: oST.close();
164:
165: oPT.destroy();
166:
167: oRT = null;
168: }
169: } catch (IOException ioe) {
170: if (DebugFile.trace)
171: DebugFile
172: .writeln("Runtime.getRuntime().exec(...) IOException "
173: + ioe.getMessage());
174: } catch (NullPointerException npe) {
175: if (DebugFile.trace)
176: DebugFile
177: .writeln("Runtime.getRuntime().exec(...) NullPointerException "
178: + npe.getMessage());
179: } finally {
180: if (null == envVars.getProperty("KNOWGATE_PROFILES")) {
181: if (DebugFile.trace)
182: DebugFile
183: .writeln("KNOWGATE_PROFILES environment variable not found setting default to "
184: + getEnvironmentDirectory());
185:
186: envVars.setProperty("KNOWGATE_PROFILES",
187: getEnvironmentDirectory());
188: }
189: }
190: } // readEnvVars
191:
192: //-----------------------------------------------------------
193:
194: /**
195: * <p>Get value for an environment variable.</p>
196: * This is not a Pure Java method since it uses the Runtime obeject for calling
197: * OS specific shell commands.
198: * @param sVarName Name of the variable to be readed.
199: * @return Value of variable or <b>null</b> if no environment variable with such name was found.
200: * @throws IllegalArgumentException If there is a Malformed \\uxxxx encoding or any other type of intrinsic error at the environment variables values
201: */
202:
203: public static String getEnvVar(String sVarName)
204: throws IllegalArgumentException {
205:
206: if (envVars == null)
207: readEnvVars();
208:
209: return envVars.getProperty(sVarName);
210: } // getEnvVar()
211:
212: //-----------------------------------------------------------
213:
214: /**
215: * <p>Get value for an environment variable.</p>
216: * This is not a Pure Java method since it uses the Runtime obeject for calling
217: * OS specific shell commands.
218: * @param sVarName Name of the variable to be readed.
219: * @return Value of variable or sDefault if no environment variable with such name was found.
220: */
221:
222: public static String getEnvVar(String sVarName, String sDefault)
223: throws IllegalArgumentException {
224: if (envVars == null)
225: readEnvVars();
226:
227: String sRetVal = envVars.getProperty(sVarName);
228:
229: if (sRetVal == null)
230: return sDefault;
231: else
232: return sRetVal;
233: } // getEnvVar()
234:
235: //-----------------------------------------------------------
236:
237: /**
238: * <P>Get temporary directory</P>
239: * @return For UNIX Sytems this function always return "/tmp/".<BR>
240: * For Windows Systems getTempDir() returns the value set at the environment
241: * variable "TEMP" or C:\\%WINDIR%\\TEMP\\ if TEMP variable is not set.
242: * @throws IllegalArgumentException
243: */
244: public static String getTempDir() throws IllegalArgumentException {
245: if (System.getProperty("os.name").startsWith("Windows")) {
246: String sTempDir = getEnvVar("TEMP");
247: if (null == sTempDir) {
248: File oWinDir;
249: oWinDir = new File("C:\\WINNT\\TEMP\\");
250: if (oWinDir.exists()) {
251: return "C:\\WINNT\\TEMP\\";
252: } else {
253: oWinDir = new File("C:\\WINDOWS\\TEMP\\");
254: if (oWinDir.exists()) {
255: return "C:\\WINDOWS\\TEMP\\";
256: } else {
257: return "C:\\TEMP\\";
258: }
259: }
260: } else {
261: return sTempDir;
262: }
263: } else { // Unix
264: return "/tmp/";
265: }
266: } // getTempDir()
267:
268: //-----------------------------------------------------------
269:
270: /**
271: * <p>Get a Properties collection from a .CNF file</p>
272: * Property files must be in the directory pointed by a operating system environment variable names
273: * <b>KNOWGATE_PROFILES</b>. If KNOWGATE_PROFILES environment variable is not found, the files will
274: * be seeked by default on C:\WINNT\ or C:\WINDOWS\ on Window Systems and /etc/ on UNIX systems.
275: * @param sProfile Properties file to read (for example "hipergate.cnf")
276: * @since v2.2 The behaviour of this function has changed: it first tries to get KNOWGATE_PROFILES
277: * from Java environment variables as set on startup "java -DKNOWGATE_PROFILES=..." if there is no
278: * Java property named KNOWGATE_PROFILES then operating system environment variabled are scanned and
279: * last if neither is found the default C:\WINNT\ C:\WINDOWS\ or /etc/ is returned
280: */
281: public static Properties getProfile(String sProfile) {
282: String sProfilesHome;
283: Properties oProfile;
284:
285: if (DebugFile.trace)
286: DebugFile.writeln("Begin Environment.getProfile()");
287:
288: oProfile = (Properties) profiles.get(sProfile);
289:
290: if (oProfile == null) {
291:
292: try {
293: sProfilesHome = System.getProperty("KNOWGATE_PROFILES",
294: getEnvVar("KNOWGATE_PROFILES"));
295: } catch (java.lang.IllegalArgumentException iae) {
296: sProfilesHome = getEnvironmentDirectory();
297:
298: if (DebugFile.trace)
299: DebugFile
300: .writeln("Environment.getEnvVar(KNOWGATE_PROFILES) IllegalArgumentException "
301: + iae.getMessage());
302: }
303:
304: if (DebugFile.trace)
305: DebugFile.writeln(" KNOWGATE_PROFILES="
306: + sProfilesHome);
307:
308: if (!sProfilesHome.endsWith(System
309: .getProperty("file.separator")))
310: sProfilesHome += System.getProperty("file.separator");
311:
312: oProfile = loadProfile(sProfile, sProfilesHome
313: + (sProfile.endsWith(".cnf") ? sProfile : sProfile
314: + ".cnf"));
315:
316: } // fi (oProfile)
317:
318: if (DebugFile.trace)
319: DebugFile.writeln("End Environment.getProfile()");
320:
321: return oProfile;
322: } // getProfile()
323:
324: //-----------------------------------------------------------
325:
326: /**
327: * <p>Load a Profile from a Properties file</p>
328: * <p>The loaded Profile is cached in memory and will be returned in
329: * future calls to getProfile()</p>
330: * <p>If profile had been already loaded, then it is overwritten.</p>
331: * @param sProfile Profile name, for example "hipergate"
332: * @param sPath Full path to properties file, fo example "/etc/knowgate/hipergate.cnf"
333: */
334: public static Properties loadProfile(String sProfile, String sPath) {
335: FileInputStream oFileStream;
336: Properties oProfile;
337:
338: if (DebugFile.trace)
339: DebugFile.writeln("Begin Environment.loadProfile("
340: + sProfile + "," + sPath + ")");
341:
342: if (profiles.containsKey(sProfile))
343: profiles.remove(sProfile);
344:
345: oProfile = new Properties();
346: try {
347: oFileStream = new FileInputStream(sPath);
348:
349: oProfile.load(oFileStream);
350: oFileStream.close();
351:
352: profiles.put(sProfile, oProfile);
353: } catch (FileNotFoundException nfe) {
354: if (DebugFile.trace)
355: DebugFile.writeln("FileNotFoundException " + sPath
356: + " " + nfe.getMessage());
357: } catch (IOException ioe) {
358: if (DebugFile.trace)
359: DebugFile.writeln("IOException " + sPath + " "
360: + ioe.getMessage());
361: }
362:
363: if (DebugFile.trace)
364: DebugFile.writeln("End Environment.loadProfile()");
365:
366: return oProfile;
367: } // loadProfile
368:
369: //-----------------------------------------------------------
370:
371: /**
372: * Get a Set with all loaded profiles names
373: * @return Set of profile names
374: */
375: public static Set getProfilesSet() {
376: return profiles.keySet();
377: }
378:
379: //-----------------------------------------------------------
380:
381: /**
382: * <p>Get a single property from a .CNF file.</p>
383: * <p>Properties are readed once from disk and then cached in memory.
384: * If .CNF file is changed, refresh() method must be called for refreshing
385: * in-memory cached values.</p>
386: * @param sProfile .CNF file name
387: * @param sVarName Property Name
388: * @return Value of property or <b>null</b> if no property with such name was found.
389: */
390: public static String getProfileVar(String sProfile, String sVarName) {
391: String sRetVal;
392: Properties oProfile;
393:
394: //if (DebugFile.trace) DebugFile.writeln("Begin Environment.getProfileVar(" + sProfile + "," + sVarName + ")");
395:
396: oProfile = getProfile(sProfile);
397:
398: if (oProfile == null)
399: sRetVal = null;
400: else
401: sRetVal = oProfile.getProperty(sVarName);
402: // fi (oProfile)
403:
404: //if (DebugFile.trace) DebugFile.writeln("End Environment.getProfileVar() : " + (sRetVal!=null ? sRetVal : "null"));
405:
406: return sRetVal;
407: } // getProfileVar()
408:
409: //-----------------------------------------------------------
410:
411: /**
412: * Get names of all properties in a profile
413: * @param sProfile Profile Name
414: * @return Set of property names
415: */
416: public static Set getProfileVarSet(String sProfile) {
417:
418: Set oRetVal;
419: Properties oProfile;
420:
421: //if (DebugFile.trace) DebugFile.writeln("Begin Environment.getProfileVarSet(" + sProfile + ")");
422:
423: oProfile = getProfile(sProfile);
424:
425: if (oProfile == null)
426: oRetVal = null;
427: else
428: oRetVal = oProfile.keySet();
429: // fi (oProfile)
430:
431: /*
432: if (DebugFile.trace)
433: if (null==oRetVal)
434: DebugFile.writeln("End Environment.getProfileVarSet() : null");
435: else
436: DebugFile.writeln("End Environment.getProfileVarSet() : " + String.valueOf(oRetVal.size()));
437: */
438:
439: return oRetVal;
440:
441: } // getProfileVarSet
442:
443: //-----------------------------------------------------------
444:
445: /**
446: * <p>Get a property from a .CNF file representing a file path.</p>
447: * <p>This method is equivalent to getProfileVar except that a
448: * file separator is always appended to the end of the readed value.</p>
449: * @param sProfile .CNF file name
450: * @param sVarName Property Name
451: * @return Value terminated with a file separator or <b>null</b> if no property with such name was found.
452: */
453:
454: public static String getProfilePath(String sProfile, String sVarName) {
455: String sPath = getProfileVar(sProfile, sVarName);
456: return Gadgets.chomp(sPath, System
457: .getProperty("file.separator"));
458: }
459:
460: //-----------------------------------------------------------
461:
462: /**
463: * <p>Get a single property from a .CNF file.</p>
464: * @param sProfile .CNF file name
465: * @param sVarName Property Name
466: * @param sDefault Default Value
467: * @return Value of property or sDefault if no property with such name was found.
468: */
469:
470: public static String getProfileVar(String sProfile,
471: String sVarName, String sDefault) {
472: String sRetVal;
473: Properties oProfile;
474:
475: //if (DebugFile.trace) DebugFile.writeln("Begin Environment.getProfileVar(" + sProfile + "," + sVarName + "," + sDefault + ")");
476:
477: oProfile = getProfile(sProfile);
478:
479: if (oProfile == null)
480: sRetVal = null;
481: else
482: sRetVal = oProfile.getProperty(sVarName);
483: // fi (oProfile)
484:
485: //if (DebugFile.trace) DebugFile.writeln("End Environment.getProfileVar() : " + (sRetVal!=null ? sRetVal : sDefault));
486:
487: return (null != sRetVal ? sRetVal : sDefault);
488: } // getProfileVar()
489:
490: //-----------------------------------------------------------
491:
492: /**
493: * <p>Set value for a profile property</p>
494: * Value is change in memory cache but not saved to disk.
495: * @param sProfile Profile Name
496: * @param sVarName Property Name
497: * @param sVarValue Prioperty Value
498: */
499: public static void setProfileVar(String sProfile, String sVarName,
500: String sVarValue) {
501: Properties oProfile = Environment.getProfile(sProfile);
502:
503: oProfile.setProperty(sVarName, sVarValue);
504: } // setProfileVar()
505:
506: //-----------------------------------------------------------
507:
508: private static boolean execCommand(String sCmd) {
509: boolean bRetVal = true;
510:
511: try {
512: Runtime.getRuntime().exec(sCmd);
513: } catch (IOException ioe) {
514: bRetVal = false;
515: }
516:
517: return bRetVal;
518: } // execCommand
519:
520: //-----------------------------------------------------------
521:
522: /**
523: * <p>Refresh in-memory cached properties by re-reading then from disk files.</p>
524: */
525:
526: public static void refresh() {
527: envVars = null;
528: profiles = new HashMap();
529: }
530:
531: //-----------------------------------------------------------
532:
533: /**
534: * <p>Update system time</p>
535: * <p>This is an alpha testing method, do not use in production environments.</p>
536: * @param lTime New System Date
537: */
538:
539: public static void updateSystemTime(long lTime) {
540: try {
541: String system = System.getProperty("os.name");
542: String cmdDate = "";
543: String cmdTime = "";
544: Date curDate = new Date();
545: curDate.setTime(lTime);
546: SimpleDateFormat fmt = new SimpleDateFormat(getProfileVar(
547: "hipergate", "dateformat", "dd-MM-yyyy"));
548: //SimpleTimeZone atz = null;
549: //fmt.setCalendar(new GregorianCalendar(atz));
550: String actDate = fmt.format(curDate);
551: fmt.applyPattern("HH:mm:ss");
552: String actTime = fmt.format(curDate);
553: if (system.startsWith("Windows NT")
554: || system.startsWith("Windows 2000")) {
555: execCommand("cmd /c date " + actDate);
556: cmdTime = "cmd /c time " + actTime;
557: execCommand(cmdTime);
558: } else
559: // Win 95/98. Dirty skunk. Doesn't tell us about who it is in real
560: if (system.indexOf("Windows") == 0) {
561: fmt.applyPattern("MM.dd.yyyy");
562: actDate = fmt.format(curDate);
563: execCommand("c:\\command.com /c date " + actDate);
564: fmt.applyPattern("dd-MM-yyyy");
565: actDate = fmt.format(curDate);
566: execCommand("c:\\command /c date " + actDate);
567: fmt.applyPattern("yyyy-MM-dd");
568: actDate = fmt.format(curDate);
569: execCommand("c:\\command /c date " + actDate);
570: cmdTime = "c:\\command.com /c time " + actTime;
571: execCommand(cmdTime);
572: } else
573: //if ((system.toUpperCase().indexOf("UNIX") == 0) || (system.toUpperCase().indexOf("LINUX") == 0))
574: {
575: fmt.applyPattern("MM/dd/yyyy HH:mm:ss");
576: actDate = fmt.format(curDate);
577: cmdDate = "date -u -s'" + actDate + "' +'%D %T'";
578: execCommand(cmdDate);
579: }
580: } catch (Exception e) {
581: }
582: } // updateSystemTime
583:
584: //-----------------------------------------------------------
585:
586: private static Properties envVars = null;
587: private static HashMap profiles = new HashMap();
588:
589: } // Environment
|