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