KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > lang > System


1 /*
2  * @(#)System.java 1.150 06/03/22
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package java.lang;
8
9 import java.io.*;
10 import java.util.Properties JavaDoc;
11 import java.util.PropertyPermission JavaDoc;
12 import java.util.StringTokenizer JavaDoc;
13 import java.security.AccessController JavaDoc;
14 import java.security.PrivilegedAction JavaDoc;
15 import java.security.AllPermission JavaDoc;
16 import java.nio.channels.Channel JavaDoc;
17 import java.nio.channels.spi.SelectorProvider JavaDoc;
18 import sun.net.InetAddressCachePolicy;
19 import sun.nio.ch.Interruptible;
20 import sun.reflect.Reflection;
21 import sun.security.util.SecurityConstants;
22 import sun.reflect.annotation.AnnotationType;
23
24 /**
25  * The <code>System</code> class contains several useful class fields
26  * and methods. It cannot be instantiated.
27  *
28  * <p>Among the facilities provided by the <code>System</code> class
29  * are standard input, standard output, and error output streams;
30  * access to externally defined properties and environment
31  * variables; a means of loading files and libraries; and a utility
32  * method for quickly copying a portion of an array.
33  *
34  * @author unascribed
35  * @version 1.150, 03/22/06
36  * @since JDK1.0
37  */

38 public final class System {
39
40     /* First thing---register the natives */
41     private static native void registerNatives();
42     static {
43         registerNatives();
44     }
45
46     /** Don't let anyone instantiate this class */
47     private System() {
48     }
49
50     /**
51      * The "standard" input stream. This stream is already
52      * open and ready to supply input data. Typically this stream
53      * corresponds to keyboard input or another input source specified by
54      * the host environment or user.
55      */

56     public final static InputStream in = nullInputStream();
57
58     /**
59      * The "standard" output stream. This stream is already
60      * open and ready to accept output data. Typically this stream
61      * corresponds to display output or another output destination
62      * specified by the host environment or user.
63      * <p>
64      * For simple stand-alone Java applications, a typical way to write
65      * a line of output data is:
66      * <blockquote><pre>
67      * System.out.println(data)
68      * </pre></blockquote>
69      * <p>
70      * See the <code>println</code> methods in class <code>PrintStream</code>.
71      *
72      * @see java.io.PrintStream#println()
73      * @see java.io.PrintStream#println(boolean)
74      * @see java.io.PrintStream#println(char)
75      * @see java.io.PrintStream#println(char[])
76      * @see java.io.PrintStream#println(double)
77      * @see java.io.PrintStream#println(float)
78      * @see java.io.PrintStream#println(int)
79      * @see java.io.PrintStream#println(long)
80      * @see java.io.PrintStream#println(java.lang.Object)
81      * @see java.io.PrintStream#println(java.lang.String)
82      */

83     public final static PrintStream out = nullPrintStream();
84
85     /**
86      * The "standard" error output stream. This stream is already
87      * open and ready to accept output data.
88      * <p>
89      * Typically this stream corresponds to display output or another
90      * output destination specified by the host environment or user. By
91      * convention, this output stream is used to display error messages
92      * or other information that should come to the immediate attention
93      * of a user even if the principal output stream, the value of the
94      * variable <code>out</code>, has been redirected to a file or other
95      * destination that is typically not continuously monitored.
96      */

97     public final static PrintStream err = nullPrintStream();
98
99     /* The security manager for the system.
100      */

101     private static SecurityManager JavaDoc security = null;
102
103     /**
104      * Reassigns the "standard" input stream.
105      *
106      * <p>First, if there is a security manager, its <code>checkPermission</code>
107      * method is called with a <code>RuntimePermission("setIO")</code> permission
108      * to see if it's ok to reassign the "standard" input stream.
109      * <p>
110      *
111      * @param in the new standard input stream.
112      *
113      * @throws SecurityException
114      * if a security manager exists and its
115      * <code>checkPermission</code> method doesn't allow
116      * reassigning of the standard input stream.
117      *
118      * @see SecurityManager#checkPermission
119      * @see java.lang.RuntimePermission
120      *
121      * @since JDK1.1
122      */

123     public static void setIn(InputStream in) {
124     checkIO();
125     setIn0(in);
126     }
127
128     /**
129      * Reassigns the "standard" output stream.
130      *
131      * <p>First, if there is a security manager, its <code>checkPermission</code>
132      * method is called with a <code>RuntimePermission("setIO")</code> permission
133      * to see if it's ok to reassign the "standard" output stream.
134      *
135      * @param out the new standard output stream
136      *
137      * @throws SecurityException
138      * if a security manager exists and its
139      * <code>checkPermission</code> method doesn't allow
140      * reassigning of the standard output stream.
141      *
142      * @see SecurityManager#checkPermission
143      * @see java.lang.RuntimePermission
144      *
145      * @since JDK1.1
146      */

147     public static void setOut(PrintStream out) {
148     checkIO();
149     setOut0(out);
150     }
151
152     /**
153      * Reassigns the "standard" error output stream.
154      *
155      * <p>First, if there is a security manager, its <code>checkPermission</code>
156      * method is called with a <code>RuntimePermission("setIO")</code> permission
157      * to see if it's ok to reassign the "standard" error output stream.
158      *
159      * @param err the new standard error output stream.
160      *
161      * @throws SecurityException
162      * if a security manager exists and its
163      * <code>checkPermission</code> method doesn't allow
164      * reassigning of the standard error output stream.
165      *
166      * @see SecurityManager#checkPermission
167      * @see java.lang.RuntimePermission
168      *
169      * @since JDK1.1
170      */

171     public static void setErr(PrintStream err) {
172     checkIO();
173     setErr0(err);
174     }
175
176
177     /**
178      * Returns the channel inherited from the entity that created this
179      * Java virtual machine.
180      *
181      * <p> This method returns the channel obtained by invoking the
182      * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
183      * inheritedChannel} method of the system-wide default
184      * {@link java.nio.channels.spi.SelectorProvider} object. </p>
185      *
186      * <p> In addition to the network-oriented channels described in
187      * {@link java.nio.channels.spi.SelectorProvider#inheritedChannel
188      * inheritedChannel}, this method may return other kinds of
189      * channels in the future.
190      *
191      * @return The inherited channel, if any, otherwise <tt>null</tt>.
192      *
193      * @throws IOException
194      * If an I/O error occurs
195      *
196      * @throws SecurityException
197      * If a security manager is present and it does not
198      * permit access to the channel.
199      *
200      * @since 1.5
201      */

202     public static Channel JavaDoc inheritedChannel() throws IOException {
203         return SelectorProvider.provider().inheritedChannel();
204     }
205
206     private static void checkIO() {
207         if (security != null)
208         security.checkPermission(new RuntimePermission JavaDoc("setIO"));
209     }
210
211     private static native void setIn0(InputStream in);
212     private static native void setOut0(PrintStream out);
213     private static native void setErr0(PrintStream err);
214
215     /**
216      * Sets the System security.
217      *
218      * <p> If there is a security manager already installed, this method first
219      * calls the security manager's <code>checkPermission</code> method
220      * with a <code>RuntimePermission("setSecurityManager")</code>
221      * permission to ensure it's ok to replace the existing
222      * security manager.
223      * This may result in throwing a <code>SecurityException</code>.
224      *
225      * <p> Otherwise, the argument is established as the current
226      * security manager. If the argument is <code>null</code> and no
227      * security manager has been established, then no action is taken and
228      * the method simply returns.
229      *
230      * @param s the security manager.
231      * @exception SecurityException if the security manager has already
232      * been set and its <code>checkPermission</code> method
233      * doesn't allow it to be replaced.
234      * @see #getSecurityManager
235      * @see SecurityManager#checkPermission
236      * @see java.lang.RuntimePermission
237      */

238     public static
239     void setSecurityManager(final SecurityManager JavaDoc s) {
240         try {
241             s.checkPackageAccess("java.lang");
242         } catch (Exception JavaDoc e) {
243             // no-op
244
}
245         setSecurityManager0(s);
246     }
247
248     private static synchronized
249     void setSecurityManager0(final SecurityManager JavaDoc s) {
250     if (security != null) {
251         // ask the currently installed security manager if we
252
// can replace it.
253
security.checkPermission(new RuntimePermission JavaDoc
254                      ("setSecurityManager"));
255     }
256
257     if ((s != null) && (s.getClass().getClassLoader() != null)) {
258         // New security manager class is not on bootstrap classpath.
259
// Cause policy to get initialized before we install the new
260
// security manager, in order to prevent infinite loops when
261
// trying to initialize the policy (which usually involves
262
// accessing some security and/or system properties, which in turn
263
// calls the installed security manager's checkPermission method
264
// which will loop infinitely if there is a non-system class
265
// (in this case: the new security manager class) on the stack).
266
AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
267         public Object JavaDoc run() {
268             s.getClass().getProtectionDomain().implies
269             (SecurityConstants.ALL_PERMISSION);
270             return null;
271         }
272         });
273     }
274
275     security = s;
276     InetAddressCachePolicy.setIfNotSet(InetAddressCachePolicy.FOREVER);
277     }
278
279     /**
280      * Gets the system security interface.
281      *
282      * @return if a security manager has already been established for the
283      * current application, then that security manager is returned;
284      * otherwise, <code>null</code> is returned.
285      * @see #setSecurityManager
286      */

287     public static SecurityManager JavaDoc getSecurityManager() {
288     return security;
289     }
290
291     /**
292      * Returns the current time in milliseconds. Note that
293      * while the unit of time of the return value is a millisecond,
294      * the granularity of the value depends on the underlying
295      * operating system and may be larger. For example, many
296      * operating systems measure time in units of tens of
297      * milliseconds.
298      *
299      * <p> See the description of the class <code>Date</code> for
300      * a discussion of slight discrepancies that may arise between
301      * "computer time" and coordinated universal time (UTC).
302      *
303      * @return the difference, measured in milliseconds, between
304      * the current time and midnight, January 1, 1970 UTC.
305      * @see java.util.Date
306      */

307     public static native long currentTimeMillis();
308
309     /**
310      * Returns the current value of the most precise available system
311      * timer, in nanoseconds.
312      *
313      * <p>This method can only be used to measure elapsed time and is
314      * not related to any other notion of system or wall-clock time.
315      * The value returned represents nanoseconds since some fixed but
316      * arbitrary time (perhaps in the future, so values may be
317      * negative). This method provides nanosecond precision, but not
318      * necessarily nanosecond accuracy. No guarantees are made about
319      * how frequently values change. Differences in successive calls
320      * that span greater than approximately 292 years (2<sup>63</sup>
321      * nanoseconds) will not accurately compute elapsed time due to
322      * numerical overflow.
323      *
324      * <p> For example, to measure how long some code takes to execute:
325      * <pre>
326      * long startTime = System.nanoTime();
327      * // ... the code being measured ...
328      * long estimatedTime = System.nanoTime() - startTime;
329      * </pre>
330      *
331      * @return The current value of the system timer, in nanoseconds.
332      * @since 1.5
333      */

334     public static native long nanoTime();
335
336     /**
337      * Copies an array from the specified source array, beginning at the
338      * specified position, to the specified position of the destination array.
339      * A subsequence of array components are copied from the source
340      * array referenced by <code>src</code> to the destination array
341      * referenced by <code>dest</code>. The number of components copied is
342      * equal to the <code>length</code> argument. The components at
343      * positions <code>srcPos</code> through
344      * <code>srcPos+length-1</code> in the source array are copied into
345      * positions <code>destPos</code> through
346      * <code>destPos+length-1</code>, respectively, of the destination
347      * array.
348      * <p>
349      * If the <code>src</code> and <code>dest</code> arguments refer to the
350      * same array object, then the copying is performed as if the
351      * components at positions <code>srcPos</code> through
352      * <code>srcPos+length-1</code> were first copied to a temporary
353      * array with <code>length</code> components and then the contents of
354      * the temporary array were copied into positions
355      * <code>destPos</code> through <code>destPos+length-1</code> of the
356      * destination array.
357      * <p>
358      * If <code>dest</code> is <code>null</code>, then a
359      * <code>NullPointerException</code> is thrown.
360      * <p>
361      * If <code>src</code> is <code>null</code>, then a
362      * <code>NullPointerException</code> is thrown and the destination
363      * array is not modified.
364      * <p>
365      * Otherwise, if any of the following is true, an
366      * <code>ArrayStoreException</code> is thrown and the destination is
367      * not modified:
368      * <ul>
369      * <li>The <code>src</code> argument refers to an object that is not an
370      * array.
371      * <li>The <code>dest</code> argument refers to an object that is not an
372      * array.
373      * <li>The <code>src</code> argument and <code>dest</code> argument refer
374      * to arrays whose component types are different primitive types.
375      * <li>The <code>src</code> argument refers to an array with a primitive
376      * component type and the <code>dest</code> argument refers to an array
377      * with a reference component type.
378      * <li>The <code>src</code> argument refers to an array with a reference
379      * component type and the <code>dest</code> argument refers to an array
380      * with a primitive component type.
381      * </ul>
382      * <p>
383      * Otherwise, if any of the following is true, an
384      * <code>IndexOutOfBoundsException</code> is
385      * thrown and the destination is not modified:
386      * <ul>
387      * <li>The <code>srcPos</code> argument is negative.
388      * <li>The <code>destPos</code> argument is negative.
389      * <li>The <code>length</code> argument is negative.
390      * <li><code>srcPos+length</code> is greater than
391      * <code>src.length</code>, the length of the source array.
392      * <li><code>destPos+length</code> is greater than
393      * <code>dest.length</code>, the length of the destination array.
394      * </ul>
395      * <p>
396      * Otherwise, if any actual component of the source array from
397      * position <code>srcPos</code> through
398      * <code>srcPos+length-1</code> cannot be converted to the component
399      * type of the destination array by assignment conversion, an
400      * <code>ArrayStoreException</code> is thrown. In this case, let
401      * <b><i>k</i></b> be the smallest nonnegative integer less than
402      * length such that <code>src[srcPos+</code><i>k</i><code>]</code>
403      * cannot be converted to the component type of the destination
404      * array; when the exception is thrown, source array components from
405      * positions <code>srcPos</code> through
406      * <code>srcPos+</code><i>k</i><code>-1</code>
407      * will already have been copied to destination array positions
408      * <code>destPos</code> through
409      * <code>destPos+</code><i>k</I><code>-1</code> and no other
410      * positions of the destination array will have been modified.
411      * (Because of the restrictions already itemized, this
412      * paragraph effectively applies only to the situation where both
413      * arrays have component types that are reference types.)
414      *
415      * @param src the source array.
416      * @param srcPos starting position in the source array.
417      * @param dest the destination array.
418      * @param destPos starting position in the destination data.
419      * @param length the number of array elements to be copied.
420      * @exception IndexOutOfBoundsException if copying would cause
421      * access of data outside array bounds.
422      * @exception ArrayStoreException if an element in the <code>src</code>
423      * array could not be stored into the <code>dest</code> array
424      * because of a type mismatch.
425      * @exception NullPointerException if either <code>src</code> or
426      * <code>dest</code> is <code>null</code>.
427      */

428     public static native void arraycopy(Object JavaDoc src, int srcPos,
429                                         Object JavaDoc dest, int destPos,
430                                         int length);
431
432     /**
433      * Returns the same hash code for the given object as
434      * would be returned by the default method hashCode(),
435      * whether or not the given object's class overrides
436      * hashCode().
437      * The hash code for the null reference is zero.
438      *
439      * @param x object for which the hashCode is to be calculated
440      * @return the hashCode
441      * @since JDK1.1
442      */

443     public static native int identityHashCode(Object JavaDoc x);
444
445     /**
446      * System properties. The following properties are guaranteed to be defined:
447      * <dl>
448      * <dt>java.version <dd>Java version number
449      * <dt>java.vendor <dd>Java vendor specific string
450      * <dt>java.vendor.url <dd>Java vendor URL
451      * <dt>java.home <dd>Java installation directory
452      * <dt>java.class.version <dd>Java class version number
453      * <dt>java.class.path <dd>Java classpath
454      * <dt>os.name <dd>Operating System Name
455      * <dt>os.arch <dd>Operating System Architecture
456      * <dt>os.version <dd>Operating System Version
457      * <dt>file.separator <dd>File separator ("/" on Unix)
458      * <dt>path.separator <dd>Path separator (":" on Unix)
459      * <dt>line.separator <dd>Line separator ("\n" on Unix)
460      * <dt>user.name <dd>User account name
461      * <dt>user.home <dd>User home directory
462      * <dt>user.dir <dd>User's current working directory
463      * </dl>
464      */

465
466     private static Properties JavaDoc props;
467     private static native Properties JavaDoc initProperties(Properties JavaDoc props);
468
469     /**
470      * Determines the current system properties.
471      * <p>
472      * First, if there is a security manager, its
473      * <code>checkPropertiesAccess</code> method is called with no
474      * arguments. This may result in a security exception.
475      * <p>
476      * The current set of system properties for use by the
477      * {@link #getProperty(String)} method is returned as a
478      * <code>Properties</code> object. If there is no current set of
479      * system properties, a set of system properties is first created and
480      * initialized. This set of system properties always includes values
481      * for the following keys:
482      * <table summary="Shows property keys and associated values">
483      * <tr><th>Key</th>
484      * <th>Description of Associated Value</th></tr>
485      * <tr><td><code>java.version</code></td>
486      * <td>Java Runtime Environment version</td></tr>
487      * <tr><td><code>java.vendor</code></td>
488      * <td>Java Runtime Environment vendor</td></tr
489      * <tr><td><code>java.vendor.url</code></td>
490      * <td>Java vendor URL</td></tr>
491      * <tr><td><code>java.home</code></td>
492      * <td>Java installation directory</td></tr>
493      * <tr><td><code>java.vm.specification.version</code></td>
494      * <td>Java Virtual Machine specification version</td></tr>
495      * <tr><td><code>java.vm.specification.vendor</code></td>
496      * <td>Java Virtual Machine specification vendor</td></tr>
497      * <tr><td><code>java.vm.specification.name</code></td>
498      * <td>Java Virtual Machine specification name</td></tr>
499      * <tr><td><code>java.vm.version</code></td>
500      * <td>Java Virtual Machine implementation version</td></tr>
501      * <tr><td><code>java.vm.vendor</code></td>
502      * <td>Java Virtual Machine implementation vendor</td></tr>
503      * <tr><td><code>java.vm.name</code></td>
504      * <td>Java Virtual Machine implementation name</td></tr>
505      * <tr><td><code>java.specification.version</code></td>
506      * <td>Java Runtime Environment specification version</td></tr>
507      * <tr><td><code>java.specification.vendor</code></td>
508      * <td>Java Runtime Environment specification vendor</td></tr>
509      * <tr><td><code>java.specification.name</code></td>
510      * <td>Java Runtime Environment specification name</td></tr>
511      * <tr><td><code>java.class.version</code></td>
512      * <td>Java class format version number</td></tr>
513      * <tr><td><code>java.class.path</code></td>
514      * <td>Java class path</td></tr>
515      * <tr><td><code>java.library.path</code></td>
516      * <td>List of paths to search when loading libraries</td></tr>
517      * <tr><td><code>java.io.tmpdir</code></td>
518      * <td>Default temp file path</td></tr>
519      * <tr><td><code>java.compiler</code></td>
520      * <td>Name of JIT compiler to use</td></tr>
521      * <tr><td><code>java.ext.dirs</code></td>
522      * <td>Path of extension directory or directories</td></tr>
523      * <tr><td><code>os.name</code></td>
524      * <td>Operating system name</td></tr>
525      * <tr><td><code>os.arch</code></td>
526      * <td>Operating system architecture</td></tr>
527      * <tr><td><code>os.version</code></td>
528      * <td>Operating system version</td></tr>
529      * <tr><td><code>file.separator</code></td>
530      * <td>File separator ("/" on UNIX)</td></tr>
531      * <tr><td><code>path.separator</code></td>
532      * <td>Path separator (":" on UNIX)</td></tr>
533      * <tr><td><code>line.separator</code></td>
534      * <td>Line separator ("\n" on UNIX)</td></tr>
535      * <tr><td><code>user.name</code></td>
536      * <td>User's account name</td></tr>
537      * <tr><td><code>user.home</code></td>
538      * <td>User's home directory</td></tr>
539      * <tr><td><code>user.dir</code></td>
540      * <td>User's current working directory</td></tr>
541      * </table>
542      * <p>
543      * Multiple paths in a system property value are separated by the path
544      * separator character of the platform.
545      * <p>
546      * Note that even if the security manager does not permit the
547      * <code>getProperties</code> operation, it may choose to permit the
548      * {@link #getProperty(String)} operation.
549      *
550      * @return the system properties
551      * @exception SecurityException if a security manager exists and its
552      * <code>checkPropertiesAccess</code> method doesn't allow access
553      * to the system properties.
554      * @see #setProperties
555      * @see java.lang.SecurityException
556      * @see java.lang.SecurityManager#checkPropertiesAccess()
557      * @see java.util.Properties
558      */

559     public static Properties JavaDoc getProperties() {
560     if (security != null) {
561         security.checkPropertiesAccess();
562     }
563     return props;
564     }
565
566     /**
567      * Sets the system properties to the <code>Properties</code>
568      * argument.
569      * <p>
570      * First, if there is a security manager, its
571      * <code>checkPropertiesAccess</code> method is called with no
572      * arguments. This may result in a security exception.
573      * <p>
574      * The argument becomes the current set of system properties for use
575      * by the {@link #getProperty(String)} method. If the argument is
576      * <code>null</code>, then the current set of system properties is
577      * forgotten.
578      *
579      * @param props the new system properties.
580      * @exception SecurityException if a security manager exists and its
581      * <code>checkPropertiesAccess</code> method doesn't allow access
582      * to the system properties.
583      * @see #getProperties
584      * @see java.util.Properties
585      * @see java.lang.SecurityException
586      * @see java.lang.SecurityManager#checkPropertiesAccess()
587      */

588     public static void setProperties(Properties JavaDoc props) {
589     if (security != null) {
590         security.checkPropertiesAccess();
591     }
592         if (props == null) {
593             props = new Properties JavaDoc();
594             initProperties(props);
595         }
596     System.props = props;
597     }
598
599     /**
600      * Gets the system property indicated by the specified key.
601      * <p>
602      * First, if there is a security manager, its
603      * <code>checkPropertyAccess</code> method is called with the key as
604      * its argument. This may result in a SecurityException.
605      * <p>
606      * If there is no current set of system properties, a set of system
607      * properties is first created and initialized in the same manner as
608      * for the <code>getProperties</code> method.
609      *
610      * @param key the name of the system property.
611      * @return the string value of the system property,
612      * or <code>null</code> if there is no property with that key.
613      *
614      * @exception SecurityException if a security manager exists and its
615      * <code>checkPropertyAccess</code> method doesn't allow
616      * access to the specified system property.
617      * @exception NullPointerException if <code>key</code> is
618      * <code>null</code>.
619      * @exception IllegalArgumentException if <code>key</code> is empty.
620      * @see #setProperty
621      * @see java.lang.SecurityException
622      * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
623      * @see java.lang.System#getProperties()
624      */

625     public static String JavaDoc getProperty(String JavaDoc key) {
626     checkKey(key);
627     if (security != null) {
628         security.checkPropertyAccess(key);
629     }
630     return props.getProperty(key);
631     }
632
633     /**
634      * Gets the system property indicated by the specified key.
635      * <p>
636      * First, if there is a security manager, its
637      * <code>checkPropertyAccess</code> method is called with the
638      * <code>key</code> as its argument.
639      * <p>
640      * If there is no current set of system properties, a set of system
641      * properties is first created and initialized in the same manner as
642      * for the <code>getProperties</code> method.
643      *
644      * @param key the name of the system property.
645      * @param def a default value.
646      * @return the string value of the system property,
647      * or the default value if there is no property with that key.
648      *
649      * @exception SecurityException if a security manager exists and its
650      * <code>checkPropertyAccess</code> method doesn't allow
651      * access to the specified system property.
652      * @exception NullPointerException if <code>key</code> is
653      * <code>null</code>.
654      * @exception IllegalArgumentException if <code>key</code> is empty.
655      * @see #setProperty
656      * @see java.lang.SecurityManager#checkPropertyAccess(java.lang.String)
657      * @see java.lang.System#getProperties()
658      */

659     public static String JavaDoc getProperty(String JavaDoc key, String JavaDoc def) {
660     checkKey(key);
661     if (security != null) {
662         security.checkPropertyAccess(key);
663     }
664     return props.getProperty(key, def);
665     }
666
667     /**
668      * Sets the system property indicated by the specified key.
669      * <p>
670      * First, if a security manager exists, its
671      * <code>SecurityManager.checkPermission</code> method
672      * is called with a <code>PropertyPermission(key, "write")</code>
673      * permission. This may result in a SecurityException being thrown.
674      * If no exception is thrown, the specified property is set to the given
675      * value.
676      * <p>
677      *
678      * @param key the name of the system property.
679      * @param value the value of the system property.
680      * @return the previous value of the system property,
681      * or <code>null</code> if it did not have one.
682      *
683      * @exception SecurityException if a security manager exists and its
684      * <code>checkPermission</code> method doesn't allow
685      * setting of the specified property.
686      * @exception NullPointerException if <code>key</code> or
687      * <code>value</code> is <code>null</code>.
688      * @exception IllegalArgumentException if <code>key</code> is empty.
689      * @see #getProperty
690      * @see java.lang.System#getProperty(java.lang.String)
691      * @see java.lang.System#getProperty(java.lang.String, java.lang.String)
692      * @see java.util.PropertyPermission
693      * @see SecurityManager#checkPermission
694      * @since 1.2
695      */

696     public static String JavaDoc setProperty(String JavaDoc key, String JavaDoc value) {
697     checkKey(key);
698     if (security != null)
699         security.checkPermission(new PropertyPermission JavaDoc(key,
700         SecurityConstants.PROPERTY_WRITE_ACTION));
701     return (String JavaDoc) props.setProperty(key, value);
702     }
703
704     /**
705      * Removes the system property indicated by the specified key.
706      * <p>
707      * First, if a security manager exists, its
708      * <code>SecurityManager.checkPermission</code> method
709      * is called with a <code>PropertyPermission(key, "write")</code>
710      * permission. This may result in a SecurityException being thrown.
711      * If no exception is thrown, the specified property is removed.
712      * <p>
713      *
714      * @param key the name of the system property to be removed.
715      * @return the previous string value of the system property,
716      * or <code>null</code> if there was no property with that key.
717      *
718      * @exception SecurityException if a security manager exists and its
719      * <code>checkPropertyAccess</code> method doesn't allow
720      * access to the specified system property.
721      * @exception NullPointerException if <code>key</code> is
722      * <code>null</code>.
723      * @exception IllegalArgumentException if <code>key</code> is empty.
724      * @see #getProperty
725      * @see #setProperty
726      * @see java.util.Properties
727      * @see java.lang.SecurityException
728      * @see java.lang.SecurityManager#checkPropertiesAccess()
729      * @since 1.5
730      */

731     public static String JavaDoc clearProperty(String JavaDoc key) {
732         checkKey(key);
733         if (security != null)
734             security.checkPermission(new PropertyPermission JavaDoc(key, "write"));
735         return (String JavaDoc) props.remove(key);
736     }
737
738     private static void checkKey(String JavaDoc key) {
739         if (key == null) {
740             throw new NullPointerException JavaDoc("key can't be null");
741         }
742         if (key.equals("")) {
743             throw new IllegalArgumentException JavaDoc("key can't be empty");
744         }
745     }
746
747     /**
748      * Gets the value of the specified environment variable. An
749      * environment variable is a system-dependent external named
750      * value.
751      *
752      * <p>If a security manager exists, its
753      * {@link SecurityManager#checkPermission checkPermission}
754      * method is called with a
755      * <code>{@link RuntimePermission}("getenv."+name)</code>
756      * permission. This may result in a {@link SecurityException}
757      * being thrown. If no exception is thrown the value of the
758      * variable <code>name</code> is returned.
759      *
760      * <p><a name="EnvironmentVSSystemProperties"><i>System
761      * properties</i> and <i>environment variables</i> are both
762      * conceptually mappings between names and values. Both
763      * mechanisms can be used to pass user-defined information to a
764      * Java process. Environment variables have a more global effect,
765      * because they are visible to all descendants of the process
766      * which defines them, not just the immediate Java subprocess.
767      * They can have subtly different semantics, such as case
768      * insensitivity, on different operating systems. For these
769      * reasons, environment variables are more likely to have
770      * unintended side effects. It is best to use system properties
771      * where possible. Environment variables should be used when a
772      * global effect is desired, or when an external system interface
773      * requires an environment variable (such as <code>PATH</code>).
774      *
775      * <p>On UNIX systems the alphabetic case of <code>name</code> is
776      * typically significant, while on Microsoft Windows systems it is
777      * typically not. For example, the expression
778      * <code>System.getenv("FOO").equals(System.getenv("foo"))</code>
779      * is likely to be true on Microsoft Windows.
780      *
781      * @param name the name of the environment variable
782      * @return the string value of the variable, or <code>null</code>
783      * if the variable is not defined in the system environment
784      * @throws NullPointerException if <code>name</code> is <code>null</code>
785      * @throws SecurityException
786      * if a security manager exists and its
787      * {@link SecurityManager#checkPermission checkPermission}
788      * method doesn't allow access to the environment variable
789      * <code>name</code>
790      * @see #getenv()
791      * @see ProcessBuilder#environment()
792      */

793     public static String JavaDoc getenv(String JavaDoc name) {
794     if (security != null)
795         security.checkPermission(new RuntimePermission JavaDoc("getenv."+name));
796
797     return ProcessEnvironment.getenv(name);
798     }
799
800     
801     /**
802      * Returns an unmodifiable string map view of the current system environment.
803      * The environment is a system-dependent mapping from names to
804      * values which is passed from parent to child processes.
805      *
806      * <p>If the system does not support environment variables, an
807      * empty map is returned.
808      *
809      * <p>The returned map will never contain null keys or values.
810      * Attempting to query the presence of a null key or value will
811      * throw a {@link NullPointerException}. Attempting to query
812      * the presence of a key or value which is not of type
813      * {@link String} will throw a {@link ClassCastException}.
814      *
815      * <p>The returned map and its collection views may not obey the
816      * general contract of the {@link Object#equals} and
817      * {@link Object#hashCode} methods.
818      *
819      * <p>The returned map is typically case-sensitive on all platforms.
820      *
821      * <p>If a security manager exists, its
822      * {@link SecurityManager#checkPermission checkPermission}
823      * method is called with a
824      * <code>{@link RuntimePermission}("getenv.*")</code>
825      * permission. This may result in a {@link SecurityException} being
826      * thrown.
827      *
828      * <p>When passing information to a Java subprocess,
829      * <a HREF=#EnvironmentVSSystemProperties>system properties</a>
830      * are generally preferred over environment variables.
831      *
832      * @return the environment as a map of variable names to values
833      * @throws SecurityException
834      * if a security manager exists and its
835      * {@link SecurityManager#checkPermission checkPermission}
836      * method doesn't allow access to the process environment
837      * @see #getenv(String)
838      * @see ProcessBuilder#environment()
839      * @since 1.5
840      */

841     public static java.util.Map JavaDoc<String JavaDoc,String JavaDoc> getenv() {
842     if (security != null)
843         security.checkPermission(new RuntimePermission JavaDoc("getenv.*"));
844
845     return ProcessEnvironment.getenv();
846     }
847
848     /**
849      * Terminates the currently running Java Virtual Machine. The
850      * argument serves as a status code; by convention, a nonzero status
851      * code indicates abnormal termination.
852      * <p>
853      * This method calls the <code>exit</code> method in class
854      * <code>Runtime</code>. This method never returns normally.
855      * <p>
856      * The call <code>System.exit(n)</code> is effectively equivalent to
857      * the call:
858      * <blockquote><pre>
859      * Runtime.getRuntime().exit(n)
860      * </pre></blockquote>
861      *
862      * @param status exit status.
863      * @throws SecurityException
864      * if a security manager exists and its <code>checkExit</code>
865      * method doesn't allow exit with the specified status.
866      * @see java.lang.Runtime#exit(int)
867      */

868     public static void exit(int status) {
869     Runtime.getRuntime().exit(status);
870     }
871
872     /**
873      * Runs the garbage collector.
874      * <p>
875      * Calling the <code>gc</code> method suggests that the Java Virtual
876      * Machine expend effort toward recycling unused objects in order to
877      * make the memory they currently occupy available for quick reuse.
878      * When control returns from the method call, the Java Virtual
879      * Machine has made a best effort to reclaim space from all discarded
880      * objects.
881      * <p>
882      * The call <code>System.gc()</code> is effectively equivalent to the
883      * call:
884      * <blockquote><pre>
885      * Runtime.getRuntime().gc()
886      * </pre></blockquote>
887      *
888      * @see java.lang.Runtime#gc()
889      */

890     public static void gc() {
891     Runtime.getRuntime().gc();
892     }
893
894     /**
895      * Runs the finalization methods of any objects pending finalization.
896      * <p>
897      * Calling this method suggests that the Java Virtual Machine expend
898      * effort toward running the <code>finalize</code> methods of objects
899      * that have been found to be discarded but whose <code>finalize</code>
900      * methods have not yet been run. When control returns from the
901      * method call, the Java Virtual Machine has made a best effort to
902      * complete all outstanding finalizations.
903      * <p>
904      * The call <code>System.runFinalization()</code> is effectively
905      * equivalent to the call:
906      * <blockquote><pre>
907      * Runtime.getRuntime().runFinalization()
908      * </pre></blockquote>
909      *
910      * @see java.lang.Runtime#runFinalization()
911      */

912     public static void runFinalization() {
913     Runtime.getRuntime().runFinalization();
914     }
915
916     /**
917      * Enable or disable finalization on exit; doing so specifies that the
918      * finalizers of all objects that have finalizers that have not yet been
919      * automatically invoked are to be run before the Java runtime exits.
920      * By default, finalization on exit is disabled.
921      *
922      * <p>If there is a security manager,
923      * its <code>checkExit</code> method is first called
924      * with 0 as its argument to ensure the exit is allowed.
925      * This could result in a SecurityException.
926      *
927      * @deprecated This method is inherently unsafe. It may result in
928      * finalizers being called on live objects while other threads are
929      * concurrently manipulating those objects, resulting in erratic
930      * behavior or deadlock.
931      * @param value indicating enabling or disabling of finalization
932      * @throws SecurityException
933      * if a security manager exists and its <code>checkExit</code>
934      * method doesn't allow the exit.
935      *
936      * @see java.lang.Runtime#exit(int)
937      * @see java.lang.Runtime#gc()
938      * @see java.lang.SecurityManager#checkExit(int)
939      * @since JDK1.1
940      */

941     @Deprecated JavaDoc
942     public static void runFinalizersOnExit(boolean value) {
943     Runtime.getRuntime().runFinalizersOnExit(value);
944     }
945
946     /**
947      * Loads a code file with the specified filename from the local file
948      * system as a dynamic library. The filename
949      * argument must be a complete path name.
950      * <p>
951      * The call <code>System.load(name)</code> is effectively equivalent
952      * to the call:
953      * <blockquote><pre>
954      * Runtime.getRuntime().load(name)
955      * </pre></blockquote>
956      *
957      * @param filename the file to load.
958      * @exception SecurityException if a security manager exists and its
959      * <code>checkLink</code> method doesn't allow
960      * loading of the specified dynamic library
961      * @exception UnsatisfiedLinkError if the file does not exist.
962      * @exception NullPointerException if <code>filename</code> is
963      * <code>null</code>
964      * @see java.lang.Runtime#load(java.lang.String)
965      * @see java.lang.SecurityManager#checkLink(java.lang.String)
966      */

967     public static void load(String JavaDoc filename) {
968     Runtime.getRuntime().load0(getCallerClass(), filename);
969     }
970
971     /**
972      * Loads the system library specified by the <code>libname</code>
973      * argument. The manner in which a library name is mapped to the
974      * actual system library is system dependent.
975      * <p>
976      * The call <code>System.loadLibrary(name)</code> is effectively
977      * equivalent to the call
978      * <blockquote><pre>
979      * Runtime.getRuntime().loadLibrary(name)
980      * </pre></blockquote>
981      *
982      * @param libname the name of the library.
983      * @exception SecurityException if a security manager exists and its
984      * <code>checkLink</code> method doesn't allow
985      * loading of the specified dynamic library
986      * @exception UnsatisfiedLinkError if the library does not exist.
987      * @exception NullPointerException if <code>libname</code> is
988      * <code>null</code>
989      * @see java.lang.Runtime#loadLibrary(java.lang.String)
990      * @see java.lang.SecurityManager#checkLink(java.lang.String)
991      */

992     public static void loadLibrary(String JavaDoc libname) {
993     Runtime.getRuntime().loadLibrary0(getCallerClass(), libname);
994     }
995
996     /**
997      * Maps a library name into a platform-specific string representing
998      * a native library.
999      *
1000     * @param libname the name of the library.
1001     * @return a platform-dependent native library name.
1002     * @exception NullPointerException if <code>libname</code> is
1003     * <code>null</code>
1004     * @see java.lang.System#loadLibrary(java.lang.String)
1005     * @see java.lang.ClassLoader#findLibrary(java.lang.String)
1006     * @since 1.2
1007     */

1008    public static native String JavaDoc mapLibraryName(String JavaDoc libname);
1009
1010    /**
1011     * The following two methods exist because in, out, and err must be
1012     * initialized to null. The compiler, however, cannot be permitted to
1013     * inline access to them, since they are later set to more sensible values
1014     * by initializeSystemClass().
1015     */

1016    private static InputStream nullInputStream() throws NullPointerException JavaDoc {
1017    if (currentTimeMillis() > 0)
1018        return null;
1019    throw new NullPointerException JavaDoc();
1020    }
1021
1022    private static PrintStream nullPrintStream() throws NullPointerException JavaDoc {
1023    if (currentTimeMillis() > 0)
1024        return null;
1025    throw new NullPointerException JavaDoc();
1026    }
1027
1028    /**
1029     * Initialize the system class. Called after thread initialization.
1030     */

1031    private static void initializeSystemClass() {
1032    props = new Properties JavaDoc();
1033    initProperties(props);
1034    sun.misc.Version.init();
1035    FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
1036    FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
1037    FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
1038    setIn0(new BufferedInputStream(fdIn));
1039    setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
1040    setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));
1041
1042    // Load the zip library now in order to keep java.util.zip.ZipFile
1043
// from trying to use itself to load this library later.
1044
loadLibrary("zip");
1045
1046        // Currently File.deleteOnExit is built on JVM_Exit, which is a
1047
// separate mechanism from shutdown hooks. Unfortunately in order to
1048
// work properly JVM_Exit implicitly requires that Java signal
1049
// handlers be set up for HUP, TERM, and INT (where available). If
1050
// File.deleteOnExit were implemented in terms of shutdown hooks this
1051
// call to Terminator.setup() could be removed.
1052
Terminator.setup();
1053
1054    // Set the maximum amount of direct memory. This value is controlled
1055
// by the vm option -XX:MaxDirectMemorySize=<size>. This method acts
1056
// as an initializer only if it is called before sun.misc.VM.booted().
1057
sun.misc.VM.maxDirectMemory();
1058
1059    // Set a boolean to determine whether ClassLoader.loadClass accepts
1060
// array syntax. This value is controlled by the system property
1061
// "sun.lang.ClassLoader.allowArraySyntax". This method acts as
1062
// an initializer only if it is called before sun.misc.VM.booted().
1063
sun.misc.VM.allowArraySyntax();
1064
1065    // Subsystems that are invoked during initialization can invoke
1066
// sun.misc.VM.isBooted() in order to avoid doing things that should
1067
// wait until the application class loader has been set up.
1068
sun.misc.VM.booted();
1069
1070        // The main thread is not added to its thread group in the same
1071
// way as other threads; we must do it ourselves here.
1072
Thread JavaDoc current = Thread.currentThread();
1073        current.getThreadGroup().add(current);
1074
1075        // Allow privileged classes outside of java.lang
1076
sun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess(){
1077            public sun.reflect.ConstantPool getConstantPool(Class JavaDoc klass) {
1078                return klass.getConstantPool();
1079            }
1080            public void setAnnotationType(Class JavaDoc klass, AnnotationType type) {
1081                klass.setAnnotationType(type);
1082            }
1083            public AnnotationType getAnnotationType(Class JavaDoc klass) {
1084                return klass.getAnnotationType();
1085            }
1086            public void blockedOn(Thread JavaDoc t, Interruptible b) {
1087                t.blockedOn(b);
1088            }
1089        });
1090    }
1091
1092    /* returns the class of the caller. */
1093    static Class JavaDoc getCallerClass() {
1094        // NOTE use of more generic Reflection.getCallerClass()
1095
return Reflection.getCallerClass(3);
1096    }
1097}
1098
Popular Tags