home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 1998 July & August / Pcwk78a98.iso / Internet / Javadraw / DATA.Z / Runtime.java < prev    next >
Text File  |  1997-08-30  |  19KB  |  496 lines

  1. /*
  2.  * @(#)Runtime.java    1.26 97/02/24
  3.  * 
  4.  * Copyright (c) 1995, 1996 Sun Microsystems, Inc. All Rights Reserved.
  5.  * 
  6.  * This software is the confidential and proprietary information of Sun
  7.  * Microsystems, Inc. ("Confidential Information").  You shall not
  8.  * disclose such Confidential Information and shall use it only in
  9.  * accordance with the terms of the license agreement you entered into
  10.  * with Sun.
  11.  * 
  12.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
  13.  * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  14.  * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  15.  * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
  16.  * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
  17.  * THIS SOFTWARE OR ITS DERIVATIVES.
  18.  * 
  19.  * CopyrightVersion 1.1_beta
  20.  * 
  21.  */
  22.  
  23. package java.lang;
  24.  
  25. import java.io.*;
  26. import java.util.StringTokenizer;
  27.  
  28. /*
  29.  * Every Java application has a single instance of class 
  30.  * <code>Runtime</code> that allows the application to interface with 
  31.  * the environment in which the application is running. The current 
  32.  * runtime can be obtained from the <code>getRuntime</code> method. 
  33.  * <p>
  34.  * An application cannot create its own instance of this class. 
  35.  *
  36.  * @author  unascribed
  37.  * @version 1.26, 02/24/97
  38.  * @see     java.lang.Runtime#getRuntime()
  39.  * @since   JDK1.0
  40.  */
  41. public class Runtime {
  42.     private static Runtime currentRuntime = new Runtime();
  43.       
  44.     /**
  45.      * Returns the runtime object associated with the current Java application.
  46.      *
  47.      * @return  the <code>Runtime</code> object associated with the current
  48.      *          Java application.
  49.      * @since   JDK1.0
  50.      */
  51.     public static Runtime getRuntime() { 
  52.     return currentRuntime;
  53.     }
  54.     
  55.     /** Don't let anyone else instantiate this class */
  56.     private Runtime() {}
  57.  
  58.     /* Helper for exit
  59.      */
  60.     private native void exitInternal(int status);
  61.  
  62.     /**
  63.      * Terminates the currently running Java Virtual Machine. This 
  64.      * method never returns normally. 
  65.      * <p>
  66.      * If there is a security manager, its <code>checkExit</code> method 
  67.      * is called with the status as its argument. This may result in a 
  68.      * security exception. 
  69.      * <p>
  70.      * The argument serves as a status code; by convention, a nonzero 
  71.      * status code indicates abnormal termination. 
  72.      *
  73.      * @param      status   exit status.
  74.      * @exception  SecurityException  if the current thread cannot exit with
  75.      *               the specified status.
  76.      * @see        java.lang.SecurityException
  77.      * @see        java.lang.SecurityManager#checkExit(int)
  78.      * @since      JDK1.0
  79.      */
  80.     public void exit(int status) {
  81.     SecurityManager security = System.getSecurityManager();
  82.     if (security != null) {
  83.         security.checkExit(status);
  84.     }
  85.     exitInternal(status);
  86.     }
  87.  
  88.     /**
  89.      * Enable or disable finalization on exit; doing so specifies that the
  90.      * finalizers of all objects that have finalizers that have not yet been
  91.      * automatically invoked are to be run before the Java runtime exits.
  92.      * By default, finalization on exit is disabled.  An invocation of
  93.      * the runFinalizersOnExit method is permitted only if the caller is
  94.      * allowed to exit, and is otherwise rejected by the security manager.
  95.      * @see Runtime#gc
  96.      * @see Runtime#exit
  97.      * @since   JDK1.1
  98.      */
  99.     public static void runFinalizersOnExit(boolean value) {
  100.     SecurityManager security = System.getSecurityManager();
  101.     if (security != null) {
  102.         try { security.checkExit(0); }
  103.         catch (SecurityException e) {
  104.         throw new SecurityException("runFinalizersOnExit");
  105.         }
  106.     }
  107.     runFinalizersOnExit0(value);
  108.     }
  109.  
  110.     /*
  111.      * Private variable holding the boolean determining whether to finalize
  112.      * on exit.  The default value of the variable is false.  See the comment
  113.      * on Runtime.runFinalizersOnExit for constraints on modifying this.
  114.      */
  115.     private static native void runFinalizersOnExit0(boolean value);
  116.  
  117.     /* Helper for exec
  118.      */
  119.     private native Process execInternal(String cmdarray[], String envp[]) 
  120.      throws IOException;
  121.  
  122.     /**
  123.      * Executes the specified string command in a separate process. 
  124.      * <p>
  125.      * The <code>command</code> argument is parsed into tokens and then 
  126.      * executed as a command in a separate process. This method has 
  127.      * exactly the same effect as <code>exec(command, null)</code>. 
  128.      *
  129.      * @param      command   a specified system command.
  130.      * @return     a <code>Process</code> object for managing the subprocess.
  131.      * @exception  SecurityException  if the current thread cannot create a
  132.      *             subprocess.
  133.      * @see        java.lang.Runtime#exec(java.lang.String, java.lang.String[])
  134.      * @since      JDK1.0
  135.      */
  136.     public Process exec(String command) throws IOException {
  137.     return exec(command, null);
  138.     }
  139.  
  140.     /**
  141.      * Executes the specified string command in a separate process with the 
  142.      * specified environment. 
  143.      * <p>
  144.      * This method breaks the <code>command</code> string into tokens and 
  145.      * creates a new array <code>cmdarray</code> containing the tokens; it 
  146.      * then performs the call <code>exec(cmdarray, envp)</code>. 
  147.      *
  148.      * @param      command   a specified system command.
  149.      * @param      envp      array containing environment in format
  150.      *                       <i>name</i>=<i>value</i>
  151.      * @return     a <code>Process</code> object for managing the subprocess.
  152.      * @exception  SecurityException  if the current thread cannot create a
  153.      *               subprocess.
  154.      * @see        java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
  155.      * @since      JDK1.0
  156.      */
  157.     public Process exec(String command, String envp[]) throws IOException {
  158.     int count = 0;
  159.     String cmdarray[];
  160.      StringTokenizer st;
  161.  
  162.     st = new StringTokenizer(command);
  163.      count = st.countTokens();
  164.  
  165.     cmdarray = new String[count];
  166.     st = new StringTokenizer(command);
  167.     count = 0;
  168.      while (st.hasMoreTokens()) {
  169.          cmdarray[count++] = st.nextToken();
  170.      }
  171.     SecurityManager security = System.getSecurityManager();
  172.     if (security != null) {
  173.         security.checkExec(cmdarray[0]);
  174.     }
  175.     return execInternal(cmdarray, envp);
  176.     }
  177.  
  178.     /**
  179.      * Executes the specified command and arguments in a separate process.
  180.      * <p>
  181.      * The command specified by the tokens in <code>cmdarray</code> is 
  182.      * executed as a command in a separate process. This has exactly the 
  183.      * same effect as <code>exec(cmdarray, null)</code>. 
  184.      *
  185.      * @param      cmdarray   array containing the command to call and
  186.      *                        its arguments.
  187.      * @return     a <code>Process</code> object for managing the subprocess.
  188.      * @exception  SecurityException  if the current thread cannot create a
  189.      *               subprocess.
  190.      * @see        java.lang.Runtime#exec(java.lang.String[], java.lang.String[])
  191.      * @since      JDK1.0
  192.      */
  193.     public Process exec(String cmdarray[]) throws IOException {
  194.     return exec(cmdarray, null);
  195.     }
  196.  
  197.     /**
  198.      * Executes the specified command and arguments in a separate process
  199.      * with the specified environment. 
  200.      * <p>
  201.      * If there is a security manager, its <code>checkExec</code> method 
  202.      * is called with the first component of the array 
  203.      * <code>cmdarray</code> as its argument. This may result in a security 
  204.      * exception. 
  205.      * <p>
  206.      * Given an array of strings <code>cmdarray</code>, representing the 
  207.      * tokens of a command line, and an array of strings <code>envp</code>, 
  208.      * representing an "environment" that defines system 
  209.      * properties, this method creates a new process in which to execute 
  210.      * the specified command. 
  211.      *
  212.      * @param      cmdarray   array containing the command to call and
  213.      *                        its arguments.
  214.      * @param      envp       array containing environment in format
  215.      *                        <i>name</i>=<i>value</i>.
  216.      * @return     a <code>Process</code> object for managing the subprocess.
  217.      * @exception  SecurityException  if the current thread cannot create a
  218.      *               subprocess.
  219.      * @see     java.lang.SecurityException
  220.      * @see     java.lang.SecurityManager#checkExec(java.lang.String)
  221.      * @since   JDK1.0
  222.      */
  223.     public Process exec(String cmdarray[], String envp[]) throws IOException {
  224.     SecurityManager security = System.getSecurityManager();
  225.     if (security != null) {
  226.         security.checkExec(cmdarray[0]);
  227.     }
  228.     return execInternal(cmdarray, envp);
  229.     }
  230.  
  231.     /**
  232.      * Returns the amount of free memory in the system. The value returned
  233.      * by this method is always less than the value returned by the
  234.      * <code>totalMemory</code> method. Calling the <code>gc</code> method may
  235.      * result in increasing the value returned by <code>freeMemory.</code>
  236.      *
  237.      * @return  an approximation to the total amount of memory currently
  238.      *          available for future allocated objects, measured in bytes.
  239.      * @since   JDK1.0
  240.      */
  241.     public native long freeMemory();
  242.  
  243.     /**
  244.      * Returns the total amount of memory in the Java Virtual Machine. 
  245.      *
  246.      * @return  the total amount of memory currently available for allocating
  247.      *          objects, measured in bytes.
  248.      * @since   JDK1.0
  249.      */
  250.     public native long totalMemory();
  251.  
  252.     /**
  253.      * Runs the garbage collector.
  254.      * Calling this method suggests that the Java Virtual Machine expend 
  255.      * effort toward recycling unused objects in order to make the memory 
  256.      * they currently occupy available for quick reuse. When control 
  257.      * returns from the method call, the Java Virtual Machine has made 
  258.      * its best effort to recycle all unused objects. 
  259.      * <p>
  260.      * The name <code>gc</code> stands for "garbage 
  261.      * collector". The Java Virtual Machine performs this recycling 
  262.      * process automatically as needed even if the <code>gc</code> method 
  263.      * is not invoked explicitly. 
  264.      *
  265.      * @since   JDK1.0
  266.      */
  267.     public native void gc();
  268.  
  269.     /**
  270.      * Runs the finalization methods of any objects pending finalization.
  271.      * Calling this method suggests that the Java Virtual Machine expend 
  272.      * effort toward running the <code>finalize</code> methods of objects 
  273.      * that have been found to be discarded but whose <code>finalize</code> 
  274.      * methods have not yet been run. When control returns from the 
  275.      * method call, the Java Virtual Machine has made a best effort to 
  276.      * complete all outstanding finalizations. 
  277.      * <p>
  278.      * The Java Virtual Machine performs the finalization process 
  279.      * automatically as needed if the <code>runFinalization</code> method 
  280.      * is not invoked explicitly. 
  281.      *
  282.      * @see     java.lang.Object#finalize()
  283.      * @since   JDK1.0
  284.      */
  285.     public native void runFinalization();
  286.  
  287.     /**
  288.      * Enables/Disables tracing of instructions.
  289.      * If the <code>boolean</code> argument is <code>true</code>, this 
  290.      * method asks the Java Virtual Machine to print out a detailed trace 
  291.      * of each instruction in the Java Virtual Machine as it is executed. 
  292.      * The virtual machine may ignore this request if it does not support 
  293.      * this feature. The destination of the trace output is system 
  294.      * dependent. 
  295.      * <p>
  296.      * If the <code>boolean</code> argument is <code>false</code>, this 
  297.      * method causes the Java Virtual Machine to stop performing the 
  298.      * detailed instruction trace it is performing. 
  299.      *
  300.      * @param   on   <code>true</code> to enable instruction tracing;
  301.      *               <code>false</code> to disable this feature.
  302.      * @since   JDK1.0
  303.      */
  304.     public native void traceInstructions(boolean on);
  305.  
  306.     /**
  307.      * Enables/Disables tracing of method calls.
  308.      * If the <code>boolean</code> argument is <code>true</code>, this 
  309.      * method asks the Java Virtual Machine to print out a detailed trace 
  310.      * of each method in the Java Virtual Machine as it is called. The 
  311.      * virtual machine may ignore this request if it does not support 
  312.      * this feature. The destination of the trace output is system dependent. 
  313.      * <p>
  314.      * If the <code>boolean</code> argument is <code>false</code>, this 
  315.      * method causes the Java Virtual Machine to stop performing the 
  316.      * detailed method trace it is performing. 
  317.      *
  318.      * @param   on   <code>true</code> to enable instruction tracing;
  319.      *               <code>false</code> to disable this feature.
  320.      * @since   JDK1.0
  321.      */
  322.     public native void traceMethodCalls(boolean on);
  323.  
  324.     /**
  325.      * Initializes the linker and returns the search path for shared libraries.
  326.      */
  327.     private synchronized native String initializeLinkerInternal();
  328.     private native String buildLibName(String pathname, String filename);
  329.  
  330.     /* Helper for load and loadLibrary */
  331.     private native int loadFileInternal(String filename);
  332.  
  333.     /** The paths searched for libraries */
  334.     private String paths[];
  335.  
  336.     private void initializeLinker() {
  337.     String ldpath = initializeLinkerInternal();
  338.     char c = System.getProperty("path.separator").charAt(0);
  339.     int ldlen = ldpath.length();
  340.     int i, j, n;
  341.     // Count the separators in the path
  342.     i = ldpath.indexOf(c);
  343.     n = 0;
  344.     while (i >= 0) {
  345.         n++;
  346.         i = ldpath.indexOf(c, i+1);
  347.     }
  348.  
  349.     // allocate the array of paths - n :'s = n + 1 path elements
  350.     paths = new String[n + 1];
  351.  
  352.     // Fill the array with paths from the ldpath
  353.     n = i = 0;
  354.     j = ldpath.indexOf(c);
  355.     while (j >= 0) {
  356.         if (j - i > 0) {
  357.         paths[n++] = ldpath.substring(i, j);
  358.         } else if (j - i == 0) { 
  359.         paths[n++] = ".";
  360.         }
  361.         i = j + 1;
  362.         j = ldpath.indexOf(c, i);
  363.     }
  364.     paths[n] = ldpath.substring(i, ldlen);
  365.     }
  366.  
  367.     /**
  368.      * Loads the specified filename as a dynamic library. The filename 
  369.      * argument must be a complete pathname. 
  370.      * From <code>java_g</code> it will automagically insert "_g" before the
  371.      * ".so" (for example
  372.      * <code>Runtime.getRuntime().load("/home/avh/lib/libX11.so");</code>).
  373.      * <p>
  374.      * If there is a security manager, its <code>checkLink</code> method 
  375.      * is called with the <code>filename</code> as its argument. This may 
  376.      * result in a security exception. 
  377.      *
  378.      * @param      filename   the file to load.
  379.      * @exception  SecurityException     if the current thread cannot load the
  380.      *               specified dynamic library.
  381.      * @exception  UnsatisfiedLinkError  if the file does not exist.
  382.      * @see        java.lang.Runtime#getRuntime()
  383.      * @see        java.lang.SecurityException
  384.      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
  385.      * @since      JDK1.0
  386.      */
  387.     public synchronized void load(String filename) {
  388.     SecurityManager security = System.getSecurityManager();
  389.     int ret;
  390.     if (security != null) {
  391.         security.checkLink(filename);
  392.     }
  393.     ret = loadFileInternal(filename);
  394.     if (ret == -1) {
  395.         throw new OutOfMemoryError();
  396.     } else if (ret == 0) {
  397.         throw new UnsatisfiedLinkError(filename);
  398.     }   /* else load was successful; return */
  399.     }
  400.  
  401.     /**
  402.      * Loads the dynamic library with the specified library name. The 
  403.      * mapping from a library name to a specific filename is done in a 
  404.      * system-specific manner. 
  405.      * <p>
  406.      * First, if there is a security manager, its <code>checkLink</code> 
  407.      * method is called with the <code>filename</code> as its argument. 
  408.      * This may result in a security exception. 
  409.      * <p>
  410.      * If this method is called more than once with the same library 
  411.      * name, the second and subsequent calls are ignored. 
  412.      *
  413.      * @param      libname   the name of the library.
  414.      * @exception  SecurityException     if the current thread cannot load the
  415.      *               specified dynamic library.
  416.      * @exception  UnsatisfiedLinkError  if the library does not exist.
  417.      * @see        java.lang.SecurityException
  418.      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
  419.      * @since      JDK1.0
  420.      */
  421.     public synchronized void loadLibrary(String libname) {
  422.     SecurityManager security = System.getSecurityManager();
  423.     if (security != null) {
  424.         security.checkLink(libname);
  425.     }
  426.         if (paths == null) {
  427.             initializeLinker();
  428.     }
  429.     for (int i = 0 ; i < paths.length ; i++) {
  430.         int ret;
  431.         String tempname = buildLibName(paths[i], libname);
  432.         ret = loadFileInternal(tempname);
  433.         if (ret == -1) {
  434.         throw new OutOfMemoryError();
  435.         } else if (ret == 1) {    // Loaded or found it already loaded
  436.         return;
  437.         }
  438.     }
  439.     // Oops, it failed
  440.         throw new UnsatisfiedLinkError("no " + libname + 
  441.                        " in shared library path");
  442.     }
  443.  
  444.     /**
  445.      * Creates a localized version of an input stream. This method takes 
  446.      * an <code>InputStream</code> and returns an <code>InputStream</code> 
  447.      * equivalent to the argument in all respects except that it is 
  448.      * localized: as characters in the local character set are read from 
  449.      * the stream, they are automatically converted from the local 
  450.      * character set to Unicode. 
  451.      * <p>
  452.      * If the argument is already a localized stream, it may be returned 
  453.      * as the result. 
  454.      *
  455.      * @deprecated As of JDK 1.1, the preferred way translate a byte
  456.      * stream in the local encoding into a character stream in Unicode is via
  457.      * the <code>InputStreamReader</code> and <code>BufferedReader</code>
  458.      * classes.
  459.      *
  460.      * @return     a localized input stream.
  461.      * @see        java.io.InputStream
  462.      * @see        java.io.BufferedReader#BufferedReader(java.io.Reader)
  463.      * @see        java.io.InputStreamReader#InputStreamReader(java.io.InputStream)
  464.      */
  465.     public InputStream getLocalizedInputStream(InputStream in) {
  466.     return in;
  467.     }
  468.  
  469.     /**
  470.      * Creates a localized version of an output stream. This method 
  471.      * takes an <code>OutputStream</code> and returns an 
  472.      * <code>OutputStream</code> equivalent to the argument in all respects 
  473.      * except that it is localized: as Unicode characters are written to 
  474.      * the stream, they are automatically converted to the local 
  475.      * character set. 
  476.      * <p>
  477.      * If the argument is already a localized stream, it may be returned 
  478.      * as the result. 
  479.      *
  480.      * @deprecated As of JDK 1.1, the preferred way to translate a
  481.      * Unicode character stream into a byte stream in the local encoding is via
  482.      * the <code>OutputStreamWriter</code>, <code>BufferedWriter</code>, and
  483.      * <code>PrintWriter</code> classes.
  484.      *
  485.      * @return     a localized output stream.
  486.      * @see        java.io.OutputStream
  487.      * @see        java.io.BufferedWriter#BufferedWriter(java.io.Writer)
  488.      * @see        java.io.OutputStreamWriter#OutputStreamWriter(java.io.OutputStream)
  489.      * @see        java.io.PrintWriter#PrintWriter(java.io.OutputStream)
  490.      */
  491.     public OutputStream getLocalizedOutputStream(OutputStream out) {
  492.     return out;
  493.     }
  494.  
  495. }
  496.