OSDN Git Service

* java/lang/Thread.java (Thread(ThreadGroup, Runnable, String)): Pass
[pf3gnuchains/gcc-fork.git] / libjava / java / lang / System.java
1 /* System.java -- useful methods to interface with the system
2    Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006
3    Free Software Foundation, Inc.
4
5 This file is part of GNU Classpath.
6
7 GNU Classpath is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2, or (at your option)
10 any later version.
11
12 GNU Classpath is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Classpath; see the file COPYING.  If not, write to the
19 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
20 02110-1301 USA.
21
22 Linking this library statically or dynamically with other modules is
23 making a combined work based on this library.  Thus, the terms and
24 conditions of the GNU General Public License cover the whole
25 combination.
26
27 As a special exception, the copyright holders of this library give you
28 permission to link this library with independent modules to produce an
29 executable, regardless of the license terms of these independent
30 modules, and to copy and distribute the resulting executable under
31 terms of your choice, provided that you also meet, for each linked
32 independent module, the terms and conditions of the license of that
33 module.  An independent module is a module which is not derived from
34 or based on this library.  If you modify this library, you may extend
35 this exception to your version of the library, but you are not
36 obligated to do so.  If you do not wish to do so, delete this
37 exception statement from your version. */
38
39
40 package java.lang;
41
42 import gnu.classpath.SystemProperties;
43
44 import java.io.BufferedInputStream;
45 import java.io.BufferedOutputStream;
46 import java.io.FileDescriptor;
47 import java.io.FileInputStream;
48 import java.io.FileOutputStream;
49 import java.io.InputStream;
50 import java.io.PrintStream;
51 import java.util.AbstractCollection;
52 import java.util.ArrayList;
53 import java.util.Collection;
54 import java.util.Collections;
55 import java.util.HashMap;
56 import java.util.Iterator;
57 import java.util.List;
58 import java.util.Map;
59 import java.util.Set;
60 import java.util.Properties;
61 import java.util.PropertyPermission;
62
63 /**
64  * System represents system-wide resources; things that represent the
65  * general environment.  As such, all methods are static.
66  *
67  * @author John Keiser
68  * @author Eric Blake (ebb9@email.byu.edu)
69  * @since 1.0
70  * @status still missing 1.4 functionality
71  */
72 public final class System
73 {
74   // WARNING: System is a CORE class in the bootstrap cycle. See the comments
75   // in vm/reference/java/lang/Runtime for implications of this fact.
76
77   /**
78    * The standard InputStream. This is assigned at startup and starts its
79    * life perfectly valid. Although it is marked final, you can change it
80    * using {@link #setIn(InputStream)} through some hefty VM magic.
81    *
82    * <p>This corresponds to the C stdin and C++ cin variables, which
83    * typically input from the keyboard, but may be used to pipe input from
84    * other processes or files.  That should all be transparent to you,
85    * however.
86    */
87   public static final InputStream in
88     = new BufferedInputStream(new FileInputStream(FileDescriptor.in));
89   /**
90    * The standard output PrintStream.  This is assigned at startup and
91    * starts its life perfectly valid. Although it is marked final, you can
92    * change it using {@link #setOut(PrintStream)} through some hefty VM magic.
93    *
94    * <p>This corresponds to the C stdout and C++ cout variables, which
95    * typically output normal messages to the screen, but may be used to pipe
96    * output to other processes or files.  That should all be transparent to
97    * you, however.
98    */
99   public static final PrintStream out
100     = new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true);
101   /**
102    * The standard output PrintStream.  This is assigned at startup and
103    * starts its life perfectly valid. Although it is marked final, you can
104    * change it using {@link #setErr(PrintStream)} through some hefty VM magic.
105    *
106    * <p>This corresponds to the C stderr and C++ cerr variables, which
107    * typically output error messages to the screen, but may be used to pipe
108    * output to other processes or files.  That should all be transparent to
109    * you, however.
110    */
111   public static final PrintStream err
112     = new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.err)), true);
113
114   /**
115    * A cached copy of the environment variable map.
116    */
117   private static Map<String,String> environmentMap;
118
119   /**
120    * This class is uninstantiable.
121    */
122   private System()
123   {
124   }
125
126   /**
127    * Set {@link #in} to a new InputStream. This uses some VM magic to change
128    * a "final" variable, so naturally there is a security check,
129    * <code>RuntimePermission("setIO")</code>.
130    *
131    * @param in the new InputStream
132    * @throws SecurityException if permission is denied
133    * @since 1.1
134    */
135   public static void setIn(InputStream in)
136   {
137     SecurityManager sm = SecurityManager.current; // Be thread-safe.
138     if (sm != null)
139       sm.checkPermission(new RuntimePermission("setIO"));
140     setIn0(in);
141   }
142
143   /**
144    * Set {@link #out} to a new PrintStream. This uses some VM magic to change
145    * a "final" variable, so naturally there is a security check,
146    * <code>RuntimePermission("setIO")</code>.
147    *
148    * @param out the new PrintStream
149    * @throws SecurityException if permission is denied
150    * @since 1.1
151    */
152   public static void setOut(PrintStream out)
153   {
154     SecurityManager sm = SecurityManager.current; // Be thread-safe.
155     if (sm != null)
156       sm.checkPermission(new RuntimePermission("setIO"));
157     
158     setOut0(out);
159   }
160
161   /**
162    * Set {@link #err} to a new PrintStream. This uses some VM magic to change
163    * a "final" variable, so naturally there is a security check,
164    * <code>RuntimePermission("setIO")</code>.
165    *
166    * @param err the new PrintStream
167    * @throws SecurityException if permission is denied
168    * @since 1.1
169    */
170   public static void setErr(PrintStream err)
171   {
172     SecurityManager sm = SecurityManager.current; // Be thread-safe.
173     if (sm != null)
174       sm.checkPermission(new RuntimePermission("setIO"));
175     setErr0(err);
176   }
177
178   /**
179    * Set the current SecurityManager. If a security manager already exists,
180    * then <code>RuntimePermission("setSecurityManager")</code> is checked
181    * first. Since this permission is denied by the default security manager,
182    * setting the security manager is often an irreversible action.
183    *
184    * @param sm the new SecurityManager
185    * @throws SecurityException if permission is denied
186    */
187   public static synchronized void setSecurityManager(SecurityManager sm)
188   {
189     // Implementation note: the field lives in SecurityManager because of
190     // bootstrap initialization issues. This method is synchronized so that
191     // no other thread changes it to null before this thread makes the change.
192     if (SecurityManager.current != null)
193       SecurityManager.current.checkPermission
194         (new RuntimePermission("setSecurityManager"));
195     SecurityManager.current = sm;
196   }
197
198   /**
199    * Get the current SecurityManager. If the SecurityManager has not been
200    * set yet, then this method returns null.
201    *
202    * @return the current SecurityManager, or null
203    */
204   public static SecurityManager getSecurityManager()
205   {
206     return SecurityManager.current;
207   }
208
209   /**
210    * Get the current time, measured in the number of milliseconds from the
211    * beginning of Jan. 1, 1970. This is gathered from the system clock, with
212    * any attendant incorrectness (it may be timezone dependent).
213    *
214    * @return the current time
215    * @see java.util.Date
216    */
217   public static native long currentTimeMillis();
218
219   /**
220    * Get the current time, measured in nanoseconds.  The result is as
221    * precise as possible, and is measured against a fixed epoch.
222    * However, unlike currentTimeMillis(), the epoch chosen is
223    * arbitrary and may vary by platform, etc.
224    * @since 1.5
225    */
226   public static native long nanoTime();
227
228   /**
229    * Copy one array onto another from <code>src[srcStart]</code> ...
230    * <code>src[srcStart+len-1]</code> to <code>dest[destStart]</code> ...
231    * <code>dest[destStart+len-1]</code>. First, the arguments are validated:
232    * neither array may be null, they must be of compatible types, and the
233    * start and length must fit within both arrays. Then the copying starts,
234    * and proceeds through increasing slots.  If src and dest are the same
235    * array, this will appear to copy the data to a temporary location first.
236    * An ArrayStoreException in the middle of copying will leave earlier
237    * elements copied, but later elements unchanged.
238    *
239    * @param src the array to copy elements from
240    * @param srcStart the starting position in src
241    * @param dest the array to copy elements to
242    * @param destStart the starting position in dest
243    * @param len the number of elements to copy
244    * @throws NullPointerException if src or dest is null
245    * @throws ArrayStoreException if src or dest is not an array, if they are
246    *         not compatible array types, or if an incompatible runtime type
247    *         is stored in dest
248    * @throws IndexOutOfBoundsException if len is negative, or if the start or
249    *         end copy position in either array is out of bounds
250    */
251   public static native void arraycopy(Object src, int srcStart,
252                                       Object dest, int destStart, int len);
253
254   /**
255    * Get a hash code computed by the VM for the Object. This hash code will
256    * be the same as Object's hashCode() method.  It is usually some
257    * convolution of the pointer to the Object internal to the VM.  It
258    * follows standard hash code rules, in that it will remain the same for a
259    * given Object for the lifetime of that Object.
260    *
261    * @param o the Object to get the hash code for
262    * @return the VM-dependent hash code for this Object
263    * @since 1.1
264    */
265   public static native int identityHashCode(Object o);
266
267   /**
268    * Get all the system properties at once. A security check may be performed,
269    * <code>checkPropertiesAccess</code>. Note that a security manager may
270    * allow getting a single property, but not the entire group.
271    *
272    * <p>The required properties include:
273    * <dl>
274    * <dt>java.version</dt>         <dd>Java version number</dd>
275    * <dt>java.vendor</dt>          <dd>Java vendor specific string</dd>
276    * <dt>java.vendor.url</dt>      <dd>Java vendor URL</dd>
277    * <dt>java.home</dt>            <dd>Java installation directory</dd>
278    * <dt>java.vm.specification.version</dt> <dd>VM Spec version</dd>
279    * <dt>java.vm.specification.vendor</dt>  <dd>VM Spec vendor</dd>
280    * <dt>java.vm.specification.name</dt>    <dd>VM Spec name</dd>
281    * <dt>java.vm.version</dt>      <dd>VM implementation version</dd>
282    * <dt>java.vm.vendor</dt>       <dd>VM implementation vendor</dd>
283    * <dt>java.vm.name</dt>         <dd>VM implementation name</dd>
284    * <dt>java.specification.version</dt>    <dd>Java Runtime Environment version</dd>
285    * <dt>java.specification.vendor</dt>     <dd>Java Runtime Environment vendor</dd>
286    * <dt>java.specification.name</dt>       <dd>Java Runtime Environment name</dd>
287    * <dt>java.class.version</dt>   <dd>Java class version number</dd>
288    * <dt>java.class.path</dt>      <dd>Java classpath</dd>
289    * <dt>java.library.path</dt>    <dd>Path for finding Java libraries</dd>
290    * <dt>java.io.tmpdir</dt>       <dd>Default temp file path</dd>
291    * <dt>java.compiler</dt>        <dd>Name of JIT to use</dd>
292    * <dt>java.ext.dirs</dt>        <dd>Java extension path</dd>
293    * <dt>os.name</dt>              <dd>Operating System Name</dd>
294    * <dt>os.arch</dt>              <dd>Operating System Architecture</dd>
295    * <dt>os.version</dt>           <dd>Operating System Version</dd>
296    * <dt>file.separator</dt>       <dd>File separator ("/" on Unix)</dd>
297    * <dt>path.separator</dt>       <dd>Path separator (":" on Unix)</dd>
298    * <dt>line.separator</dt>       <dd>Line separator ("\n" on Unix)</dd>
299    * <dt>user.name</dt>            <dd>User account name</dd>
300    * <dt>user.home</dt>            <dd>User home directory</dd>
301    * <dt>user.dir</dt>             <dd>User's current working directory</dd>
302    * </dl>
303    *
304    * In addition, gnu defines several other properties, where ? stands for
305    * each character in '0' through '9':
306    * <dl>
307    * <dt>gnu.classpath.home</dt>         <dd>Path to the classpath libraries.</dd>
308    * <dt>gnu.classpath.version</dt>      <dd>Version of the classpath libraries.</dd>
309    * <dt>gnu.classpath.vm.shortname</dt> <dd>Succinct version of the VM name;
310    *     used for finding property files in file system</dd>
311    * <dt>gnu.classpath.home.url</dt>     <dd> Base URL; used for finding
312    *     property files in file system</dd>
313    * <dt>gnu.cpu.endian</dt>             <dd>big or little</dd>
314    * <dt>gnu.java.io.encoding_scheme_alias.ISO-8859-?</dt>   <dd>8859_?</dd>
315    * <dt>gnu.java.io.encoding_scheme_alias.iso-8859-?</dt>   <dd>8859_?</dd>
316    * <dt>gnu.java.io.encoding_scheme_alias.iso8859_?</dt>    <dd>8859_?</dd>
317    * <dt>gnu.java.io.encoding_scheme_alias.iso-latin-_?</dt> <dd>8859_?</dd>
318    * <dt>gnu.java.io.encoding_scheme_alias.latin?</dt>       <dd>8859_?</dd>
319    * <dt>gnu.java.io.encoding_scheme_alias.UTF-8</dt>        <dd>UTF8</dd>
320    * <dt>gnu.java.io.encoding_scheme_alias.utf-8</dt>        <dd>UTF8</dd>
321    * </dl>
322    *
323    * @return the system properties, will never be null
324    * @throws SecurityException if permission is denied
325    */
326   public static Properties getProperties()
327   {
328     SecurityManager sm = SecurityManager.current; // Be thread-safe.
329     if (sm != null)
330       sm.checkPropertiesAccess();
331     return SystemProperties.getProperties();
332   }
333
334   /**
335    * Set all the system properties at once. A security check may be performed,
336    * <code>checkPropertiesAccess</code>. Note that a security manager may
337    * allow setting a single property, but not the entire group. An argument
338    * of null resets the properties to the startup default.
339    *
340    * @param properties the new set of system properties
341    * @throws SecurityException if permission is denied
342    */
343   public static void setProperties(Properties properties)
344   {
345     SecurityManager sm = SecurityManager.current; // Be thread-safe.
346     if (sm != null)
347       sm.checkPropertiesAccess();
348     SystemProperties.setProperties(properties);
349   }
350
351   /**
352    * Get a single system property by name. A security check may be performed,
353    * <code>checkPropertyAccess(key)</code>.
354    *
355    * @param key the name of the system property to get
356    * @return the property, or null if not found
357    * @throws SecurityException if permission is denied
358    * @throws NullPointerException if key is null
359    * @throws IllegalArgumentException if key is ""
360    */
361   public static String getProperty(String key)
362   {
363     SecurityManager sm = SecurityManager.current; // Be thread-safe.
364     if (sm != null)
365       sm.checkPropertyAccess(key);
366     else if (key.length() == 0)
367       throw new IllegalArgumentException("key can't be empty");
368     return SystemProperties.getProperty(key);
369   }
370
371   /**
372    * Get a single system property by name. A security check may be performed,
373    * <code>checkPropertyAccess(key)</code>.
374    *
375    * @param key the name of the system property to get
376    * @param def the default
377    * @return the property, or def if not found
378    * @throws SecurityException if permission is denied
379    * @throws NullPointerException if key is null
380    * @throws IllegalArgumentException if key is ""
381    */
382   public static String getProperty(String key, String def)
383   {
384     SecurityManager sm = SecurityManager.current; // Be thread-safe.
385     if (sm != null)
386       sm.checkPropertyAccess(key);
387     return SystemProperties.getProperty(key, def);
388   }
389
390   /**
391    * Set a single system property by name. A security check may be performed,
392    * <code>checkPropertyAccess(key, "write")</code>.
393    *
394    * @param key the name of the system property to set
395    * @param value the new value
396    * @return the previous value, or null
397    * @throws SecurityException if permission is denied
398    * @throws NullPointerException if key is null
399    * @throws IllegalArgumentException if key is ""
400    * @since 1.2
401    */
402   public static String setProperty(String key, String value)
403   {
404     SecurityManager sm = SecurityManager.current; // Be thread-safe.
405     if (sm != null)
406       sm.checkPermission(new PropertyPermission(key, "write"));
407     return SystemProperties.setProperty(key, value);
408   }
409
410   /**
411    * Remove a single system property by name. A security check may be
412    * performed, <code>checkPropertyAccess(key, "write")</code>.
413    *
414    * @param key the name of the system property to remove
415    * @return the previous value, or null
416    * @throws SecurityException if permission is denied
417    * @throws NullPointerException if key is null
418    * @throws IllegalArgumentException if key is ""
419    * @since 1.5
420    */
421   public static String clearProperty(String key)
422   {
423     SecurityManager sm = SecurityManager.current; // Be thread-safe.
424     if (sm != null)
425       sm.checkPermission(new PropertyPermission(key, "write"));
426     // This handles both the null pointer exception and the illegal
427     // argument exception.
428     if (key.length() == 0)
429       throw new IllegalArgumentException("key can't be empty");
430     return SystemProperties.remove(key);
431   }
432
433   /**
434    * Gets the value of an environment variable.
435    *
436    * @param name the name of the environment variable
437    * @return the string value of the variable or null when the
438    *         environment variable is not defined.
439    * @throws NullPointerException
440    * @throws SecurityException if permission is denied
441    * @since 1.5
442    * @specnote This method was deprecated in some JDK releases, but
443    *           was restored in 1.5.
444    */
445   public static String getenv(String name)
446   {
447     if (name == null)
448       throw new NullPointerException();
449     SecurityManager sm = SecurityManager.current; // Be thread-safe.
450     if (sm != null)
451       sm.checkPermission(new RuntimePermission("getenv." + name));
452     return getenv0(name);
453   }
454
455   /**
456    * <p>
457    * Returns an unmodifiable view of the system environment variables.
458    * If the underlying system does not support environment variables,
459    * an empty map is returned.
460    * </p>
461    * <p>
462    * The returned map is read-only and does not accept queries using
463    * null keys or values, or those of a type other than <code>String</code>.
464    * Attempts to modify the map will throw an
465    * <code>UnsupportedOperationException</code>, while attempts
466    * to pass in a null value will throw a
467    * <code>NullPointerException</code>.  Types other than <code>String</code>
468    * throw a <code>ClassCastException</code>.
469    * </p>
470    * <p>
471    * As the returned map is generated using data from the underlying
472    * platform, it may not comply with the <code>equals()</code>
473    * and <code>hashCode()</code> contracts.  It is also likely that
474    * the keys of this map will be case-sensitive.
475    * </p>
476    * <p>
477    * Use of this method may require a security check for the
478    * RuntimePermission "getenv.*".
479    * </p>
480    *
481    * @return a map of the system environment variables.
482    * @throws SecurityException if the checkPermission method of
483    *         an installed security manager prevents access to
484    *         the system environment variables.
485    * @since 1.5
486    */
487   public static Map<String, String> getenv()
488   {
489     SecurityManager sm = SecurityManager.current; // Be thread-safe.
490     if (sm != null)
491       sm.checkPermission(new RuntimePermission("getenv.*"));
492     if (environmentMap == null)
493       {
494         // List<String> environ = (List<String>)VMSystem.environ();
495         // FIXME
496         List<String> environ = new ArrayList<String>();
497         Map<String,String> variables = new EnvironmentMap();
498         for (String pair : environ)
499           {
500             String[] parts = pair.split("=");
501             variables.put(parts[0], parts[1]);
502           }
503         environmentMap = Collections.unmodifiableMap(variables);
504       }
505     return environmentMap;
506   }
507
508   /**
509    * Terminate the Virtual Machine. This just calls
510    * <code>Runtime.getRuntime().exit(status)</code>, and never returns.
511    * Obviously, a security check is in order, <code>checkExit</code>.
512    *
513    * @param status the exit status; by convention non-zero is abnormal
514    * @throws SecurityException if permission is denied
515    * @see Runtime#exit(int)
516    */
517   public static void exit(int status)
518   {
519     Runtime.getRuntime().exit(status);
520   }
521
522   /**
523    * Calls the garbage collector. This is only a hint, and it is up to the
524    * implementation what this hint suggests, but it usually causes a
525    * best-effort attempt to reclaim unused memory from discarded objects.
526    * This calls <code>Runtime.getRuntime().gc()</code>.
527    *
528    * @see Runtime#gc()
529    */
530   public static void gc()
531   {
532     Runtime.getRuntime().gc();
533   }
534
535   /**
536    * Runs object finalization on pending objects. This is only a hint, and
537    * it is up to the implementation what this hint suggests, but it usually
538    * causes a best-effort attempt to run finalizers on all objects ready
539    * to be reclaimed. This calls
540    * <code>Runtime.getRuntime().runFinalization()</code>.
541    *
542    * @see Runtime#runFinalization()
543    */
544   public static void runFinalization()
545   {
546     Runtime.getRuntime().runFinalization();
547   }
548
549   /**
550    * Tell the Runtime whether to run finalization before exiting the
551    * JVM.  This is inherently unsafe in multi-threaded applications,
552    * since it can force initialization on objects which are still in use
553    * by live threads, leading to deadlock; therefore this is disabled by
554    * default. There may be a security check, <code>checkExit(0)</code>. This
555    * calls <code>Runtime.getRuntime().runFinalizersOnExit()</code>.
556    *
557    * @param finalizeOnExit whether to run finalizers on exit
558    * @throws SecurityException if permission is denied
559    * @see Runtime#runFinalizersOnExit()
560    * @since 1.1
561    * @deprecated never rely on finalizers to do a clean, thread-safe,
562    *             mop-up from your code
563    */
564   public static void runFinalizersOnExit(boolean finalizeOnExit)
565   {
566     Runtime.getRuntime().runFinalizersOnExit(finalizeOnExit);
567   }
568
569   /**
570    * Load a code file using its explicit system-dependent filename. A security
571    * check may be performed, <code>checkLink</code>. This just calls
572    * <code>Runtime.getRuntime().load(filename)</code>.
573    *
574    * <p>
575    * The library is loaded using the class loader associated with the
576    * class associated with the invoking method.
577    *
578    * @param filename the code file to load
579    * @throws SecurityException if permission is denied
580    * @throws UnsatisfiedLinkError if the file cannot be loaded
581    * @see Runtime#load(String)
582    */
583   public static void load(String filename)
584   {
585     Runtime.getRuntime().load(filename);
586   }
587
588   /**
589    * Load a library using its explicit system-dependent filename. A security
590    * check may be performed, <code>checkLink</code>. This just calls
591    * <code>Runtime.getRuntime().load(filename)</code>.
592    *
593    * <p>
594    * The library is loaded using the class loader associated with the
595    * class associated with the invoking method.
596    *
597    * @param libname the library file to load
598    * @throws SecurityException if permission is denied
599    * @throws UnsatisfiedLinkError if the file cannot be loaded
600    * @see Runtime#load(String)
601    */
602   public static void loadLibrary(String libname)
603   {
604     Runtime.getRuntime().loadLibrary(libname);
605   }
606
607   /**
608    * Convert a library name to its platform-specific variant.
609    *
610    * @param libname the library name, as used in <code>loadLibrary</code>
611    * @return the platform-specific mangling of the name
612    * @since 1.2
613    */
614   public static String mapLibraryName(String libname)
615   {
616     // XXX Fix this!!!!
617     return Runtime.nativeGetLibname("", libname);
618   }
619
620   /**
621    * Set {@link #in} to a new InputStream.
622    *
623    * @param in the new InputStream
624    * @see #setIn(InputStream)
625    */
626   private static native void setIn0(InputStream in);
627
628   /**
629    * Set {@link #out} to a new PrintStream.
630    *
631    * @param out the new PrintStream
632    * @see #setOut(PrintStream)
633    */
634   private static native void setOut0(PrintStream out);
635
636   /**
637    * Set {@link #err} to a new PrintStream.
638    *
639    * @param err the new PrintStream
640    * @see #setErr(PrintStream)
641    */
642   private static native void setErr0(PrintStream err);
643
644   /**
645    * Gets the value of an environment variable.
646    *
647    * @see #getenv(String)
648    */
649   static native String getenv0(String name);
650
651
652   /**
653    * This is a specialised <code>Collection</code>, providing
654    * the necessary provisions for the collections used by the
655    * environment variable map.  Namely, it prevents
656    * querying anything but <code>String</code>s.
657    *
658    * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
659    */
660   private static class EnvironmentCollection
661     extends AbstractCollection<String>
662   {
663
664     /**
665      * The wrapped collection.
666      */
667     protected Collection<String> c;
668
669     /**
670      * Constructs a new environment collection, which
671      * wraps the elements of the supplied collection.
672      *
673      * @param coll the collection to use as a base for
674      *             this collection.
675      */
676     public EnvironmentCollection(Collection<String> coll)
677     {
678       c = coll;
679     }
680         
681     /**
682      * Blocks queries containing a null object or an object which
683      * isn't of type <code>String</code>.  All other queries
684      * are forwarded to the underlying collection.
685      *
686      * @param obj the object to look for.
687      * @return true if the object exists in the collection.
688      * @throws NullPointerException if the specified object is null.
689      * @throws ClassCastException if the specified object is not a String.
690      */
691     public boolean contains(Object obj)
692     {
693       if (obj == null)
694           throw new
695             NullPointerException("This collection does not support " +
696                                  "null values.");
697       if (!(obj instanceof String))
698           throw new
699             ClassCastException("This collection only supports Strings.");
700       return c.contains(obj);
701     }
702     
703     /**
704      * Blocks queries where the collection contains a null object or
705      * an object which isn't of type <code>String</code>.  All other
706      * queries are forwarded to the underlying collection.
707      *
708      * @param coll the collection of objects to look for.
709      * @return true if the collection contains all elements in the collection.
710      * @throws NullPointerException if the collection is null.
711      * @throws NullPointerException if any collection entry is null.
712      * @throws ClassCastException if any collection entry is not a String.
713      */
714     public boolean containsAll(Collection<?> coll)
715     {
716       for (Object o: coll)
717         {
718           if (o == null)
719               throw new
720                 NullPointerException("This collection does not support " +
721                                      "null values.");
722           if (!(o instanceof String))
723               throw new
724                 ClassCastException("This collection only supports Strings.");
725         }
726       return c.containsAll(coll);
727     }
728
729     /**
730      * This returns an iterator over the map elements, with the
731      * same provisions as for the collection and underlying map.
732      *
733      * @return an iterator over the map elements.
734      */
735     public Iterator<String> iterator()
736     {
737       return c.iterator();
738     }
739     
740     /**
741      * Blocks the removal of elements from the collection.
742      *
743      * @return true if the removal was sucessful.
744      * @throws NullPointerException if the collection is null.
745      * @throws NullPointerException if any collection entry is null.
746      * @throws ClassCastException if any collection entry is not a String.
747      */
748     public boolean remove(Object key)
749     {
750       if (key == null)
751           throw new
752             NullPointerException("This collection does not support " +
753                                  "null values.");
754       if (!(key instanceof String))
755           throw new
756             ClassCastException("This collection only supports Strings.");
757       return c.contains(key);
758     }   
759         
760     /**
761      * Blocks the removal of all elements in the specified
762      * collection from the collection.
763      *
764      * @param coll the collection of elements to remove.
765      * @return true if the elements were removed.
766      * @throws NullPointerException if the collection is null.
767      * @throws NullPointerException if any collection entry is null.
768      * @throws ClassCastException if any collection entry is not a String.
769      */
770     public boolean removeAll(Collection<?> coll)
771     {
772       for (Object o: coll)
773         {
774           if (o == null)
775               throw new
776                 NullPointerException("This collection does not support " +
777                                      "null values.");
778           if (!(o instanceof String))
779             throw new
780               ClassCastException("This collection only supports Strings.");
781         }
782       return c.removeAll(coll);
783     }
784     
785     /**
786      * Blocks the retention of all elements in the specified
787      * collection from the collection.
788      *
789      * @param c the collection of elements to retain.
790      * @return true if the other elements were removed.
791      * @throws NullPointerException if the collection is null.
792      * @throws NullPointerException if any collection entry is null.
793      * @throws ClassCastException if any collection entry is not a String.
794      */
795     public boolean retainAll(Collection<?> coll)
796     {
797       for (Object o: coll)
798         {
799           if (o == null)
800               throw new
801                 NullPointerException("This collection does not support " +
802                                      "null values.");
803           if (!(o instanceof String))
804             throw new
805               ClassCastException("This collection only supports Strings.");
806         }
807       return c.containsAll(coll);
808     }
809
810     /**
811      * This simply calls the same method on the wrapped
812      * collection.
813      *
814      * @return the size of the underlying collection.
815      */
816     public int size()
817     {
818       return c.size();
819     }
820
821   } // class EnvironmentCollection<String>
822
823   /**
824    * This is a specialised <code>HashMap</code>, which
825    * prevents the addition or querying of anything other than
826    * <code>String</code> objects. 
827    *
828    * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
829    */
830   private static class EnvironmentMap
831     extends HashMap<String,String>
832   {
833     
834     /**
835      * Cache the entry set.
836      */
837     private transient Set<Map.Entry<String,String>> entries;
838
839     /**
840      * Cache the key set.
841      */
842     private transient Set<String> keys;
843
844     /**
845      * Cache the value collection.
846      */
847     private transient Collection<String> values;
848
849     /**
850      * Constructs a new empty <code>EnvironmentMap</code>.
851      */
852     EnvironmentMap()
853     {
854       super();
855     }
856     
857     /**
858      * Blocks queries containing a null key or one which is not
859      * of type <code>String</code>.  All other queries
860      * are forwarded to the superclass.
861      *
862      * @param key the key to look for in the map.
863      * @return true if the key exists in the map.
864      * @throws NullPointerException if the specified key is null.
865      */
866     public boolean containsKey(Object key)
867     {
868       if (key == null)
869         throw new
870           NullPointerException("This map does not support null keys.");
871       if (!(key instanceof String))
872         throw new
873           ClassCastException("This map only allows queries using Strings.");
874       return super.containsKey(key);
875     }
876     
877     /**
878      * Blocks queries using a null or non-<code>String</code> value.
879      * All other queries are forwarded to the superclass.
880      *
881      * @param value the value to look for in the map.
882      * @return true if the value exists in the map.
883      * @throws NullPointerException if the specified value is null.
884      */
885     public boolean containsValue(Object value)
886     {
887       if (value == null)
888           throw new
889             NullPointerException("This map does not support null values.");
890       if (!(value instanceof String))
891         throw new
892           ClassCastException("This map only allows queries using Strings.");
893       return super.containsValue(value);
894     }
895
896     /**
897      * Returns a set view of the map entries, with the same
898      * provisions as for the underlying map.
899      *
900      * @return a set containing the map entries.
901      */
902     public Set<Map.Entry<String,String>> entrySet()
903     {
904       if (entries == null)
905         entries = super.entrySet();
906       return entries;
907     }
908
909     /**
910      * Blocks queries containing a null or non-<code>String</code> key.
911      * All other queries are passed on to the superclass.
912      *
913      * @param key the key to retrieve the value for.
914      * @return the value associated with the given key.
915      * @throws NullPointerException if the specified key is null.
916      * @throws ClassCastException if the specified key is not a String.
917      */
918     public String get(Object key)
919     {
920       if (key == null)
921         throw new
922           NullPointerException("This map does not support null keys.");
923       if (!(key instanceof String))
924         throw new
925           ClassCastException("This map only allows queries using Strings.");
926       return super.get(key);
927     }
928     
929     /**
930      * Returns a set view of the keys, with the same
931      * provisions as for the underlying map.
932      *
933      * @return a set containing the keys.
934      */
935     public Set<String> keySet()
936     {
937       if (keys == null)
938         keys = new EnvironmentSet(super.keySet());
939       return keys;
940     }
941     
942     /**
943      * Removes a key-value pair from the map.  The queried key may not
944      * be null or of a type other than a <code>String</code>.
945      *
946      * @param key the key of the entry to remove.
947      * @return the removed value.
948      * @throws NullPointerException if the specified key is null.
949      * @throws ClassCastException if the specified key is not a String.
950      */
951     public String remove(Object key)
952     {
953       if (key == null)
954         throw new
955           NullPointerException("This map does not support null keys.");
956       if (!(key instanceof String))
957         throw new
958           ClassCastException("This map only allows queries using Strings.");
959       return super.remove(key);
960     }
961     
962     /**
963      * Returns a collection view of the values, with the same
964      * provisions as for the underlying map.
965      *
966      * @return a collection containing the values.
967      */
968     public Collection<String> values()
969     {
970       if (values == null)
971         values = new EnvironmentCollection(super.values());
972       return values;
973     }
974     
975   }
976
977   /**
978    * This is a specialised <code>Set</code>, providing
979    * the necessary provisions for the collections used by the
980    * environment variable map.  Namely, it prevents
981    * modifications and the use of queries with null
982    * or non-<code>String</code> values.
983    *
984    * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
985    */
986   private static class EnvironmentSet
987     extends EnvironmentCollection
988     implements Set<String>
989   {
990
991     /**
992      * Constructs a new environment set, which
993      * wraps the elements of the supplied set.
994      *
995      * @param set the set to use as a base for
996      *             this set.
997      */
998     public EnvironmentSet(Set<String> set)
999     {
1000       super(set);
1001     }
1002
1003     /**
1004      * This simply calls the same method on the wrapped
1005      * collection.
1006      *
1007      * @param obj the object to compare with.
1008      * @return true if the two objects are equal.
1009      */
1010     public boolean equals(Object obj)
1011     {
1012       return c.equals(obj);
1013     }
1014
1015     /**
1016      * This simply calls the same method on the wrapped
1017      * collection.
1018      *
1019      * @return the hashcode of the collection.
1020      */
1021     public int hashCode()
1022     {
1023       return c.hashCode();
1024     }
1025
1026   } // class EnvironmentSet<String>
1027
1028 } // class System