1 /* System.java -- useful methods to interface with the system
2 Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
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;
43 import gnu.classpath.VMStackWalker;
45 import java.io.InputStream;
46 import java.io.PrintStream;
47 import java.util.AbstractCollection;
48 import java.util.Collection;
49 import java.util.Collections;
50 import java.util.HashMap;
51 import java.util.Iterator;
52 import java.util.List;
55 import java.util.Properties;
56 import java.util.PropertyPermission;
59 * System represents system-wide resources; things that represent the
60 * general environment. As such, all methods are static.
63 * @author Eric Blake (ebb9@email.byu.edu)
65 * @status still missing 1.4 functionality
67 public final class System
69 // WARNING: System is a CORE class in the bootstrap cycle. See the comments
70 // in vm/reference/java/lang/Runtime for implications of this fact.
73 * The standard InputStream. This is assigned at startup and starts its
74 * life perfectly valid. Although it is marked final, you can change it
75 * using {@link #setIn(InputStream)} through some hefty VM magic.
77 * <p>This corresponds to the C stdin and C++ cin variables, which
78 * typically input from the keyboard, but may be used to pipe input from
79 * other processes or files. That should all be transparent to you,
82 public static final InputStream in = VMSystem.makeStandardInputStream();
85 * The standard output PrintStream. This is assigned at startup and
86 * starts its life perfectly valid. Although it is marked final, you can
87 * change it using {@link #setOut(PrintStream)} through some hefty VM magic.
89 * <p>This corresponds to the C stdout and C++ cout variables, which
90 * typically output normal messages to the screen, but may be used to pipe
91 * output to other processes or files. That should all be transparent to
94 public static final PrintStream out = VMSystem.makeStandardOutputStream();
97 * The standard output PrintStream. This is assigned at startup and
98 * starts its life perfectly valid. Although it is marked final, you can
99 * change it using {@link #setErr(PrintStream)} through some hefty VM magic.
101 * <p>This corresponds to the C stderr and C++ cerr variables, which
102 * typically output error messages to the screen, but may be used to pipe
103 * output to other processes or files. That should all be transparent to
106 public static final PrintStream err = VMSystem.makeStandardErrorStream();
109 * A cached copy of the environment variable map.
111 private static Map<String,String> environmentMap;
114 * This class is uninstantiable.
121 * Set {@link #in} to a new InputStream. This uses some VM magic to change
122 * a "final" variable, so naturally there is a security check,
123 * <code>RuntimePermission("setIO")</code>.
125 * @param in the new InputStream
126 * @throws SecurityException if permission is denied
129 public static void setIn(InputStream in)
131 SecurityManager sm = SecurityManager.current; // Be thread-safe.
133 sm.checkPermission(new RuntimePermission("setIO"));
139 * Set {@link #out} to a new PrintStream. This uses some VM magic to change
140 * a "final" variable, so naturally there is a security check,
141 * <code>RuntimePermission("setIO")</code>.
143 * @param out the new PrintStream
144 * @throws SecurityException if permission is denied
147 public static void setOut(PrintStream out)
149 SecurityManager sm = SecurityManager.current; // Be thread-safe.
151 sm.checkPermission(new RuntimePermission("setIO"));
152 VMSystem.setOut(out);
156 * Set {@link #err} to a new PrintStream. This uses some VM magic to change
157 * a "final" variable, so naturally there is a security check,
158 * <code>RuntimePermission("setIO")</code>.
160 * @param err the new PrintStream
161 * @throws SecurityException if permission is denied
164 public static void setErr(PrintStream err)
166 SecurityManager sm = SecurityManager.current; // Be thread-safe.
168 sm.checkPermission(new RuntimePermission("setIO"));
169 VMSystem.setErr(err);
173 * Set the current SecurityManager. If a security manager already exists,
174 * then <code>RuntimePermission("setSecurityManager")</code> is checked
175 * first. Since this permission is denied by the default security manager,
176 * setting the security manager is often an irreversible action.
178 * <STRONG>Spec Note:</STRONG> Don't ask me, I didn't write it. It looks
179 * pretty vulnerable; whoever gets to the gate first gets to set the policy.
180 * There is probably some way to set the original security manager as a
181 * command line argument to the VM, but I don't know it.
183 * @param sm the new SecurityManager
184 * @throws SecurityException if permission is denied
186 public static synchronized void setSecurityManager(SecurityManager sm)
188 // Implementation note: the field lives in SecurityManager because of
189 // bootstrap initialization issues. This method is synchronized so that
190 // no other thread changes it to null before this thread makes the change.
191 if (SecurityManager.current != null)
192 SecurityManager.current.checkPermission
193 (new RuntimePermission("setSecurityManager"));
195 // java.security.Security's class initialiser loads and parses the
196 // policy files. If it hasn't been run already it will be run
197 // during the first permission check. That initialisation will
198 // fail if a very restrictive security manager is in force, so we
200 if (SecurityManager.current == null)
204 Class.forName("java.security.Security");
206 catch (ClassNotFoundException e)
211 SecurityManager.current = sm;
215 * Get the current SecurityManager. If the SecurityManager has not been
216 * set yet, then this method returns null.
218 * @return the current SecurityManager, or null
220 public static SecurityManager getSecurityManager()
222 return SecurityManager.current;
226 * Get the current time, measured in the number of milliseconds from the
227 * beginning of Jan. 1, 1970. This is gathered from the system clock, with
228 * any attendant incorrectness (it may be timezone dependent).
230 * @return the current time
231 * @see java.util.Date
233 public static long currentTimeMillis()
235 return VMSystem.currentTimeMillis();
240 * Returns the current value of a nanosecond-precise system timer.
241 * The value of the timer is an offset relative to some arbitrary fixed
242 * time, which may be in the future (making the value negative). This
243 * method is useful for timing events where nanosecond precision is
244 * required. This is achieved by calling this method before and after the
245 * event, and taking the difference betweent the two times:
248 * <code>long startTime = System.nanoTime();</code><br />
249 * <code>... <emph>event code</emph> ...</code><br />
250 * <code>long endTime = System.nanoTime();</code><br />
251 * <code>long duration = endTime - startTime;</code><br />
254 * Note that the value is only nanosecond-precise, and not accurate; there
255 * is no guarantee that the difference between two values is really a
256 * nanosecond. Also, the value is prone to overflow if the offset
260 * @return the time of a system timer in nanoseconds.
263 public static long nanoTime()
265 return VMSystem.nanoTime();
269 * Copy one array onto another from <code>src[srcStart]</code> ...
270 * <code>src[srcStart+len-1]</code> to <code>dest[destStart]</code> ...
271 * <code>dest[destStart+len-1]</code>. First, the arguments are validated:
272 * neither array may be null, they must be of compatible types, and the
273 * start and length must fit within both arrays. Then the copying starts,
274 * and proceeds through increasing slots. If src and dest are the same
275 * array, this will appear to copy the data to a temporary location first.
276 * An ArrayStoreException in the middle of copying will leave earlier
277 * elements copied, but later elements unchanged.
279 * @param src the array to copy elements from
280 * @param srcStart the starting position in src
281 * @param dest the array to copy elements to
282 * @param destStart the starting position in dest
283 * @param len the number of elements to copy
284 * @throws NullPointerException if src or dest is null
285 * @throws ArrayStoreException if src or dest is not an array, if they are
286 * not compatible array types, or if an incompatible runtime type
288 * @throws IndexOutOfBoundsException if len is negative, or if the start or
289 * end copy position in either array is out of bounds
291 public static void arraycopy(Object src, int srcStart,
292 Object dest, int destStart, int len)
294 VMSystem.arraycopy(src, srcStart, dest, destStart, len);
298 * Get a hash code computed by the VM for the Object. This hash code will
299 * be the same as Object's hashCode() method. It is usually some
300 * convolution of the pointer to the Object internal to the VM. It
301 * follows standard hash code rules, in that it will remain the same for a
302 * given Object for the lifetime of that Object.
304 * @param o the Object to get the hash code for
305 * @return the VM-dependent hash code for this Object
308 public static int identityHashCode(Object o)
310 return VMSystem.identityHashCode(o);
314 * Get all the system properties at once. A security check may be performed,
315 * <code>checkPropertiesAccess</code>. Note that a security manager may
316 * allow getting a single property, but not the entire group.
318 * <p>The required properties include:
320 * <dt>java.version</dt> <dd>Java version number</dd>
321 * <dt>java.vendor</dt> <dd>Java vendor specific string</dd>
322 * <dt>java.vendor.url</dt> <dd>Java vendor URL</dd>
323 * <dt>java.home</dt> <dd>Java installation directory</dd>
324 * <dt>java.vm.specification.version</dt> <dd>VM Spec version</dd>
325 * <dt>java.vm.specification.vendor</dt> <dd>VM Spec vendor</dd>
326 * <dt>java.vm.specification.name</dt> <dd>VM Spec name</dd>
327 * <dt>java.vm.version</dt> <dd>VM implementation version</dd>
328 * <dt>java.vm.vendor</dt> <dd>VM implementation vendor</dd>
329 * <dt>java.vm.name</dt> <dd>VM implementation name</dd>
330 * <dt>java.specification.version</dt> <dd>Java Runtime Environment version</dd>
331 * <dt>java.specification.vendor</dt> <dd>Java Runtime Environment vendor</dd>
332 * <dt>java.specification.name</dt> <dd>Java Runtime Environment name</dd>
333 * <dt>java.class.version</dt> <dd>Java class version number</dd>
334 * <dt>java.class.path</dt> <dd>Java classpath</dd>
335 * <dt>java.library.path</dt> <dd>Path for finding Java libraries</dd>
336 * <dt>java.io.tmpdir</dt> <dd>Default temp file path</dd>
337 * <dt>java.compiler</dt> <dd>Name of JIT to use</dd>
338 * <dt>java.ext.dirs</dt> <dd>Java extension path</dd>
339 * <dt>os.name</dt> <dd>Operating System Name</dd>
340 * <dt>os.arch</dt> <dd>Operating System Architecture</dd>
341 * <dt>os.version</dt> <dd>Operating System Version</dd>
342 * <dt>file.separator</dt> <dd>File separator ("/" on Unix)</dd>
343 * <dt>path.separator</dt> <dd>Path separator (":" on Unix)</dd>
344 * <dt>line.separator</dt> <dd>Line separator ("\n" on Unix)</dd>
345 * <dt>user.name</dt> <dd>User account name</dd>
346 * <dt>user.home</dt> <dd>User home directory</dd>
347 * <dt>user.dir</dt> <dd>User's current working directory</dd>
350 * In addition, gnu defines several other properties, where ? stands for
351 * each character in '0' through '9':
353 * <dt>gnu.classpath.home</dt> <dd>Path to the classpath libraries.</dd>
354 * <dt>gnu.classpath.version</dt> <dd>Version of the classpath libraries.</dd>
355 * <dt>gnu.classpath.vm.shortname</dt> <dd>Succinct version of the VM name;
356 * used for finding property files in file system</dd>
357 * <dt>gnu.classpath.home.url</dt> <dd> Base URL; used for finding
358 * property files in file system</dd>
359 * <dt>gnu.cpu.endian</dt> <dd>big or little</dd>
360 * <dt>gnu.java.io.encoding_scheme_alias.iso-8859-?</dt> <dd>8859_?</dd>
361 * <dt>gnu.java.io.encoding_scheme_alias.iso8859_?</dt> <dd>8859_?</dd>
362 * <dt>gnu.java.io.encoding_scheme_alias.iso-latin-_?</dt> <dd>8859_?</dd>
363 * <dt>gnu.java.io.encoding_scheme_alias.latin?</dt> <dd>8859_?</dd>
364 * <dt>gnu.java.io.encoding_scheme_alias.utf-8</dt> <dd>UTF8</dd>
365 * <dt>gnu.javax.print.server</dt> <dd>Hostname of external CUPS server.</dd>
368 * @return the system properties, will never be null
369 * @throws SecurityException if permission is denied
371 public static Properties getProperties()
373 SecurityManager sm = SecurityManager.current; // Be thread-safe.
375 sm.checkPropertiesAccess();
376 return SystemProperties.getProperties();
380 * Set all the system properties at once. A security check may be performed,
381 * <code>checkPropertiesAccess</code>. Note that a security manager may
382 * allow setting a single property, but not the entire group. An argument
383 * of null resets the properties to the startup default.
385 * @param properties the new set of system properties
386 * @throws SecurityException if permission is denied
388 public static void setProperties(Properties properties)
390 SecurityManager sm = SecurityManager.current; // Be thread-safe.
392 sm.checkPropertiesAccess();
393 SystemProperties.setProperties(properties);
397 * Get a single system property by name. A security check may be performed,
398 * <code>checkPropertyAccess(key)</code>.
400 * @param key the name of the system property to get
401 * @return the property, or null if not found
402 * @throws SecurityException if permission is denied
403 * @throws NullPointerException if key is null
404 * @throws IllegalArgumentException if key is ""
406 public static String getProperty(String key)
408 SecurityManager sm = SecurityManager.current; // Be thread-safe.
410 sm.checkPropertyAccess(key);
411 if (key.length() == 0)
412 throw new IllegalArgumentException("key can't be empty");
413 return SystemProperties.getProperty(key);
417 * Get a single system property by name. A security check may be performed,
418 * <code>checkPropertyAccess(key)</code>.
420 * @param key the name of the system property to get
421 * @param def the default
422 * @return the property, or def if not found
423 * @throws SecurityException if permission is denied
424 * @throws NullPointerException if key is null
425 * @throws IllegalArgumentException if key is ""
427 public static String getProperty(String key, String def)
429 SecurityManager sm = SecurityManager.current; // Be thread-safe.
431 sm.checkPropertyAccess(key);
432 // This handles both the null pointer exception and the illegal
433 // argument exception.
434 if (key.length() == 0)
435 throw new IllegalArgumentException("key can't be empty");
436 return SystemProperties.getProperty(key, def);
440 * Set a single system property by name. A security check may be performed,
441 * <code>checkPropertyAccess(key, "write")</code>.
443 * @param key the name of the system property to set
444 * @param value the new value
445 * @return the previous value, or null
446 * @throws SecurityException if permission is denied
447 * @throws NullPointerException if key is null
448 * @throws IllegalArgumentException if key is ""
451 public static String setProperty(String key, String value)
453 SecurityManager sm = SecurityManager.current; // Be thread-safe.
455 sm.checkPermission(new PropertyPermission(key, "write"));
456 // This handles both the null pointer exception and the illegal
457 // argument exception.
458 if (key.length() == 0)
459 throw new IllegalArgumentException("key can't be empty");
460 return SystemProperties.setProperty(key, value);
464 * Remove a single system property by name. A security check may be
465 * performed, <code>checkPropertyAccess(key, "write")</code>.
467 * @param key the name of the system property to remove
468 * @return the previous value, or null
469 * @throws SecurityException if permission is denied
470 * @throws NullPointerException if key is null
471 * @throws IllegalArgumentException if key is ""
474 public static String clearProperty(String key)
476 SecurityManager sm = SecurityManager.current; // Be thread-safe.
478 sm.checkPermission(new PropertyPermission(key, "write"));
479 // This handles both the null pointer exception and the illegal
480 // argument exception.
481 if (key.length() == 0)
482 throw new IllegalArgumentException("key can't be empty");
483 return SystemProperties.remove(key);
487 * Gets the value of an environment variable.
489 * @param name the name of the environment variable
490 * @return the string value of the variable or null when the
491 * environment variable is not defined.
492 * @throws NullPointerException
493 * @throws SecurityException if permission is denied
495 * @specnote This method was deprecated in some JDK releases, but
496 * was restored in 1.5.
498 public static String getenv(String name)
501 throw new NullPointerException();
502 SecurityManager sm = SecurityManager.current; // Be thread-safe.
504 sm.checkPermission(new RuntimePermission("getenv." + name));
505 return VMSystem.getenv(name);
510 * Returns an unmodifiable view of the system environment variables.
511 * If the underlying system does not support environment variables,
512 * an empty map is returned.
515 * The returned map is read-only and does not accept queries using
516 * null keys or values, or those of a type other than <code>String</code>.
517 * Attempts to modify the map will throw an
518 * <code>UnsupportedOperationException</code>, while attempts
519 * to pass in a null value will throw a
520 * <code>NullPointerException</code>. Types other than <code>String</code>
521 * throw a <code>ClassCastException</code>.
524 * As the returned map is generated using data from the underlying
525 * platform, it may not comply with the <code>equals()</code>
526 * and <code>hashCode()</code> contracts. It is also likely that
527 * the keys of this map will be case-sensitive.
530 * Use of this method may require a security check for the
531 * RuntimePermission "getenv.*".
534 * @return a map of the system environment variables.
535 * @throws SecurityException if the checkPermission method of
536 * an installed security manager prevents access to
537 * the system environment variables.
540 public static Map<String, String> getenv()
542 SecurityManager sm = SecurityManager.current; // Be thread-safe.
544 sm.checkPermission(new RuntimePermission("getenv.*"));
545 if (environmentMap == null)
547 List<String> environ = (List<String>)VMSystem.environ();
548 Map<String,String> variables = new EnvironmentMap();
549 for (String pair : environ)
551 String[] parts = pair.split("=");
552 if (parts.length == 2)
553 variables.put(parts[0], parts[1]);
555 variables.put(parts[0], "");
557 environmentMap = Collections.unmodifiableMap(variables);
559 return environmentMap;
563 * Terminate the Virtual Machine. This just calls
564 * <code>Runtime.getRuntime().exit(status)</code>, and never returns.
565 * Obviously, a security check is in order, <code>checkExit</code>.
567 * @param status the exit status; by convention non-zero is abnormal
568 * @throws SecurityException if permission is denied
569 * @see Runtime#exit(int)
571 public static void exit(int status)
573 Runtime.getRuntime().exit(status);
577 * Calls the garbage collector. This is only a hint, and it is up to the
578 * implementation what this hint suggests, but it usually causes a
579 * best-effort attempt to reclaim unused memory from discarded objects.
580 * This calls <code>Runtime.getRuntime().gc()</code>.
584 public static void gc()
586 Runtime.getRuntime().gc();
590 * Runs object finalization on pending objects. This is only a hint, and
591 * it is up to the implementation what this hint suggests, but it usually
592 * causes a best-effort attempt to run finalizers on all objects ready
593 * to be reclaimed. This calls
594 * <code>Runtime.getRuntime().runFinalization()</code>.
596 * @see Runtime#runFinalization()
598 public static void runFinalization()
600 Runtime.getRuntime().runFinalization();
604 * Tell the Runtime whether to run finalization before exiting the
605 * JVM. This is inherently unsafe in multi-threaded applications,
606 * since it can force initialization on objects which are still in use
607 * by live threads, leading to deadlock; therefore this is disabled by
608 * default. There may be a security check, <code>checkExit(0)</code>. This
609 * calls <code>Runtime.runFinalizersOnExit()</code>.
611 * @param finalizeOnExit whether to run finalizers on exit
612 * @throws SecurityException if permission is denied
613 * @see Runtime#runFinalizersOnExit(boolean)
615 * @deprecated never rely on finalizers to do a clean, thread-safe,
616 * mop-up from your code
618 public static void runFinalizersOnExit(boolean finalizeOnExit)
620 Runtime.runFinalizersOnExit(finalizeOnExit);
624 * Load a code file using its explicit system-dependent filename. A security
625 * check may be performed, <code>checkLink</code>. This just calls
626 * <code>Runtime.getRuntime().load(filename)</code>.
629 * The library is loaded using the class loader associated with the
630 * class associated with the invoking method.
632 * @param filename the code file to load
633 * @throws SecurityException if permission is denied
634 * @throws UnsatisfiedLinkError if the file cannot be loaded
635 * @see Runtime#load(String)
637 public static void load(String filename)
639 Runtime.getRuntime().load(filename, VMStackWalker.getCallingClassLoader());
643 * Load a library using its explicit system-dependent filename. A security
644 * check may be performed, <code>checkLink</code>. This just calls
645 * <code>Runtime.getRuntime().load(filename)</code>.
648 * The library is loaded using the class loader associated with the
649 * class associated with the invoking method.
651 * @param libname the library file to load
652 * @throws SecurityException if permission is denied
653 * @throws UnsatisfiedLinkError if the file cannot be loaded
654 * @see Runtime#load(String)
656 public static void loadLibrary(String libname)
658 Runtime.getRuntime().loadLibrary(libname,
659 VMStackWalker.getCallingClassLoader());
663 * Convert a library name to its platform-specific variant.
665 * @param libname the library name, as used in <code>loadLibrary</code>
666 * @return the platform-specific mangling of the name
669 public static String mapLibraryName(String libname)
671 return VMRuntime.mapLibraryName(libname);
676 * This is a specialised <code>Collection</code>, providing
677 * the necessary provisions for the collections used by the
678 * environment variable map. Namely, it prevents
679 * querying anything but <code>String</code>s.
681 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
683 private static class EnvironmentCollection
684 extends AbstractCollection<String>
688 * The wrapped collection.
690 protected Collection<String> c;
693 * Constructs a new environment collection, which
694 * wraps the elements of the supplied collection.
696 * @param coll the collection to use as a base for
699 public EnvironmentCollection(Collection<String> coll)
705 * Blocks queries containing a null object or an object which
706 * isn't of type <code>String</code>. All other queries
707 * are forwarded to the underlying collection.
709 * @param obj the object to look for.
710 * @return true if the object exists in the collection.
711 * @throws NullPointerException if the specified object is null.
712 * @throws ClassCastException if the specified object is not a String.
714 public boolean contains(Object obj)
718 NullPointerException("This collection does not support " +
720 if (!(obj instanceof String))
722 ClassCastException("This collection only supports Strings.");
723 return c.contains(obj);
727 * Blocks queries where the collection contains a null object or
728 * an object which isn't of type <code>String</code>. All other
729 * queries are forwarded to the underlying collection.
731 * @param coll the collection of objects to look for.
732 * @return true if the collection contains all elements in the collection.
733 * @throws NullPointerException if the collection is null.
734 * @throws NullPointerException if any collection entry is null.
735 * @throws ClassCastException if any collection entry is not a String.
737 public boolean containsAll(Collection<?> coll)
743 NullPointerException("This collection does not support " +
745 if (!(o instanceof String))
747 ClassCastException("This collection only supports Strings.");
749 return c.containsAll(coll);
753 * This returns an iterator over the map elements, with the
754 * same provisions as for the collection and underlying map.
756 * @return an iterator over the map elements.
758 public Iterator<String> iterator()
764 * Blocks the removal of elements from the collection.
766 * @return true if the removal was sucessful.
767 * @throws NullPointerException if the collection is null.
768 * @throws NullPointerException if any collection entry is null.
769 * @throws ClassCastException if any collection entry is not a String.
771 public boolean remove(Object key)
775 NullPointerException("This collection does not support " +
777 if (!(key instanceof String))
779 ClassCastException("This collection only supports Strings.");
780 return c.contains(key);
784 * Blocks the removal of all elements in the specified
785 * collection from the collection.
787 * @param coll the collection of elements to remove.
788 * @return true if the elements were removed.
789 * @throws NullPointerException if the collection is null.
790 * @throws NullPointerException if any collection entry is null.
791 * @throws ClassCastException if any collection entry is not a String.
793 public boolean removeAll(Collection<?> coll)
799 NullPointerException("This collection does not support " +
801 if (!(o instanceof String))
803 ClassCastException("This collection only supports Strings.");
805 return c.removeAll(coll);
809 * Blocks the retention of all elements in the specified
810 * collection from the collection.
812 * @param c the collection of elements to retain.
813 * @return true if the other elements were removed.
814 * @throws NullPointerException if the collection is null.
815 * @throws NullPointerException if any collection entry is null.
816 * @throws ClassCastException if any collection entry is not a String.
818 public boolean retainAll(Collection<?> coll)
824 NullPointerException("This collection does not support " +
826 if (!(o instanceof String))
828 ClassCastException("This collection only supports Strings.");
830 return c.containsAll(coll);
834 * This simply calls the same method on the wrapped
837 * @return the size of the underlying collection.
844 } // class EnvironmentCollection<String>
847 * This is a specialised <code>HashMap</code>, which
848 * prevents the addition or querying of anything other than
849 * <code>String</code> objects.
851 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
853 static class EnvironmentMap
854 extends HashMap<String,String>
858 * Cache the entry set.
860 private transient Set<Map.Entry<String,String>> entries;
865 private transient Set<String> keys;
868 * Cache the value collection.
870 private transient Collection<String> values;
873 * Constructs a new empty <code>EnvironmentMap</code>.
881 * Constructs a new <code>EnvironmentMap</code> containing
882 * the contents of the specified map.
884 * @param m the map to be added to this.
885 * @throws NullPointerException if a key or value is null.
886 * @throws ClassCastException if a key or value is not a String.
888 EnvironmentMap(Map<String,String> m)
894 * Blocks queries containing a null key or one which is not
895 * of type <code>String</code>. All other queries
896 * are forwarded to the superclass.
898 * @param key the key to look for in the map.
899 * @return true if the key exists in the map.
900 * @throws NullPointerException if the specified key is null.
902 public boolean containsKey(Object key)
906 NullPointerException("This map does not support null keys.");
907 if (!(key instanceof String))
909 ClassCastException("This map only allows queries using Strings.");
910 return super.containsKey(key);
914 * Blocks queries using a null or non-<code>String</code> value.
915 * All other queries are forwarded to the superclass.
917 * @param value the value to look for in the map.
918 * @return true if the value exists in the map.
919 * @throws NullPointerException if the specified value is null.
921 public boolean containsValue(Object value)
925 NullPointerException("This map does not support null values.");
926 if (!(value instanceof String))
928 ClassCastException("This map only allows queries using Strings.");
929 return super.containsValue(value);
933 * Returns a set view of the map entries, with the same
934 * provisions as for the underlying map.
936 * @return a set containing the map entries.
938 public Set<Map.Entry<String,String>> entrySet()
941 entries = super.entrySet();
946 * Blocks queries containing a null or non-<code>String</code> key.
947 * All other queries are passed on to the superclass.
949 * @param key the key to retrieve the value for.
950 * @return the value associated with the given key.
951 * @throws NullPointerException if the specified key is null.
952 * @throws ClassCastException if the specified key is not a String.
954 public String get(Object key)
958 NullPointerException("This map does not support null keys.");
959 if (!(key instanceof String))
961 ClassCastException("This map only allows queries using Strings.");
962 return super.get(key);
966 * Returns a set view of the keys, with the same
967 * provisions as for the underlying map.
969 * @return a set containing the keys.
971 public Set<String> keySet()
974 keys = new EnvironmentSet(super.keySet());
979 * Associates the given key to the given value. If the
980 * map already contains the key, its value is replaced.
981 * The map does not accept null keys or values, or keys
982 * and values not of type {@link String}.
984 * @param key the key to map.
985 * @param value the value to be mapped.
986 * @return the previous value of the key, or null if there was no mapping
987 * @throws NullPointerException if a key or value is null.
988 * @throws ClassCastException if a key or value is not a String.
990 public String put(String key, String value)
993 throw new NullPointerException("A new key is null.");
995 throw new NullPointerException("A new value is null.");
996 if (!(key instanceof String))
997 throw new ClassCastException("A new key is not a String.");
998 if (!(value instanceof String))
999 throw new ClassCastException("A new value is not a String.");
1000 return super.put(key, value);
1004 * Removes a key-value pair from the map. The queried key may not
1005 * be null or of a type other than a <code>String</code>.
1007 * @param key the key of the entry to remove.
1008 * @return the removed value.
1009 * @throws NullPointerException if the specified key is null.
1010 * @throws ClassCastException if the specified key is not a String.
1012 public String remove(Object key)
1016 NullPointerException("This map does not support null keys.");
1017 if (!(key instanceof String))
1019 ClassCastException("This map only allows queries using Strings.");
1020 return super.remove(key);
1024 * Returns a collection view of the values, with the same
1025 * provisions as for the underlying map.
1027 * @return a collection containing the values.
1029 public Collection<String> values()
1032 values = new EnvironmentCollection(super.values());
1039 * This is a specialised <code>Set</code>, providing
1040 * the necessary provisions for the collections used by the
1041 * environment variable map. Namely, it prevents
1042 * modifications and the use of queries with null
1043 * or non-<code>String</code> values.
1045 * @author Andrew John Hughes (gnu_andrew@member.fsf.org)
1047 private static class EnvironmentSet
1048 extends EnvironmentCollection
1049 implements Set<String>
1053 * Constructs a new environment set, which
1054 * wraps the elements of the supplied set.
1056 * @param set the set to use as a base for
1059 public EnvironmentSet(Set<String> set)
1065 * This simply calls the same method on the wrapped
1068 * @param obj the object to compare with.
1069 * @return true if the two objects are equal.
1071 public boolean equals(Object obj)
1073 return c.equals(obj);
1077 * This simply calls the same method on the wrapped
1080 * @return the hashcode of the collection.
1082 public int hashCode()
1084 return c.hashCode();
1087 } // class EnvironmentSet<String>