System.java 39 KB

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