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.
5 This file is part of GNU Classpath.
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)
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.
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
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
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. */
42 import gnu.classpath.SystemProperties;
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;
60 import java.util.Properties;
61 import java.util.PropertyPermission;
64 * System represents system-wide resources; things that represent the
65 * general environment. As such, all methods are static.
68 * @author Eric Blake (ebb9@email.byu.edu)
70 * @status still missing 1.4 functionality
72 public final class System
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.
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.
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,
87 public static final InputStream in
88 = new BufferedInputStream(new FileInputStream(FileDescriptor.in));
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.
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
99 public static final PrintStream out
100 = new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.out)), true);
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.
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
111 public static final PrintStream err
112 = new PrintStream(new BufferedOutputStream(new FileOutputStream(FileDescriptor.err)), true);
115 * A cached copy of the environment variable map.
117 private static Map<String,String> environmentMap;
120 * This class is uninstantiable.
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>.
131 * @param in the new InputStream
132 * @throws SecurityException if permission is denied
135 public static void setIn(InputStream in)
137 SecurityManager sm = SecurityManager.current; // Be thread-safe.
139 sm.checkPermission(new RuntimePermission("setIO"));
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>.
148 * @param out the new PrintStream
149 * @throws SecurityException if permission is denied
152 public static void setOut(PrintStream out)
154 SecurityManager sm = SecurityManager.current; // Be thread-safe.
156 sm.checkPermission(new RuntimePermission("setIO"));
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>.
166 * @param err the new PrintStream
167 * @throws SecurityException if permission is denied
170 public static void setErr(PrintStream err)
172 SecurityManager sm = SecurityManager.current; // Be thread-safe.
174 sm.checkPermission(new RuntimePermission("setIO"));
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.
184 * @param sm the new SecurityManager
185 * @throws SecurityException if permission is denied
187 public static synchronized void setSecurityManager(SecurityManager sm)
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;
199 * Get the current SecurityManager. If the SecurityManager has not been
200 * set yet, then this method returns null.
202 * @return the current SecurityManager, or null
204 public static SecurityManager getSecurityManager()
206 return SecurityManager.current;
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).
214 * @return the current time
215 * @see java.util.Date
217 public static native long currentTimeMillis();
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.
226 public static native long nanoTime();
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.
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
248 * @throws IndexOutOfBoundsException if len is negative, or if the start or
249 * end copy position in either array is out of bounds
251 public static native void arraycopy(Object src, int srcStart,
252 Object dest, int destStart, int len);
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.
261 * @param o the Object to get the hash code for
262 * @return the VM-dependent hash code for this Object
265 public static native int identityHashCode(Object o);
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.
272 * <p>The required properties include:
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>
304 * In addition, gnu defines several other properties, where ? stands for
305 * each character in '0' through '9':
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>
323 * @return the system properties, will never be null
324 * @throws SecurityException if permission is denied
326 public static Properties getProperties()
328 SecurityManager sm = SecurityManager.current; // Be thread-safe.
330 sm.checkPropertiesAccess();
331 return SystemProperties.getProperties();
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.
340 * @param properties the new set of system properties
341 * @throws SecurityException if permission is denied
343 public static void setProperties(Properties properties)
345 SecurityManager sm = SecurityManager.current; // Be thread-safe.
347 sm.checkPropertiesAccess();
348 SystemProperties.setProperties(properties);
352 * Get a single system property by name. A security check may be performed,
353 * <code>checkPropertyAccess(key)</code>.
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 ""
361 public static String getProperty(String key)
363 SecurityManager sm = SecurityManager.current; // Be thread-safe.
365 sm.checkPropertyAccess(key);
366 else if (key.length() == 0)
367 throw new IllegalArgumentException("key can't be empty");
368 return SystemProperties.getProperty(key);
372 * Get a single system property by name. A security check may be performed,
373 * <code>checkPropertyAccess(key)</code>.
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 ""
382 public static String getProperty(String key, String def)
384 SecurityManager sm = SecurityManager.current; // Be thread-safe.
386 sm.checkPropertyAccess(key);
387 return SystemProperties.getProperty(key, def);
391 * Set a single system property by name. A security check may be performed,
392 * <code>checkPropertyAccess(key, "write")</code>.
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 ""
402 public static String setProperty(String key, String value)
404 SecurityManager sm = SecurityManager.current; // Be thread-safe.
406 sm.checkPermission(new PropertyPermission(key, "write"));
407 return SystemProperties.setProperty(key, value);
411 * Remove a single system property by name. A security check may be
412 * performed, <code>checkPropertyAccess(key, "write")</code>.
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 ""
421 public static String clearProperty(String key)
423 SecurityManager sm = SecurityManager.current; // Be thread-safe.
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);
434 * Gets the value of an environment variable.
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
442 * @specnote This method was deprecated in some JDK releases, but
443 * was restored in 1.5.
445 public static String getenv(String name)
448 throw new NullPointerException();
449 SecurityManager sm = SecurityManager.current; // Be thread-safe.
451 sm.checkPermission(new RuntimePermission("getenv." + name));
452 return getenv0(name);
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.
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>.
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.
477 * Use of this method may require a security check for the
478 * RuntimePermission "getenv.*".
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.
487 public static Map<String, String> getenv()
489 SecurityManager sm = SecurityManager.current; // Be thread-safe.
491 sm.checkPermission(new RuntimePermission("getenv.*"));
492 if (environmentMap == null)
494 // List<String> environ = (List<String>)VMSystem.environ();
496 List<String> environ = new ArrayList<String>();
497 Map<String,String> variables = new EnvironmentMap();
498 for (String pair : environ)
500 String[] parts = pair.split("=");
501 variables.put(parts[0], parts[1]);
503 environmentMap = Collections.unmodifiableMap(variables);
505 return environmentMap;
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>.
513 * @param status the exit status; by convention non-zero is abnormal
514 * @throws SecurityException if permission is denied
515 * @see Runtime#exit(int)
517 public static void exit(int status)
519 Runtime.getRuntime().exit(status);
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>.
530 public static void gc()
532 Runtime.getRuntime().gc();
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>.
542 * @see Runtime#runFinalization()
544 public static void runFinalization()
546 Runtime.getRuntime().runFinalization();
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>.
557 * @param finalizeOnExit whether to run finalizers on exit
558 * @throws SecurityException if permission is denied
559 * @see Runtime#runFinalizersOnExit()
561 * @deprecated never rely on finalizers to do a clean, thread-safe,
562 * mop-up from your code
564 public static void runFinalizersOnExit(boolean finalizeOnExit)
566 Runtime.getRuntime().runFinalizersOnExit(finalizeOnExit);
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>.
575 * The library is loaded using the class loader associated with the
576 * class associated with the invoking method.
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)
583 public static void load(String filename)
585 Runtime.getRuntime().load(filename);
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>.
594 * The library is loaded using the class loader associated with the
595 * class associated with the invoking method.
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)
602 public static void loadLibrary(String libname)
604 Runtime.getRuntime().loadLibrary(libname);
608 * Convert a library name to its platform-specific variant.
610 * @param libname the library name, as used in <code>loadLibrary</code>
611 * @return the platform-specific mangling of the name
614 public static String mapLibraryName(String libname)
617 return Runtime.nativeGetLibname("", libname);
621 * Set {@link #in} to a new InputStream.
623 * @param in the new InputStream
624 * @see #setIn(InputStream)
626 private static native void setIn0(InputStream in);
629 * Set {@link #out} to a new PrintStream.
631 * @param out the new PrintStream
632 * @see #setOut(PrintStream)
634 private static native void setOut0(PrintStream out);
637 * Set {@link #err} to a new PrintStream.
639 * @param err the new PrintStream
640 * @see #setErr(PrintStream)
642 private static native void setErr0(PrintStream err);
645 * Gets the value of an environment variable.
647 * @see #getenv(String)
649 static native String getenv0(String name);
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.
658 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
660 private static class EnvironmentCollection
661 extends AbstractCollection<String>
665 * The wrapped collection.
667 protected Collection<String> c;
670 * Constructs a new environment collection, which
671 * wraps the elements of the supplied collection.
673 * @param coll the collection to use as a base for
676 public EnvironmentCollection(Collection<String> coll)
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.
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.
691 public boolean contains(Object obj)
695 NullPointerException("This collection does not support " +
697 if (!(obj instanceof String))
699 ClassCastException("This collection only supports Strings.");
700 return c.contains(obj);
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.
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.
714 public boolean containsAll(Collection<?> coll)
720 NullPointerException("This collection does not support " +
722 if (!(o instanceof String))
724 ClassCastException("This collection only supports Strings.");
726 return c.containsAll(coll);
730 * This returns an iterator over the map elements, with the
731 * same provisions as for the collection and underlying map.
733 * @return an iterator over the map elements.
735 public Iterator<String> iterator()
741 * Blocks the removal of elements from the collection.
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.
748 public boolean remove(Object key)
752 NullPointerException("This collection does not support " +
754 if (!(key instanceof String))
756 ClassCastException("This collection only supports Strings.");
757 return c.contains(key);
761 * Blocks the removal of all elements in the specified
762 * collection from the collection.
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.
770 public boolean removeAll(Collection<?> coll)
776 NullPointerException("This collection does not support " +
778 if (!(o instanceof String))
780 ClassCastException("This collection only supports Strings.");
782 return c.removeAll(coll);
786 * Blocks the retention of all elements in the specified
787 * collection from the collection.
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.
795 public boolean retainAll(Collection<?> coll)
801 NullPointerException("This collection does not support " +
803 if (!(o instanceof String))
805 ClassCastException("This collection only supports Strings.");
807 return c.containsAll(coll);
811 * This simply calls the same method on the wrapped
814 * @return the size of the underlying collection.
821 } // class EnvironmentCollection<String>
824 * This is a specialised <code>HashMap</code>, which
825 * prevents the addition or querying of anything other than
826 * <code>String</code> objects.
828 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
830 private static class EnvironmentMap
831 extends HashMap<String,String>
835 * Cache the entry set.
837 private transient Set<Map.Entry<String,String>> entries;
842 private transient Set<String> keys;
845 * Cache the value collection.
847 private transient Collection<String> values;
850 * Constructs a new empty <code>EnvironmentMap</code>.
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.
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.
866 public boolean containsKey(Object key)
870 NullPointerException("This map does not support null keys.");
871 if (!(key instanceof String))
873 ClassCastException("This map only allows queries using Strings.");
874 return super.containsKey(key);
878 * Blocks queries using a null or non-<code>String</code> value.
879 * All other queries are forwarded to the superclass.
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.
885 public boolean containsValue(Object value)
889 NullPointerException("This map does not support null values.");
890 if (!(value instanceof String))
892 ClassCastException("This map only allows queries using Strings.");
893 return super.containsValue(value);
897 * Returns a set view of the map entries, with the same
898 * provisions as for the underlying map.
900 * @return a set containing the map entries.
902 public Set<Map.Entry<String,String>> entrySet()
905 entries = super.entrySet();
910 * Blocks queries containing a null or non-<code>String</code> key.
911 * All other queries are passed on to the superclass.
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.
918 public String get(Object key)
922 NullPointerException("This map does not support null keys.");
923 if (!(key instanceof String))
925 ClassCastException("This map only allows queries using Strings.");
926 return super.get(key);
930 * Returns a set view of the keys, with the same
931 * provisions as for the underlying map.
933 * @return a set containing the keys.
935 public Set<String> keySet()
938 keys = new EnvironmentSet(super.keySet());
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>.
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.
951 public String remove(Object key)
955 NullPointerException("This map does not support null keys.");
956 if (!(key instanceof String))
958 ClassCastException("This map only allows queries using Strings.");
959 return super.remove(key);
963 * Returns a collection view of the values, with the same
964 * provisions as for the underlying map.
966 * @return a collection containing the values.
968 public Collection<String> values()
971 values = new EnvironmentCollection(super.values());
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.
984 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
986 private static class EnvironmentSet
987 extends EnvironmentCollection
988 implements Set<String>
992 * Constructs a new environment set, which
993 * wraps the elements of the supplied set.
995 * @param set the set to use as a base for
998 public EnvironmentSet(Set<String> set)
1004 * This simply calls the same method on the wrapped
1007 * @param obj the object to compare with.
1008 * @return true if the two objects are equal.
1010 public boolean equals(Object obj)
1012 return c.equals(obj);
1016 * This simply calls the same method on the wrapped
1019 * @return the hashcode of the collection.
1021 public int hashCode()
1023 return c.hashCode();
1026 } // class EnvironmentSet<String>