1 /*
   2  * Copyright (c) 1995, 2019, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang;
  27 
  28 import java.io.*;
  29 import java.math.BigInteger;
  30 import java.util.regex.Matcher;
  31 import java.util.regex.Pattern;
  32 import java.util.stream.Collectors;
  33 import java.util.List;
  34 import java.util.Optional;
  35 import java.util.StringTokenizer;
  36 
  37 import jdk.internal.access.SharedSecrets;
  38 import jdk.internal.reflect.CallerSensitive;
  39 import jdk.internal.reflect.Reflection;
  40 
  41 /**
  42  * Every Java application has a single instance of class
  43  * {@code Runtime} that allows the application to interface with
  44  * the environment in which the application is running. The current
  45  * runtime can be obtained from the {@code getRuntime} method.
  46  * <p>
  47  * An application cannot create its own instance of this class.
  48  *
  49  * @author  unascribed
  50  * @see     java.lang.Runtime#getRuntime()
  51  * @since   1.0
  52  */
  53 
  54 public class Runtime {
  55     private static final Runtime currentRuntime = new Runtime();
  56 
  57     private static Version version;
  58 
  59     /**
  60      * Returns the runtime object associated with the current Java application.
  61      * Most of the methods of class {@code Runtime} are instance
  62      * methods and must be invoked with respect to the current runtime object.
  63      *
  64      * @return  the {@code Runtime} object associated with the current
  65      *          Java application.
  66      */
  67     public static Runtime getRuntime() {
  68         return currentRuntime;
  69     }
  70 
  71     /** Don't let anyone else instantiate this class */
  72     private Runtime() {}
  73 
  74     /**
  75      * Terminates the currently running Java virtual machine by initiating its
  76      * shutdown sequence.  This method never returns normally.  The argument
  77      * serves as a status code; by convention, a nonzero status code indicates
  78      * abnormal termination.
  79      *
  80      * <p> All registered {@linkplain #addShutdownHook shutdown hooks}, if any,
  81      * are started in some unspecified order and allowed to run concurrently
  82      * until they finish.  Once this is done the virtual machine
  83      * {@linkplain #halt halts}.
  84      *
  85      * <p> If this method is invoked after all shutdown hooks have already
  86      * been run and the status is nonzero then this method halts the
  87      * virtual machine with the given status code. Otherwise, this method
  88      * blocks indefinitely.
  89      *
  90      * <p> The {@link System#exit(int) System.exit} method is the
  91      * conventional and convenient means of invoking this method.
  92      *
  93      * @param  status
  94      *         Termination status.  By convention, a nonzero status code
  95      *         indicates abnormal termination.
  96      *
  97      * @throws SecurityException
  98      *         If a security manager is present and its
  99      *         {@link SecurityManager#checkExit checkExit} method does not permit
 100      *         exiting with the specified status
 101      *
 102      * @see java.lang.SecurityException
 103      * @see java.lang.SecurityManager#checkExit(int)
 104      * @see #addShutdownHook
 105      * @see #removeShutdownHook
 106      * @see #halt(int)
 107      */
 108     public void exit(int status) {
 109         SecurityManager security = System.getSecurityManager();
 110         if (security != null) {
 111             security.checkExit(status);
 112         }
 113         Shutdown.exit(status);
 114     }
 115 
 116     /**
 117      * Registers a new virtual-machine shutdown hook.
 118      *
 119      * <p> The Java virtual machine <i>shuts down</i> in response to two kinds
 120      * of events:
 121      *
 122      *   <ul>
 123      *
 124      *   <li> The program <i>exits</i> normally, when the last non-daemon
 125      *   thread exits or when the {@link #exit exit} (equivalently,
 126      *   {@link System#exit(int) System.exit}) method is invoked, or
 127      *
 128      *   <li> The virtual machine is <i>terminated</i> in response to a
 129      *   user interrupt, such as typing {@code ^C}, or a system-wide event,
 130      *   such as user logoff or system shutdown.
 131      *
 132      *   </ul>
 133      *
 134      * <p> A <i>shutdown hook</i> is simply an initialized but unstarted
 135      * thread.  When the virtual machine begins its shutdown sequence it will
 136      * start all registered shutdown hooks in some unspecified order and let
 137      * them run concurrently.  When all the hooks have finished it will then
 138      * halt. Note that daemon threads will continue to run during the shutdown
 139      * sequence, as will non-daemon threads if shutdown was initiated by
 140      * invoking the {@link #exit exit} method.
 141      *
 142      * <p> Once the shutdown sequence has begun it can be stopped only by
 143      * invoking the {@link #halt halt} method, which forcibly
 144      * terminates the virtual machine.
 145      *
 146      * <p> Once the shutdown sequence has begun it is impossible to register a
 147      * new shutdown hook or de-register a previously-registered hook.
 148      * Attempting either of these operations will cause an
 149      * {@link IllegalStateException} to be thrown.
 150      *
 151      * <p> Shutdown hooks run at a delicate time in the life cycle of a virtual
 152      * machine and should therefore be coded defensively.  They should, in
 153      * particular, be written to be thread-safe and to avoid deadlocks insofar
 154      * as possible.  They should also not rely blindly upon services that may
 155      * have registered their own shutdown hooks and therefore may themselves in
 156      * the process of shutting down.  Attempts to use other thread-based
 157      * services such as the AWT event-dispatch thread, for example, may lead to
 158      * deadlocks.
 159      *
 160      * <p> Shutdown hooks should also finish their work quickly.  When a
 161      * program invokes {@link #exit exit} the expectation is
 162      * that the virtual machine will promptly shut down and exit.  When the
 163      * virtual machine is terminated due to user logoff or system shutdown the
 164      * underlying operating system may only allow a fixed amount of time in
 165      * which to shut down and exit.  It is therefore inadvisable to attempt any
 166      * user interaction or to perform a long-running computation in a shutdown
 167      * hook.
 168      *
 169      * <p> Uncaught exceptions are handled in shutdown hooks just as in any
 170      * other thread, by invoking the
 171      * {@link ThreadGroup#uncaughtException uncaughtException} method of the
 172      * thread's {@link ThreadGroup} object. The default implementation of this
 173      * method prints the exception's stack trace to {@link System#err} and
 174      * terminates the thread; it does not cause the virtual machine to exit or
 175      * halt.
 176      *
 177      * <p> In rare circumstances the virtual machine may <i>abort</i>, that is,
 178      * stop running without shutting down cleanly.  This occurs when the
 179      * virtual machine is terminated externally, for example with the
 180      * {@code SIGKILL} signal on Unix or the {@code TerminateProcess} call on
 181      * Microsoft Windows.  The virtual machine may also abort if a native
 182      * method goes awry by, for example, corrupting internal data structures or
 183      * attempting to access nonexistent memory.  If the virtual machine aborts
 184      * then no guarantee can be made about whether or not any shutdown hooks
 185      * will be run.
 186      *
 187      * @param   hook
 188      *          An initialized but unstarted {@link Thread} object
 189      *
 190      * @throws  IllegalArgumentException
 191      *          If the specified hook has already been registered,
 192      *          or if it can be determined that the hook is already running or
 193      *          has already been run
 194      *
 195      * @throws  IllegalStateException
 196      *          If the virtual machine is already in the process
 197      *          of shutting down
 198      *
 199      * @throws  SecurityException
 200      *          If a security manager is present and it denies
 201      *          {@link RuntimePermission}("shutdownHooks")
 202      *
 203      * @see #removeShutdownHook
 204      * @see #halt(int)
 205      * @see #exit(int)
 206      * @since 1.3
 207      */
 208     public void addShutdownHook(Thread hook) {
 209         SecurityManager sm = System.getSecurityManager();
 210         if (sm != null) {
 211             sm.checkPermission(new RuntimePermission("shutdownHooks"));
 212         }
 213         ApplicationShutdownHooks.add(hook);
 214     }
 215 
 216     /**
 217      * De-registers a previously-registered virtual-machine shutdown hook.
 218      *
 219      * @param hook the hook to remove
 220      * @return {@code true} if the specified hook had previously been
 221      * registered and was successfully de-registered, {@code false}
 222      * otherwise.
 223      *
 224      * @throws  IllegalStateException
 225      *          If the virtual machine is already in the process of shutting
 226      *          down
 227      *
 228      * @throws  SecurityException
 229      *          If a security manager is present and it denies
 230      *          {@link RuntimePermission}("shutdownHooks")
 231      *
 232      * @see #addShutdownHook
 233      * @see #exit(int)
 234      * @since 1.3
 235      */
 236     public boolean removeShutdownHook(Thread hook) {
 237         SecurityManager sm = System.getSecurityManager();
 238         if (sm != null) {
 239             sm.checkPermission(new RuntimePermission("shutdownHooks"));
 240         }
 241         return ApplicationShutdownHooks.remove(hook);
 242     }
 243 
 244     /**
 245      * Forcibly terminates the currently running Java virtual machine.  This
 246      * method never returns normally.
 247      *
 248      * <p> This method should be used with extreme caution.  Unlike the
 249      * {@link #exit exit} method, this method does not cause shutdown
 250      * hooks to be started.  If the shutdown sequence has already been
 251      * initiated then this method does not wait for any running
 252      * shutdown hooks to finish their work.
 253      *
 254      * @param  status
 255      *         Termination status. By convention, a nonzero status code
 256      *         indicates abnormal termination. If the {@link Runtime#exit exit}
 257      *         (equivalently, {@link System#exit(int) System.exit}) method
 258      *         has already been invoked then this status code
 259      *         will override the status code passed to that method.
 260      *
 261      * @throws SecurityException
 262      *         If a security manager is present and its
 263      *         {@link SecurityManager#checkExit checkExit} method
 264      *         does not permit an exit with the specified status
 265      *
 266      * @see #exit
 267      * @see #addShutdownHook
 268      * @see #removeShutdownHook
 269      * @since 1.3
 270      */
 271     public void halt(int status) {
 272         SecurityManager sm = System.getSecurityManager();
 273         if (sm != null) {
 274             sm.checkExit(status);
 275         }
 276         Shutdown.beforeHalt();
 277         Shutdown.halt(status);
 278     }
 279 
 280     /**
 281      * Executes the specified string command in a separate process.
 282      *
 283      * <p>This is a convenience method.  An invocation of the form
 284      * {@code exec(command)}
 285      * behaves in exactly the same way as the invocation
 286      * {@link #exec(String, String[], File) exec}{@code (command, null, null)}.
 287      *
 288      * @param   command   a specified system command.
 289      *
 290      * @return  A new {@link Process} object for managing the subprocess
 291      *
 292      * @throws  SecurityException
 293      *          If a security manager exists and its
 294      *          {@link SecurityManager#checkExec checkExec}
 295      *          method doesn't allow creation of the subprocess
 296      *
 297      * @throws  IOException
 298      *          If an I/O error occurs
 299      *
 300      * @throws  NullPointerException
 301      *          If {@code command} is {@code null}
 302      *
 303      * @throws  IllegalArgumentException
 304      *          If {@code command} is empty
 305      *
 306      * @see     #exec(String[], String[], File)
 307      * @see     ProcessBuilder
 308      */
 309     public Process exec(String command) throws IOException {
 310         return exec(command, null, null);
 311     }
 312 
 313     /**
 314      * Executes the specified string command in a separate process with the
 315      * specified environment.
 316      *
 317      * <p>This is a convenience method.  An invocation of the form
 318      * {@code exec(command, envp)}
 319      * behaves in exactly the same way as the invocation
 320      * {@link #exec(String, String[], File) exec}{@code (command, envp, null)}.
 321      *
 322      * @param   command   a specified system command.
 323      *
 324      * @param   envp      array of strings, each element of which
 325      *                    has environment variable settings in the format
 326      *                    <i>name</i>=<i>value</i>, or
 327      *                    {@code null} if the subprocess should inherit
 328      *                    the environment of the current process.
 329      *
 330      * @return  A new {@link Process} object for managing the subprocess
 331      *
 332      * @throws  SecurityException
 333      *          If a security manager exists and its
 334      *          {@link SecurityManager#checkExec checkExec}
 335      *          method doesn't allow creation of the subprocess
 336      *
 337      * @throws  IOException
 338      *          If an I/O error occurs
 339      *
 340      * @throws  NullPointerException
 341      *          If {@code command} is {@code null},
 342      *          or one of the elements of {@code envp} is {@code null}
 343      *
 344      * @throws  IllegalArgumentException
 345      *          If {@code command} is empty
 346      *
 347      * @see     #exec(String[], String[], File)
 348      * @see     ProcessBuilder
 349      */
 350     public Process exec(String command, String[] envp) throws IOException {
 351         return exec(command, envp, null);
 352     }
 353 
 354     /**
 355      * Executes the specified string command in a separate process with the
 356      * specified environment and working directory.
 357      *
 358      * <p>This is a convenience method.  An invocation of the form
 359      * {@code exec(command, envp, dir)}
 360      * behaves in exactly the same way as the invocation
 361      * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, dir)},
 362      * where {@code cmdarray} is an array of all the tokens in
 363      * {@code command}.
 364      *
 365      * <p>More precisely, the {@code command} string is broken
 366      * into tokens using a {@link StringTokenizer} created by the call
 367      * {@code new {@link StringTokenizer}(command)} with no
 368      * further modification of the character categories.  The tokens
 369      * produced by the tokenizer are then placed in the new string
 370      * array {@code cmdarray}, in the same order.
 371      *
 372      * @param   command   a specified system command.
 373      *
 374      * @param   envp      array of strings, each element of which
 375      *                    has environment variable settings in the format
 376      *                    <i>name</i>=<i>value</i>, or
 377      *                    {@code null} if the subprocess should inherit
 378      *                    the environment of the current process.
 379      *
 380      * @param   dir       the working directory of the subprocess, or
 381      *                    {@code null} if the subprocess should inherit
 382      *                    the working directory of the current process.
 383      *
 384      * @return  A new {@link Process} object for managing the subprocess
 385      *
 386      * @throws  SecurityException
 387      *          If a security manager exists and its
 388      *          {@link SecurityManager#checkExec checkExec}
 389      *          method doesn't allow creation of the subprocess
 390      *
 391      * @throws  IOException
 392      *          If an I/O error occurs
 393      *
 394      * @throws  NullPointerException
 395      *          If {@code command} is {@code null},
 396      *          or one of the elements of {@code envp} is {@code null}
 397      *
 398      * @throws  IllegalArgumentException
 399      *          If {@code command} is empty
 400      *
 401      * @see     ProcessBuilder
 402      * @since 1.3
 403      */
 404     public Process exec(String command, String[] envp, File dir)
 405         throws IOException {
 406         if (command.isEmpty())
 407             throw new IllegalArgumentException("Empty command");
 408 
 409         StringTokenizer st = new StringTokenizer(command);
 410         String[] cmdarray = new String[st.countTokens()];
 411         for (int i = 0; st.hasMoreTokens(); i++)
 412             cmdarray[i] = st.nextToken();
 413         return exec(cmdarray, envp, dir);
 414     }
 415 
 416     /**
 417      * Executes the specified command and arguments in a separate process.
 418      *
 419      * <p>This is a convenience method.  An invocation of the form
 420      * {@code exec(cmdarray)}
 421      * behaves in exactly the same way as the invocation
 422      * {@link #exec(String[], String[], File) exec}{@code (cmdarray, null, null)}.
 423      *
 424      * @param   cmdarray  array containing the command to call and
 425      *                    its arguments.
 426      *
 427      * @return  A new {@link Process} object for managing the subprocess
 428      *
 429      * @throws  SecurityException
 430      *          If a security manager exists and its
 431      *          {@link SecurityManager#checkExec checkExec}
 432      *          method doesn't allow creation of the subprocess
 433      *
 434      * @throws  IOException
 435      *          If an I/O error occurs
 436      *
 437      * @throws  NullPointerException
 438      *          If {@code cmdarray} is {@code null},
 439      *          or one of the elements of {@code cmdarray} is {@code null}
 440      *
 441      * @throws  IndexOutOfBoundsException
 442      *          If {@code cmdarray} is an empty array
 443      *          (has length {@code 0})
 444      *
 445      * @see     ProcessBuilder
 446      */
 447     public Process exec(String cmdarray[]) throws IOException {
 448         return exec(cmdarray, null, null);
 449     }
 450 
 451     /**
 452      * Executes the specified command and arguments in a separate process
 453      * with the specified environment.
 454      *
 455      * <p>This is a convenience method.  An invocation of the form
 456      * {@code exec(cmdarray, envp)}
 457      * behaves in exactly the same way as the invocation
 458      * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, null)}.
 459      *
 460      * @param   cmdarray  array containing the command to call and
 461      *                    its arguments.
 462      *
 463      * @param   envp      array of strings, each element of which
 464      *                    has environment variable settings in the format
 465      *                    <i>name</i>=<i>value</i>, or
 466      *                    {@code null} if the subprocess should inherit
 467      *                    the environment of the current process.
 468      *
 469      * @return  A new {@link Process} object for managing the subprocess
 470      *
 471      * @throws  SecurityException
 472      *          If a security manager exists and its
 473      *          {@link SecurityManager#checkExec checkExec}
 474      *          method doesn't allow creation of the subprocess
 475      *
 476      * @throws  IOException
 477      *          If an I/O error occurs
 478      *
 479      * @throws  NullPointerException
 480      *          If {@code cmdarray} is {@code null},
 481      *          or one of the elements of {@code cmdarray} is {@code null},
 482      *          or one of the elements of {@code envp} is {@code null}
 483      *
 484      * @throws  IndexOutOfBoundsException
 485      *          If {@code cmdarray} is an empty array
 486      *          (has length {@code 0})
 487      *
 488      * @see     ProcessBuilder
 489      */
 490     public Process exec(String[] cmdarray, String[] envp) throws IOException {
 491         return exec(cmdarray, envp, null);
 492     }
 493 
 494 
 495     /**
 496      * Executes the specified command and arguments in a separate process with
 497      * the specified environment and working directory.
 498      *
 499      * <p>Given an array of strings {@code cmdarray}, representing the
 500      * tokens of a command line, and an array of strings {@code envp},
 501      * representing "environment" variable settings, this method creates
 502      * a new process in which to execute the specified command.
 503      *
 504      * <p>This method checks that {@code cmdarray} is a valid operating
 505      * system command.  Which commands are valid is system-dependent,
 506      * but at the very least the command must be a non-empty list of
 507      * non-null strings.
 508      *
 509      * <p>If {@code envp} is {@code null}, the subprocess inherits the
 510      * environment settings of the current process.
 511      *
 512      * <p>A minimal set of system dependent environment variables may
 513      * be required to start a process on some operating systems.
 514      * As a result, the subprocess may inherit additional environment variable
 515      * settings beyond those in the specified environment.
 516      *
 517      * <p>{@link ProcessBuilder#start()} is now the preferred way to
 518      * start a process with a modified environment.
 519      *
 520      * <p>The working directory of the new subprocess is specified by {@code dir}.
 521      * If {@code dir} is {@code null}, the subprocess inherits the
 522      * current working directory of the current process.
 523      *
 524      * <p>If a security manager exists, its
 525      * {@link SecurityManager#checkExec checkExec}
 526      * method is invoked with the first component of the array
 527      * {@code cmdarray} as its argument. This may result in a
 528      * {@link SecurityException} being thrown.
 529      *
 530      * <p>Starting an operating system process is highly system-dependent.
 531      * Among the many things that can go wrong are:
 532      * <ul>
 533      * <li>The operating system program file was not found.
 534      * <li>Access to the program file was denied.
 535      * <li>The working directory does not exist.
 536      * </ul>
 537      *
 538      * <p>In such cases an exception will be thrown.  The exact nature
 539      * of the exception is system-dependent, but it will always be a
 540      * subclass of {@link IOException}.
 541      *
 542      * <p>If the operating system does not support the creation of
 543      * processes, an {@link UnsupportedOperationException} will be thrown.
 544      *
 545      *
 546      * @param   cmdarray  array containing the command to call and
 547      *                    its arguments.
 548      *
 549      * @param   envp      array of strings, each element of which
 550      *                    has environment variable settings in the format
 551      *                    <i>name</i>=<i>value</i>, or
 552      *                    {@code null} if the subprocess should inherit
 553      *                    the environment of the current process.
 554      *
 555      * @param   dir       the working directory of the subprocess, or
 556      *                    {@code null} if the subprocess should inherit
 557      *                    the working directory of the current process.
 558      *
 559      * @return  A new {@link Process} object for managing the subprocess
 560      *
 561      * @throws  SecurityException
 562      *          If a security manager exists and its
 563      *          {@link SecurityManager#checkExec checkExec}
 564      *          method doesn't allow creation of the subprocess
 565      *
 566      * @throws  UnsupportedOperationException
 567      *          If the operating system does not support the creation of processes.
 568      *
 569      * @throws  IOException
 570      *          If an I/O error occurs
 571      *
 572      * @throws  NullPointerException
 573      *          If {@code cmdarray} is {@code null},
 574      *          or one of the elements of {@code cmdarray} is {@code null},
 575      *          or one of the elements of {@code envp} is {@code null}
 576      *
 577      * @throws  IndexOutOfBoundsException
 578      *          If {@code cmdarray} is an empty array
 579      *          (has length {@code 0})
 580      *
 581      * @see     ProcessBuilder
 582      * @since 1.3
 583      */
 584     public Process exec(String[] cmdarray, String[] envp, File dir)
 585         throws IOException {
 586         return new ProcessBuilder(cmdarray)
 587             .environment(envp)
 588             .directory(dir)
 589             .start();
 590     }
 591 
 592     /**
 593      * Returns the number of processors available to the Java virtual machine.
 594      *
 595      * <p> This value may change during a particular invocation of the virtual
 596      * machine.  Applications that are sensitive to the number of available
 597      * processors should therefore occasionally poll this property and adjust
 598      * their resource usage appropriately. </p>
 599      *
 600      * @return  the maximum number of processors available to the virtual
 601      *          machine; never smaller than one
 602      * @since 1.4
 603      */
 604     public native int availableProcessors();
 605 
 606     /**
 607      * Returns the amount of free memory in the Java Virtual Machine.
 608      * Calling the
 609      * {@code gc} method may result in increasing the value returned
 610      * by {@code freeMemory.}
 611      *
 612      * @return  an approximation to the total amount of memory currently
 613      *          available for future allocated objects, measured in bytes.
 614      */
 615     public native long freeMemory();
 616 
 617     /**
 618      * Returns the total amount of memory in the Java virtual machine.
 619      * The value returned by this method may vary over time, depending on
 620      * the host environment.
 621      * <p>
 622      * Note that the amount of memory required to hold an object of any
 623      * given type may be implementation-dependent.
 624      *
 625      * @return  the total amount of memory currently available for current
 626      *          and future objects, measured in bytes.
 627      */
 628     public native long totalMemory();
 629 
 630     /**
 631      * Returns the maximum amount of memory that the Java virtual machine
 632      * will attempt to use.  If there is no inherent limit then the value
 633      * {@link java.lang.Long#MAX_VALUE} will be returned.
 634      *
 635      * @return  the maximum amount of memory that the virtual machine will
 636      *          attempt to use, measured in bytes
 637      * @since 1.4
 638      */
 639     public native long maxMemory();
 640 
 641     /**
 642      * Runs the garbage collector in the Java Virtual Machine.
 643      * <p>
 644      * Calling this method suggests that the Java Virtual Machine
 645      * expend effort toward recycling unused objects in order to
 646      * make the memory they currently occupy available for reuse
 647      * by the Java Virtual Machine.
 648      * When control returns from the method call, the Java Virtual Machine
 649      * has made a best effort to reclaim space from all unused objects.
 650      * There is no guarantee that this effort will recycle any particular
 651      * number of unused objects, reclaim any particular amount of space, or
 652      * complete at any particular time, if at all, before the method returns or ever.
 653      * <p>
 654      * The name {@code gc} stands for "garbage
 655      * collector". The Java Virtual Machine performs this recycling
 656      * process automatically as needed, in a separate thread, even if the
 657      * {@code gc} method is not invoked explicitly.
 658      * <p>
 659      * The method {@link System#gc()} is the conventional and convenient
 660      * means of invoking this method.
 661      */
 662     public native void gc();
 663 
 664     /**
 665      * Runs the finalization methods of any objects pending finalization.
 666      * Calling this method suggests that the Java virtual machine expend
 667      * effort toward running the {@code finalize} methods of objects
 668      * that have been found to be discarded but whose {@code finalize}
 669      * methods have not yet been run. When control returns from the
 670      * method call, the virtual machine has made a best effort to
 671      * complete all outstanding finalizations.
 672      * <p>
 673      * The virtual machine performs the finalization process
 674      * automatically as needed, in a separate thread, if the
 675      * {@code runFinalization} method is not invoked explicitly.
 676      * <p>
 677      * The method {@link System#runFinalization()} is the conventional
 678      * and convenient means of invoking this method.
 679      *
 680      * @see     java.lang.Object#finalize()
 681      */
 682     public void runFinalization() {
 683         SharedSecrets.getJavaLangRefAccess().runFinalization();
 684     }
 685 
 686     /**
 687      * Loads the native library specified by the filename argument.  The filename
 688      * argument must be an absolute path name.
 689      * (for example
 690      * {@code Runtime.getRuntime().load("/home/avh/lib/libX11.so");}).
 691      *
 692      * If the filename argument, when stripped of any platform-specific library
 693      * prefix, path, and file extension, indicates a library whose name is,
 694      * for example, L, and a native library called L is statically linked
 695      * with the VM, then the JNI_OnLoad_L function exported by the library
 696      * is invoked rather than attempting to load a dynamic library.
 697      * A filename matching the argument does not have to exist in the file
 698      * system.
 699      * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a>
 700      * for more details.
 701      *
 702      * Otherwise, the filename argument is mapped to a native library image in
 703      * an implementation-dependent manner.
 704      * <p>
 705      * First, if there is a security manager, its {@code checkLink}
 706      * method is called with the {@code filename} as its argument.
 707      * This may result in a security exception.
 708      * <p>
 709      * This is similar to the method {@link #loadLibrary(String)}, but it
 710      * accepts a general file name as an argument rather than just a library
 711      * name, allowing any file of native code to be loaded.
 712      * <p>
 713      * The method {@link System#load(String)} is the conventional and
 714      * convenient means of invoking this method.
 715      *
 716      * @param      filename   the file to load.
 717      * @throws     SecurityException  if a security manager exists and its
 718      *             {@code checkLink} method doesn't allow
 719      *             loading of the specified dynamic library
 720      * @throws     UnsatisfiedLinkError  if either the filename is not an
 721      *             absolute path name, the native library is not statically
 722      *             linked with the VM, or the library cannot be mapped to
 723      *             a native library image by the host system.
 724      * @throws     NullPointerException if {@code filename} is
 725      *             {@code null}
 726      * @see        java.lang.Runtime#getRuntime()
 727      * @see        java.lang.SecurityException
 728      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
 729      */
 730     @CallerSensitive
 731     public void load(String filename) {
 732         load0(Reflection.getCallerClass(), filename);
 733     }
 734 
 735     synchronized void load0(Class<?> fromClass, String filename) {
 736         SecurityManager security = System.getSecurityManager();
 737         if (security != null) {
 738             security.checkLink(filename);
 739         }
 740         if (!(new File(filename).isAbsolute())) {
 741             throw new UnsatisfiedLinkError(
 742                 "Expecting an absolute path of the library: " + filename);
 743         }
 744         ClassLoader.loadLibrary(fromClass, filename, true);
 745     }
 746 
 747     /**
 748      * Loads the native library specified by the {@code libname}
 749      * argument.  The {@code libname} argument must not contain any platform
 750      * specific prefix, file extension or path. If a native library
 751      * called {@code libname} is statically linked with the VM, then the
 752      * JNI_OnLoad_{@code libname} function exported by the library is invoked.
 753      * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a>
 754      * for more details.
 755      *
 756      * Otherwise, the libname argument is loaded from a system library
 757      * location and mapped to a native library image in an implementation-
 758      * dependent manner.
 759      * <p>
 760      * First, if there is a security manager, its {@code checkLink}
 761      * method is called with the {@code libname} as its argument.
 762      * This may result in a security exception.
 763      * <p>
 764      * The method {@link System#loadLibrary(String)} is the conventional
 765      * and convenient means of invoking this method. If native
 766      * methods are to be used in the implementation of a class, a standard
 767      * strategy is to put the native code in a library file (call it
 768      * {@code LibFile}) and then to put a static initializer:
 769      * <blockquote><pre>
 770      * static { System.loadLibrary("LibFile"); }
 771      * </pre></blockquote>
 772      * within the class declaration. When the class is loaded and
 773      * initialized, the necessary native code implementation for the native
 774      * methods will then be loaded as well.
 775      * <p>
 776      * If this method is called more than once with the same library
 777      * name, the second and subsequent calls are ignored.
 778      *
 779      * @param      libname   the name of the library.
 780      * @throws     SecurityException  if a security manager exists and its
 781      *             {@code checkLink} method doesn't allow
 782      *             loading of the specified dynamic library
 783      * @throws     UnsatisfiedLinkError if either the libname argument
 784      *             contains a file path, the native library is not statically
 785      *             linked with the VM,  or the library cannot be mapped to a
 786      *             native library image by the host system.
 787      * @throws     NullPointerException if {@code libname} is
 788      *             {@code null}
 789      * @see        java.lang.SecurityException
 790      * @see        java.lang.SecurityManager#checkLink(java.lang.String)
 791      */
 792     @CallerSensitive
 793     public void loadLibrary(String libname) {
 794         loadLibrary0(Reflection.getCallerClass(), libname);
 795     }
 796 
 797     synchronized void loadLibrary0(Class<?> fromClass, String libname) {
 798         SecurityManager security = System.getSecurityManager();
 799         if (security != null) {
 800             security.checkLink(libname);
 801         }
 802         if (libname.indexOf((int)File.separatorChar) != -1) {
 803             throw new UnsatisfiedLinkError(
 804     "Directory separator should not appear in library name: " + libname);
 805         }
 806         ClassLoader.loadLibrary(fromClass, libname, false);
 807     }
 808 
 809     /**
 810      * Returns the version of the Java Runtime Environment as a {@link Version}.
 811      *
 812      * @return  the {@link Version} of the Java Runtime Environment
 813      *
 814      * @since  9
 815      */
 816     public static Version version() {
 817         if (version == null) {
 818             version = new Version(VersionProps.versionNumbers(),
 819                     VersionProps.pre(), VersionProps.build(),
 820                     VersionProps.optional());
 821         }
 822         return version;
 823     }
 824 
 825     /**
 826      * A representation of a version string for an implementation of the
 827      * Java&nbsp;SE Platform.  A version string consists of a version number
 828      * optionally followed by pre-release and build information.
 829      *
 830      * <h2><a id="verNum">Version numbers</a></h2>
 831      *
 832      * <p> A <em>version number</em>, {@code $VNUM}, is a non-empty sequence of
 833      * elements separated by period characters (U+002E).  An element is either
 834      * zero, or an unsigned integer numeral without leading zeros.  The final
 835      * element in a version number must not be zero.  When an element is
 836      * incremented, all subsequent elements are removed.  The format is: </p>
 837      *
 838      * <blockquote><pre>
 839      * [1-9][0-9]*((\.0)*\.[1-9][0-9]*)*
 840      * </pre></blockquote>
 841      *
 842      * <p> The sequence may be of arbitrary length but the first four elements
 843      * are assigned specific meanings, as follows:</p>
 844      *
 845      * <blockquote><pre>
 846      * $FEATURE.$INTERIM.$UPDATE.$PATCH
 847      * </pre></blockquote>
 848      *
 849      * <ul>
 850      *
 851      * <li><p> <a id="FEATURE">{@code $FEATURE}</a> — The
 852      * feature-release counter, incremented for every feature release
 853      * regardless of release content.  Features may be added in a feature
 854      * release; they may also be removed, if advance notice was given at least
 855      * one feature release ahead of time.  Incompatible changes may be made
 856      * when justified. </p></li>
 857      *
 858      * <li><p> <a id="INTERIM">{@code $INTERIM}</a> — The
 859      * interim-release counter, incremented for non-feature releases that
 860      * contain compatible bug fixes and enhancements but no incompatible
 861      * changes, no feature removals, and no changes to standard APIs.
 862      * </p></li>
 863      *
 864      * <li><p> <a id="UPDATE">{@code $UPDATE}</a> — The update-release
 865      * counter, incremented for compatible update releases that fix security
 866      * issues, regressions, and bugs in newer features. </p></li>
 867      *
 868      * <li><p> <a id="PATCH">{@code $PATCH}</a> — The emergency
 869      * patch-release counter, incremented only when it's necessary to produce
 870      * an emergency release to fix a critical issue. </p></li>
 871      *
 872      * </ul>
 873      *
 874      * <p> The fifth and later elements of a version number are free for use by
 875      * platform implementors, to identify implementor-specific patch
 876      * releases. </p>
 877      *
 878      * <p> A version number never has trailing zero elements.  If an element
 879      * and all those that follow it logically have the value zero then all of
 880      * them are omitted. </p>
 881      *
 882      * <p> The sequence of numerals in a version number is compared to another
 883      * such sequence in numerical, pointwise fashion; <em>e.g.</em>, {@code
 884      * 10.0.4} is less than {@code 10.1.2}.  If one sequence is shorter than
 885      * another then the missing elements of the shorter sequence are considered
 886      * to be less than the corresponding elements of the longer sequence;
 887      * <em>e.g.</em>, {@code 10.0.2} is less than {@code 10.0.2.1}. </p>
 888      *
 889      * <h2><a id="verStr">Version strings</a></h2>
 890      *
 891      * <p> A <em>version string</em>, {@code $VSTR}, is a version number {@code
 892      * $VNUM}, as described above, optionally followed by pre-release and build
 893      * information, in one of the following formats: </p>
 894      *
 895      * <blockquote><pre>
 896      *     $VNUM(-$PRE)?\+$BUILD(-$OPT)?
 897      *     $VNUM-$PRE(-$OPT)?
 898      *     $VNUM(+-$OPT)?
 899      * </pre></blockquote>
 900      *
 901      * <p> where: </p>
 902      *
 903      * <ul>
 904      *
 905      * <li><p> <a id="pre">{@code $PRE}</a>, matching {@code ([a-zA-Z0-9]+)}
 906      * — A pre-release identifier.  Typically {@code ea}, for a
 907      * potentially unstable early-access release under active development, or
 908      * {@code internal}, for an internal developer build. </p></li>
 909      *
 910      * <li><p> <a id="build">{@code $BUILD}</a>, matching {@code
 911      * (0|[1-9][0-9]*)} — The build number, incremented for each promoted
 912      * build.  {@code $BUILD} is reset to {@code 1} when any portion of {@code
 913      * $VNUM} is incremented. </p></li>
 914      *
 915      * <li><p> <a id="opt">{@code $OPT}</a>, matching {@code ([-a-zA-Z0-9.]+)}
 916      * — Additional build information, if desired.  In the case of an
 917      * {@code internal} build this will often contain the date and time of the
 918      * build. </p></li>
 919      *
 920      * </ul>
 921      *
 922      * <p> A version string {@code 10-ea} matches {@code $VNUM = "10"} and
 923      * {@code $PRE = "ea"}.  The version string {@code 10+-ea} matches
 924      * {@code $VNUM = "10"} and {@code $OPT = "ea"}. </p>
 925      *
 926      * <p> When comparing two version strings, the value of {@code $OPT}, if
 927      * present, may or may not be significant depending on the chosen
 928      * comparison method.  The comparison methods {@link #compareTo(Version)
 929      * compareTo()} and {@link #compareToIgnoreOptional(Version)
 930      * compareToIgnoreOptional()} should be used consistently with the
 931      * corresponding methods {@link #equals(Object) equals()} and {@link
 932      * #equalsIgnoreOptional(Object) equalsIgnoreOptional()}.  </p>
 933      *
 934      * <p> A <em>short version string</em>, {@code $SVSTR}, often useful in
 935      * less formal contexts, is a version number optionally followed by a
 936      * pre-release identifier:</p>
 937      *
 938      * <blockquote><pre>
 939      *     $VNUM(-$PRE)?
 940      * </pre></blockquote>
 941      *
 942      * <p>This is a <a href="./doc-files/ValueBased.html">value-based</a>
 943      * class; use of identity-sensitive operations (including reference equality
 944      * ({@code ==}), identity hash code, or synchronization) on instances of
 945      * {@code Version} may have unpredictable results and should be avoided.
 946      * </p>
 947      *
 948      * @since  9
 949      */
 950     public static final class Version
 951         implements Comparable<Version>
 952     {
 953         private final List<Integer>     version;
 954         private final Optional<String>  pre;
 955         private final Optional<Integer> build;
 956         private final Optional<String>  optional;
 957 
 958         /*
 959          * List of version number components passed to this constructor MUST
 960          * be at least unmodifiable (ideally immutable). In the case on an
 961          * unmodifiable list, the caller MUST hand the list over to this
 962          * constructor and never change the underlying list.
 963          */
 964         private Version(List<Integer> unmodifiableListOfVersions,
 965                         Optional<String> pre,
 966                         Optional<Integer> build,
 967                         Optional<String> optional)
 968         {
 969             this.version = unmodifiableListOfVersions;
 970             this.pre = pre;
 971             this.build = build;
 972             this.optional = optional;
 973         }
 974 
 975         /**
 976          * Parses the given string as a valid
 977          * <a href="#verStr">version string</a> containing a
 978          * <a href="#verNum">version number</a> followed by pre-release and
 979          * build information.
 980          *
 981          * @param  s
 982          *         A string to interpret as a version
 983          *
 984          * @throws  IllegalArgumentException
 985          *          If the given string cannot be interpreted as a valid
 986          *          version
 987          *
 988          * @throws  NullPointerException
 989          *          If the given string is {@code null}
 990          *
 991          * @throws  NumberFormatException
 992          *          If an element of the version number or the build number
 993          *          cannot be represented as an {@link Integer}
 994          *
 995          * @return  The Version of the given string
 996          */
 997         public static Version parse(String s) {
 998             if (s == null)
 999                 throw new NullPointerException();
1000 
1001             // Shortcut to avoid initializing VersionPattern when creating
1002             // feature-version constants during startup
1003             if (isSimpleNumber(s)) {
1004                 return new Version(List.of(Integer.parseInt(s)),
1005                         Optional.empty(), Optional.empty(), Optional.empty());
1006             }
1007             Matcher m = VersionPattern.VSTR_PATTERN.matcher(s);
1008             if (!m.matches())
1009                 throw new IllegalArgumentException("Invalid version string: '"
1010                                                    + s + "'");
1011 
1012             // $VNUM is a dot-separated list of integers of arbitrary length
1013             String[] split = m.group(VersionPattern.VNUM_GROUP).split("\\.");
1014             Integer[] version = new Integer[split.length];
1015             for (int i = 0; i < split.length; i++) {
1016                 version[i] = Integer.parseInt(split[i]);
1017             }
1018 
1019             Optional<String> pre = Optional.ofNullable(
1020                     m.group(VersionPattern.PRE_GROUP));
1021 
1022             String b = m.group(VersionPattern.BUILD_GROUP);
1023             // $BUILD is an integer
1024             Optional<Integer> build = (b == null)
1025                 ? Optional.empty()
1026                 : Optional.of(Integer.parseInt(b));
1027 
1028             Optional<String> optional = Optional.ofNullable(
1029                     m.group(VersionPattern.OPT_GROUP));
1030 
1031             // empty '+'
1032             if (!build.isPresent()) {
1033                 if (m.group(VersionPattern.PLUS_GROUP) != null) {
1034                     if (optional.isPresent()) {
1035                         if (pre.isPresent())
1036                             throw new IllegalArgumentException("'+' found with"
1037                                 + " pre-release and optional components:'" + s
1038                                 + "'");
1039                     } else {
1040                         throw new IllegalArgumentException("'+' found with neither"
1041                             + " build or optional components: '" + s + "'");
1042                     }
1043                 } else {
1044                     if (optional.isPresent() && !pre.isPresent()) {
1045                         throw new IllegalArgumentException("optional component"
1046                             + " must be preceeded by a pre-release component"
1047                             + " or '+': '" + s + "'");
1048                     }
1049                 }
1050             }
1051             return new Version(List.of(version), pre, build, optional);
1052         }
1053 
1054         private static boolean isSimpleNumber(String s) {
1055             for (int i = 0; i < s.length(); i++) {
1056                 char c = s.charAt(i);
1057                 char lowerBound = (i > 0) ? '0' : '1';
1058                 if (c < lowerBound || c > '9') {
1059                     return false;
1060                 }
1061             }
1062             return true;
1063         }
1064 
1065         /**
1066          * Returns the value of the <a href="#FEATURE">feature</a> element of
1067          * the version number.
1068          *
1069          * @return The value of the feature element
1070          *
1071          * @since 10
1072          */
1073         public int feature() {
1074             return version.get(0);
1075         }
1076 
1077         /**
1078          * Returns the value of the <a href="#INTERIM">interim</a> element of
1079          * the version number, or zero if it is absent.
1080          *
1081          * @return The value of the interim element, or zero
1082          *
1083          * @since 10
1084          */
1085         public int interim() {
1086             return (version.size() > 1 ? version.get(1) : 0);
1087         }
1088 
1089         /**
1090          * Returns the value of the <a href="#UPDATE">update</a> element of the
1091          * version number, or zero if it is absent.
1092          *
1093          * @return The value of the update element, or zero
1094          *
1095          * @since 10
1096          */
1097         public int update() {
1098             return (version.size() > 2 ? version.get(2) : 0);
1099         }
1100 
1101         /**
1102          * Returns the value of the <a href="#PATCH">patch</a> element of the
1103          * version number, or zero if it is absent.
1104          *
1105          * @return The value of the patch element, or zero
1106          *
1107          * @since 10
1108          */
1109         public int patch() {
1110             return (version.size() > 3 ? version.get(3) : 0);
1111         }
1112 
1113         /**
1114          * Returns the value of the major element of the version number.
1115          *
1116          * @deprecated As of Java&nbsp;SE 10, the first element of a version
1117          * number is not the major-release number but the feature-release
1118          * counter, incremented for every time-based release.  Use the {@link
1119          * #feature()} method in preference to this method.  For compatibility,
1120          * this method returns the value of the <a href="#FEATURE">feature</a>
1121          * element.
1122          *
1123          * @return The value of the feature element
1124          */
1125         @Deprecated(since = "10")
1126         public int major() {
1127             return feature();
1128         }
1129 
1130         /**
1131          * Returns the value of the minor element of the version number, or
1132          * zero if it is absent.
1133          *
1134          * @deprecated As of Java&nbsp;SE 10, the second element of a version
1135          * number is not the minor-release number but the interim-release
1136          * counter, incremented for every interim release.  Use the {@link
1137          * #interim()} method in preference to this method.  For compatibility,
1138          * this method returns the value of the <a href="#INTERIM">interim</a>
1139          * element, or zero if it is absent.
1140          *
1141          * @return The value of the interim element, or zero
1142          */
1143         @Deprecated(since = "10")
1144         public int minor() {
1145             return interim();
1146         }
1147 
1148         /**
1149          * Returns the value of the security element of the version number, or
1150          * zero if it is absent.
1151          *
1152          * @deprecated As of Java&nbsp;SE 10, the third element of a version
1153          * number is not the security level but the update-release counter,
1154          * incremented for every update release.  Use the {@link #update()}
1155          * method in preference to this method.  For compatibility, this method
1156          * returns the value of the <a href="#UPDATE">update</a> element, or
1157          * zero if it is absent.
1158          *
1159          * @return  The value of the update element, or zero
1160          */
1161         @Deprecated(since = "10")
1162         public int security() {
1163             return update();
1164         }
1165 
1166         /**
1167          * Returns an unmodifiable {@link java.util.List List} of the integers
1168          * represented in the <a href="#verNum">version number</a>.
1169          * The {@code List} always contains at least one element corresponding to
1170          * the <a href="#FEATURE">feature version number</a>.
1171          *
1172          * @return  An unmodifiable list of the integers
1173          *          represented in the version number
1174          */
1175         public List<Integer> version() {
1176             return version;
1177         }
1178 
1179         /**
1180          * Returns the optional <a href="#pre">pre-release</a> information.
1181          *
1182          * @return  The optional pre-release information as a String
1183          */
1184         public Optional<String> pre() {
1185             return pre;
1186         }
1187 
1188         /**
1189          * Returns the <a href="#build">build number</a>.
1190          *
1191          * @return  The optional build number.
1192          */
1193         public Optional<Integer> build() {
1194             return build;
1195         }
1196 
1197         /**
1198          * Returns <a href="#opt">optional</a> additional identifying build
1199          * information.
1200          *
1201          * @return  Additional build information as a String
1202          */
1203         public Optional<String> optional() {
1204             return optional;
1205         }
1206 
1207         /**
1208          * Compares this version to another.
1209          *
1210          * <p> Each of the components in the <a href="#verStr">version</a> is
1211          * compared in the following order of precedence: version numbers,
1212          * pre-release identifiers, build numbers, optional build information.
1213          * </p>
1214          *
1215          * <p> Comparison begins by examining the sequence of version numbers.
1216          * If one sequence is shorter than another, then the missing elements
1217          * of the shorter sequence are considered to be less than the
1218          * corresponding elements of the longer sequence. </p>
1219          *
1220          * <p> A version with a pre-release identifier is always considered to
1221          * be less than a version without one.  Pre-release identifiers are
1222          * compared numerically when they consist only of digits, and
1223          * lexicographically otherwise.  Numeric identifiers are considered to
1224          * be less than non-numeric identifiers.  </p>
1225          *
1226          * <p> A version without a build number is always less than one with a
1227          * build number; otherwise build numbers are compared numerically. </p>
1228          *
1229          * <p> The optional build information is compared lexicographically.
1230          * During this comparison, a version with optional build information is
1231          * considered to be greater than a version without one. </p>
1232          *
1233          * @param  obj
1234          *         The object to be compared
1235          *
1236          * @return  A negative integer, zero, or a positive integer if this
1237          *          {@code Version} is less than, equal to, or greater than the
1238          *          given {@code Version}
1239          *
1240          * @throws  NullPointerException
1241          *          If the given object is {@code null}
1242          */
1243         @Override
1244         public int compareTo(Version obj) {
1245             return compare(obj, false);
1246         }
1247 
1248         /**
1249          * Compares this version to another disregarding optional build
1250          * information.
1251          *
1252          * <p> Two versions are compared by examining the version string as
1253          * described in {@link #compareTo(Version)} with the exception that the
1254          * optional build information is always ignored. </p>
1255          *
1256          * <p> This method provides ordering which is consistent with
1257          * {@code equalsIgnoreOptional()}. </p>
1258          *
1259          * @param  obj
1260          *         The object to be compared
1261          *
1262          * @return  A negative integer, zero, or a positive integer if this
1263          *          {@code Version} is less than, equal to, or greater than the
1264          *          given {@code Version}
1265          *
1266          * @throws  NullPointerException
1267          *          If the given object is {@code null}
1268          */
1269         public int compareToIgnoreOptional(Version obj) {
1270             return compare(obj, true);
1271         }
1272 
1273         private int compare(Version obj, boolean ignoreOpt) {
1274             if (obj == null)
1275                 throw new NullPointerException();
1276 
1277             int ret = compareVersion(obj);
1278             if (ret != 0)
1279                 return ret;
1280 
1281             ret = comparePre(obj);
1282             if (ret != 0)
1283                 return ret;
1284 
1285             ret = compareBuild(obj);
1286             if (ret != 0)
1287                 return ret;
1288 
1289             if (!ignoreOpt)
1290                 return compareOptional(obj);
1291 
1292             return 0;
1293         }
1294 
1295         private int compareVersion(Version obj) {
1296             int size = version.size();
1297             int oSize = obj.version().size();
1298             int min = Math.min(size, oSize);
1299             for (int i = 0; i < min; i++) {
1300                 int val = version.get(i);
1301                 int oVal = obj.version().get(i);
1302                 if (val != oVal)
1303                     return val - oVal;
1304             }
1305             return size - oSize;
1306         }
1307 
1308         private int comparePre(Version obj) {
1309             Optional<String> oPre = obj.pre();
1310             if (!pre.isPresent()) {
1311                 if (oPre.isPresent())
1312                     return 1;
1313             } else {
1314                 if (!oPre.isPresent())
1315                     return -1;
1316                 String val = pre.get();
1317                 String oVal = oPre.get();
1318                 if (val.matches("\\d+")) {
1319                     return (oVal.matches("\\d+")
1320                         ? (new BigInteger(val)).compareTo(new BigInteger(oVal))
1321                         : -1);
1322                 } else {
1323                     return (oVal.matches("\\d+")
1324                         ? 1
1325                         : val.compareTo(oVal));
1326                 }
1327             }
1328             return 0;
1329         }
1330 
1331         private int compareBuild(Version obj) {
1332             Optional<Integer> oBuild = obj.build();
1333             if (oBuild.isPresent()) {
1334                 return (build.isPresent()
1335                         ? build.get().compareTo(oBuild.get())
1336                         : -1);
1337             } else if (build.isPresent()) {
1338                 return 1;
1339             }
1340             return 0;
1341         }
1342 
1343         private int compareOptional(Version obj) {
1344             Optional<String> oOpt = obj.optional();
1345             if (!optional.isPresent()) {
1346                 if (oOpt.isPresent())
1347                     return -1;
1348             } else {
1349                 if (!oOpt.isPresent())
1350                     return 1;
1351                 return optional.get().compareTo(oOpt.get());
1352             }
1353             return 0;
1354         }
1355 
1356         /**
1357          * Returns a string representation of this version.
1358          *
1359          * @return  The version string
1360          */
1361         @Override
1362         public String toString() {
1363             StringBuilder sb
1364                 = new StringBuilder(version.stream()
1365                     .map(Object::toString)
1366                     .collect(Collectors.joining(".")));
1367 
1368             pre.ifPresent(v -> sb.append("-").append(v));
1369 
1370             if (build.isPresent()) {
1371                 sb.append("+").append(build.get());
1372                 if (optional.isPresent())
1373                     sb.append("-").append(optional.get());
1374             } else {
1375                 if (optional.isPresent()) {
1376                     sb.append(pre.isPresent() ? "-" : "+-");
1377                     sb.append(optional.get());
1378                 }
1379             }
1380 
1381             return sb.toString();
1382         }
1383 
1384         /**
1385          * Determines whether this {@code Version} is equal to another object.
1386          *
1387          * <p> Two {@code Version}s are equal if and only if they represent the
1388          * same version string.
1389          *
1390          * @param  obj
1391          *         The object to which this {@code Version} is to be compared
1392          *
1393          * @return  {@code true} if, and only if, the given object is a {@code
1394          *          Version} that is identical to this {@code Version}
1395          *
1396          */
1397         @Override
1398         public boolean equals(Object obj) {
1399             boolean ret = equalsIgnoreOptional(obj);
1400             if (!ret)
1401                 return false;
1402 
1403             Version that = (Version)obj;
1404             return (this.optional().equals(that.optional()));
1405         }
1406 
1407         /**
1408          * Determines whether this {@code Version} is equal to another
1409          * disregarding optional build information.
1410          *
1411          * <p> Two {@code Version}s are equal if and only if they represent the
1412          * same version string disregarding the optional build information.
1413          *
1414          * @param  obj
1415          *         The object to which this {@code Version} is to be compared
1416          *
1417          * @return  {@code true} if, and only if, the given object is a {@code
1418          *          Version} that is identical to this {@code Version}
1419          *          ignoring the optional build information
1420          *
1421          */
1422         public boolean equalsIgnoreOptional(Object obj) {
1423             if (this == obj)
1424                 return true;
1425             if (!(obj instanceof Version))
1426                 return false;
1427 
1428             Version that = (Version)obj;
1429             return (this.version().equals(that.version())
1430                 && this.pre().equals(that.pre())
1431                 && this.build().equals(that.build()));
1432         }
1433 
1434         /**
1435          * Returns the hash code of this version.
1436          *
1437          * @return  The hashcode of this version
1438          */
1439         @Override
1440         public int hashCode() {
1441             int h = 1;
1442             int p = 17;
1443 
1444             h = p * h + version.hashCode();
1445             h = p * h + pre.hashCode();
1446             h = p * h + build.hashCode();
1447             h = p * h + optional.hashCode();
1448 
1449             return h;
1450         }
1451     }
1452 
1453     private static class VersionPattern {
1454         // $VNUM(-$PRE)?(\+($BUILD)?(\-$OPT)?)?
1455         // RE limits the format of version strings
1456         // ([1-9][0-9]*(?:(?:\.0)*\.[1-9][0-9]*)*)(?:-([a-zA-Z0-9]+))?(?:(\+)(0|[1-9][0-9]*)?)?(?:-([-a-zA-Z0-9.]+))?
1457 
1458         private static final String VNUM
1459             = "(?<VNUM>[1-9][0-9]*(?:(?:\\.0)*\\.[1-9][0-9]*)*)";
1460         private static final String PRE      = "(?:-(?<PRE>[a-zA-Z0-9]+))?";
1461         private static final String BUILD
1462             = "(?:(?<PLUS>\\+)(?<BUILD>0|[1-9][0-9]*)?)?";
1463         private static final String OPT      = "(?:-(?<OPT>[-a-zA-Z0-9.]+))?";
1464         private static final String VSTR_FORMAT = VNUM + PRE + BUILD + OPT;
1465 
1466         static final Pattern VSTR_PATTERN = Pattern.compile(VSTR_FORMAT);
1467 
1468         static final String VNUM_GROUP  = "VNUM";
1469         static final String PRE_GROUP   = "PRE";
1470         static final String PLUS_GROUP  = "PLUS";
1471         static final String BUILD_GROUP = "BUILD";
1472         static final String OPT_GROUP   = "OPT";
1473     }
1474 }