KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ixenon > free > util > Environment


1 /* $Id$
2  *
3  * Copyright (c) 1999 Xenonsoft Limited. All Rights Reserved.
4  *
5  * This software is protected by copyright. You are hereby notified from
6  * now by reading this message. This software is also the confidential
7  * and proprietary information of Xenonsoft Limited. ("Confidential
8  * Information").
9  *
10  * This software is distributed under the Xenonsoft Public end user
11  * License ("XPeL"), where the machine-readable source code is provided
12  * under the "Open Source" model.
13  * For more information, please read the file "LICENSE-XPL.txt"
14  */

15
16 //
17
// DESCRIPTION
18
//
19
// Peter Pilgrim
20
// Fri Sep 11 01:15:46 BST 1998
21
//
22
// RCS HEADER ``Environment''
23
//
24
// $Author$
25
// $Date$
26
// $Source$
27
// $Revision$ $State$ $Locker$
28
//
29

30 package ixenon.free.util;
31
32 import java.io.*;
33 import java.util.*;
34
35 /**
36  *
37  * This class helps an application read and use the Environment variables
38  * defined in the unix shell within a java program.
39  *
40  * The class has also been updated to read a default application property
41  * to set up environment variable on operating systems, such as the
42  * Windows NT and MacOS, that do not support environment variables, or
43  * have large difficulty passing environment variables to a Java program.
44  */

45 public class Environment
46 {
47     /**
48      * This static method first tries to read an application default property
49      * file to set up properties for the application, if such a file exists.
50      * <P>
51      * Secondly the method tries to read the entire environment from a system
52      * property called `env'.
53      * <P>
54      * For UNIX systems it is possible to pass the entire environment as
55      * a system property. This is <B>ONLY</B> possible, because UNIX shell
56      * interpreter allow a feature called <I>back substitution</I>.
57      * On UNIX systems to print out the environment variables use:
58      *
59      * <PRE>
60      * % env
61      * </PRE>
62      * <P>
63      * To read the current directory into the a shell variable
64      * called `APPLE' one would type:
65      *
66      * <PRE>
67      * % APPLE=`ls`
68      * </PRE>
69      * <P>
70      * Now printing the variable the variable $APPLE will print the
71      * current directory.
72      *
73      * <PRE>
74      * % echo $APPLE
75      * </PRE>
76      * <P>
77      * Hence to pass to the entire environment to a java virtual as
78      * system property is very easy on UNIX systems.
79      * <P>
80      * For UNIX operating systems the entire environment is available
81      * through the calls <B>System.getProperties().getProperty("env")</B>
82      * This static method basically takes the value of this property
83      * which is the entire environment and breaks it up in to original
84      * settings storing each one as a system property. Each setting is
85      * stored with a prefix "env.X" where X is an environment variable.
86      * <P>
87      * Hence to read the unix PATH environment variable then read the
88      * system property called `env.PATH'
89      * <P>
90      * To use this class the java virtual machine must be invoked with
91      * a <I>-Denv="`env`"</I> option. For example:
92      *
93      * <PRE>
94      * % java -Denv="`env`" Foobar
95      * </PRE>
96      *
97      * <P>
98      * The default property file is found by searching for directory
99      * defined by the system property called <B>`appres.path'</B>.
100      * This path separator delimited value containing directory path
101      * where the property could be found. You pass the property to
102      * a java virtual machine by using the -D command line parameter.
103      *
104      * <PRE>
105      * % java -Dappres.path="C:\Alice\Wonderland" -Denv="`env`" Foobar
106      * </PRE>
107      *
108      * <P>
109      * If the system property <B>`appres.path'</B> is not defined, then
110      * the value of the system property `user.home' is used.
111      *
112      * @param propertyFile specifies the name of the default property filename
113      *
114      */

115     public static void readEnvironment( String JavaDoc propertyFile )
116     {
117     String JavaDoc osname = System.getProperty( "os.name" );
118     String JavaDoc appresPath = System.getProperty( "appres.path" );
119     String JavaDoc fileSep = System.getProperty( "file.separator" );
120     String JavaDoc pathSep = System.getProperty( "path.separator" );
121     boolean foundPropFile = false;
122
123     if ( appresPath == null ) {
124         appresPath = System.getProperty( "user.home" );
125         if ( osname.startsWith("Windows 95") ||
126          osname.startsWith("Windows 98") ||
127          osname.startsWith("Windows NT") ||
128          osname.startsWith("Windows 2000") ||
129          osname.startsWith("OS/2") )
130         appresPath += pathSep + "C:\\Program Files";
131         else
132         appresPath += pathSep + fileSep + "usr"+fileSep+"local";
133     }
134
135     //
136
// Try to find the default application property file by searching
137
// application resource path.
138
//
139
StringTokenizer st = new StringTokenizer( appresPath, pathSep );
140     while ( st.hasMoreTokens() ) {
141         String JavaDoc dirpath = st.nextToken();
142         File propFile = new File( dirpath, propertyFile );
143         // System.out.println( "*** "+propFile.getPath() );
144
if ( propFile.exists() ) {
145         // System.out.println( "*** FOUND DEFAULT PROPERTY FILE ***" );
146
foundPropFile = readDefaultPropertyFile( propFile, false );
147         break;
148         }
149     }
150
151     boolean foundEnv = Environment.readEnvironmentVariables();
152     if ( !foundPropFile && !foundEnv ) {
153         System.out.println( "*WARNING: cannot find or retrieve application default resources" );
154         System.out.println( "property file: `"+propertyFile+"'" );
155         System.out.println( "HINT: % java -Denv=\"`env`\" Foobar is used." );
156     }
157     }
158
159     /**
160      * readDefaultPropertyFile
161      * @param file the property default filename
162      */

163     public static boolean readDefaultPropertyFile( File propFile, boolean override )
164     {
165     if ( !propFile.exists() )
166         return (false);
167     
168     Properties propJVM = System.getProperties ();
169
170     //
171
// load the default application properties files.
172
//
173
System.out.println("Loading default application properties file: `"+propFile.getPath()+"'" );
174     if ( !propFile.canRead() ) {
175         System.err.println("Cannot read default properties file:`"+propFile.getPath()+"'" );
176         return (false);
177     }
178     
179     //
180
// Merge the default properties into the system properties
181
//
182
boolean retval=false;
183     Properties propTemp = new Properties();
184     try {
185         FileInputStream fis = new FileInputStream( propFile );
186         propTemp.load(fis);
187         Enumeration keys = propTemp.propertyNames();
188         while( keys.hasMoreElements() ) {
189         String JavaDoc name = (String JavaDoc)keys.nextElement();
190         String JavaDoc value1 = propTemp.getProperty( name );
191         String JavaDoc value2 = propJVM.getProperty( name );
192         if (value2 == null || override) {
193             // DEBUG: System.out.println( "Merging ==> "+name+"="+value1 );
194
propJVM.put( name, value1 );
195         }
196         }
197     }
198     catch (IOException ioe) {
199         retval = false;
200         System.err.println(
201         "I/O Exception occurred reading file:" +
202         propFile.getPath() + " message:`" + ioe.getMessage()+"'" );
203     }
204
205     return (retval);
206     }
207
208     /**
209      * read (UNIX) environment variables from the system property
210      * <B>`env'</B>.
211      */

212     public static boolean readEnvironmentVariables()
213     {
214     Properties propJVM = System.getProperties();
215
216     String JavaDoc env = propJVM.getProperty("env");
217     if ( env == null )
218         return (false);
219
220     // If we get here, there was `env' property specified on the
221
// command line obviously. This property holds the entire environment
222
// on a UNIX type system.
223
try {
224         // Remove the old system propery called `env'
225
propJVM.remove("env");
226
227         // Read in environment variable definitions setting
228
// new property prefixed with "env." The value of the property
229
// is usual a large string value (about 1024 characters).
230
//
231
ReadbackStream readback = new ReadbackStream();
232         OutputStreamWriter osw = new OutputStreamWriter(readback);
233         PrintWriter wholeenv = new PrintWriter(osw);
234         
235         // Write the entire system property `env' into the
236
// readback stream and convert the character encoding
237
propJVM.save( readback, null);
238         byte [] envarray = env.getBytes( osw.getEncoding() );
239         
240         BufferedReader envin =
241         new BufferedReader(
242             new InputStreamReader(
243             new ByteArrayInputStream(envarray) ) );
244         String JavaDoc line;
245         while ( (line = envin.readLine() ) != null )
246         {
247         // Read the property `env' line by line and prepend
248
// the property name before writing it to the same
249
// readback stream again. Affectively breaking up the
250
// long environment output value into consituent parts.
251
line = "env." + line;
252         wholeenv.println(line);
253         wholeenv.flush(); // Force flush
254
// DEBUG: System.out.println(line);
255
}
256         // Load the system property from the contents of the
257
// readback stream thereby creating a list of new system
258
// properties in the process.
259
propJVM.load( readback.getInputStream() );
260     }
261     catch ( UnsupportedEncodingException e ) {
262         System.err.println( "Environment character encoding is not supported.");
263         System.err.println( "Exception Msg:"+e.getMessage());
264         System.exit(1);
265     }
266     catch ( IOException e ) {}
267     // DEBUG: System.out.println("**** DEATH 69 ****"); System.exit(69);
268

269     return (true);
270     }
271 }
272
273 // fini
274
Popular Tags