1 /* 2 * Copyright (c) 1995, 2018, 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 * 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 * There is no guarantee that this effort will recycle any particular 649 * number of unused objects, reclaim any particular amount of space, 650 * or complete at any particular time, if at all. 651 * <p> 652 * The name {@code gc} stands for "garbage 653 * collector". The Java Virtual Machine performs this recycling 654 * process automatically as needed, in a separate thread, even if the 655 * {@code gc} method is not invoked explicitly. 656 * <p> 657 * The method {@link System#gc()} is the conventional and convenient 658 * means of invoking this method. 659 */ 660 public native void gc(); 661 662 /** 663 * Runs the finalization methods of any objects pending finalization. 664 * Calling this method suggests that the Java virtual machine expend 665 * effort toward running the {@code finalize} methods of objects 666 * that have been found to be discarded but whose {@code finalize} 667 * methods have not yet been run. When control returns from the 668 * method call, the virtual machine has made a best effort to 669 * complete all outstanding finalizations. 670 * <p> 671 * The virtual machine performs the finalization process 672 * automatically as needed, in a separate thread, if the 673 * {@code runFinalization} method is not invoked explicitly. 674 * <p> 675 * The method {@link System#runFinalization()} is the conventional 676 * and convenient means of invoking this method. 677 * 678 * @see java.lang.Object#finalize() 679 */ 680 public void runFinalization() { 681 SharedSecrets.getJavaLangRefAccess().runFinalization(); 682 } 683 684 /** 685 * Not implemented, does nothing. 686 * 687 * @deprecated 688 * This method was intended to control instruction tracing. 689 * It has been superseded by JVM-specific tracing mechanisms. 690 * This method is subject to removal in a future version of Java SE. 691 * 692 * @param on ignored 693 */ 694 @Deprecated(since="9", forRemoval=true) 695 public void traceInstructions(boolean on) { } 696 697 /** 698 * Not implemented, does nothing. 699 * 700 * @deprecated 701 * This method was intended to control method call tracing. 702 * It has been superseded by JVM-specific tracing mechanisms. 703 * This method is subject to removal in a future version of Java SE. 704 * 705 * @param on ignored 706 */ 707 @Deprecated(since="9", forRemoval=true) 708 public void traceMethodCalls(boolean on) { } 709 710 /** 711 * Loads the native library specified by the filename argument. The filename 712 * argument must be an absolute path name. 713 * (for example 714 * {@code Runtime.getRuntime().load("/home/avh/lib/libX11.so");}). 715 * 716 * If the filename argument, when stripped of any platform-specific library 717 * prefix, path, and file extension, indicates a library whose name is, 718 * for example, L, and a native library called L is statically linked 719 * with the VM, then the JNI_OnLoad_L function exported by the library 720 * is invoked rather than attempting to load a dynamic library. 721 * A filename matching the argument does not have to exist in the file 722 * system. 723 * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a> 724 * for more details. 725 * 726 * Otherwise, the filename argument is mapped to a native library image in 727 * an implementation-dependent manner. 728 * <p> 729 * First, if there is a security manager, its {@code checkLink} 730 * method is called with the {@code filename} as its argument. 731 * This may result in a security exception. 732 * <p> 733 * This is similar to the method {@link #loadLibrary(String)}, but it 734 * accepts a general file name as an argument rather than just a library 735 * name, allowing any file of native code to be loaded. 736 * <p> 737 * The method {@link System#load(String)} is the conventional and 738 * convenient means of invoking this method. 739 * 740 * @param filename the file to load. 741 * @throws SecurityException if a security manager exists and its 742 * {@code checkLink} method doesn't allow 743 * loading of the specified dynamic library 744 * @throws UnsatisfiedLinkError if either the filename is not an 745 * absolute path name, the native library is not statically 746 * linked with the VM, or the library cannot be mapped to 747 * a native library image by the host system. 748 * @throws NullPointerException if {@code filename} is 749 * {@code null} 750 * @see java.lang.Runtime#getRuntime() 751 * @see java.lang.SecurityException 752 * @see java.lang.SecurityManager#checkLink(java.lang.String) 753 */ 754 @CallerSensitive 755 public void load(String filename) { 756 load0(Reflection.getCallerClass(), filename); 757 } 758 759 synchronized void load0(Class<?> fromClass, String filename) { 760 SecurityManager security = System.getSecurityManager(); 761 if (security != null) { 762 security.checkLink(filename); 763 } 764 if (!(new File(filename).isAbsolute())) { 765 throw new UnsatisfiedLinkError( 766 "Expecting an absolute path of the library: " + filename); 767 } 768 ClassLoader.loadLibrary(fromClass, filename, true); 769 } 770 771 /** 772 * Loads the native library specified by the {@code libname} 773 * argument. The {@code libname} argument must not contain any platform 774 * specific prefix, file extension or path. If a native library 775 * called {@code libname} is statically linked with the VM, then the 776 * JNI_OnLoad_{@code libname} function exported by the library is invoked. 777 * See the <a href="{@docRoot}/../specs/jni/index.html"> JNI Specification</a> 778 * for more details. 779 * 780 * Otherwise, the libname argument is loaded from a system library 781 * location and mapped to a native library image in an implementation- 782 * dependent manner. 783 * <p> 784 * First, if there is a security manager, its {@code checkLink} 785 * method is called with the {@code libname} as its argument. 786 * This may result in a security exception. 787 * <p> 788 * The method {@link System#loadLibrary(String)} is the conventional 789 * and convenient means of invoking this method. If native 790 * methods are to be used in the implementation of a class, a standard 791 * strategy is to put the native code in a library file (call it 792 * {@code LibFile}) and then to put a static initializer: 793 * <blockquote><pre> 794 * static { System.loadLibrary("LibFile"); } 795 * </pre></blockquote> 796 * within the class declaration. When the class is loaded and 797 * initialized, the necessary native code implementation for the native 798 * methods will then be loaded as well. 799 * <p> 800 * If this method is called more than once with the same library 801 * name, the second and subsequent calls are ignored. 802 * 803 * @param libname the name of the library. 804 * @throws SecurityException if a security manager exists and its 805 * {@code checkLink} method doesn't allow 806 * loading of the specified dynamic library 807 * @throws UnsatisfiedLinkError if either the libname argument 808 * contains a file path, the native library is not statically 809 * linked with the VM, or the library cannot be mapped to a 810 * native library image by the host system. 811 * @throws NullPointerException if {@code libname} is 812 * {@code null} 813 * @see java.lang.SecurityException 814 * @see java.lang.SecurityManager#checkLink(java.lang.String) 815 */ 816 @CallerSensitive 817 public void loadLibrary(String libname) { 818 loadLibrary0(Reflection.getCallerClass(), libname); 819 } 820 821 synchronized void loadLibrary0(Class<?> fromClass, String libname) { 822 SecurityManager security = System.getSecurityManager(); 823 if (security != null) { 824 security.checkLink(libname); 825 } 826 if (libname.indexOf((int)File.separatorChar) != -1) { 827 throw new UnsatisfiedLinkError( 828 "Directory separator should not appear in library name: " + libname); 829 } 830 ClassLoader.loadLibrary(fromClass, libname, false); 831 } 832 833 /** 834 * Returns the version of the Java Runtime Environment as a {@link Version}. 835 * 836 * @return the {@link Version} of the Java Runtime Environment 837 * 838 * @since 9 839 */ 840 public static Version version() { 841 if (version == null) { 842 version = new Version(VersionProps.versionNumbers(), 843 VersionProps.pre(), VersionProps.build(), 844 VersionProps.optional()); 845 } 846 return version; 847 } 848 849 /** 850 * A representation of a version string for an implementation of the 851 * Java SE Platform. A version string consists of a version number 852 * optionally followed by pre-release and build information. 853 * 854 * <h2><a id="verNum">Version numbers</a></h2> 855 * 856 * <p> A <em>version number</em>, {@code $VNUM}, is a non-empty sequence of 857 * elements separated by period characters (U+002E). An element is either 858 * zero, or an unsigned integer numeral without leading zeros. The final 859 * element in a version number must not be zero. When an element is 860 * incremented, all subsequent elements are removed. The format is: </p> 861 * 862 * <blockquote><pre> 863 * [1-9][0-9]*((\.0)*\.[1-9][0-9]*)* 864 * </pre></blockquote> 865 * 866 * <p> The sequence may be of arbitrary length but the first four elements 867 * are assigned specific meanings, as follows:</p> 868 * 869 * <blockquote><pre> 870 * $FEATURE.$INTERIM.$UPDATE.$PATCH 871 * </pre></blockquote> 872 * 873 * <ul> 874 * 875 * <li><p> <a id="FEATURE">{@code $FEATURE}</a> — The 876 * feature-release counter, incremented for every feature release 877 * regardless of release content. Features may be added in a feature 878 * release; they may also be removed, if advance notice was given at least 879 * one feature release ahead of time. Incompatible changes may be made 880 * when justified. </p></li> 881 * 882 * <li><p> <a id="INTERIM">{@code $INTERIM}</a> — The 883 * interim-release counter, incremented for non-feature releases that 884 * contain compatible bug fixes and enhancements but no incompatible 885 * changes, no feature removals, and no changes to standard APIs. 886 * </p></li> 887 * 888 * <li><p> <a id="UPDATE">{@code $UPDATE}</a> — The update-release 889 * counter, incremented for compatible update releases that fix security 890 * issues, regressions, and bugs in newer features. </p></li> 891 * 892 * <li><p> <a id="PATCH">{@code $PATCH}</a> — The emergency 893 * patch-release counter, incremented only when it's necessary to produce 894 * an emergency release to fix a critical issue. </p></li> 895 * 896 * </ul> 897 * 898 * <p> The fifth and later elements of a version number are free for use by 899 * platform implementors, to identify implementor-specific patch 900 * releases. </p> 901 * 902 * <p> A version number never has trailing zero elements. If an element 903 * and all those that follow it logically have the value zero then all of 904 * them are omitted. </p> 905 * 906 * <p> The sequence of numerals in a version number is compared to another 907 * such sequence in numerical, pointwise fashion; <em>e.g.</em>, {@code 908 * 10.0.4} is less than {@code 10.1.2}. If one sequence is shorter than 909 * another then the missing elements of the shorter sequence are considered 910 * to be less than the corresponding elements of the longer sequence; 911 * <em>e.g.</em>, {@code 10.0.2} is less than {@code 10.0.2.1}. </p> 912 * 913 * <h2><a id="verStr">Version strings</a></h2> 914 * 915 * <p> A <em>version string</em>, {@code $VSTR}, is a version number {@code 916 * $VNUM}, as described above, optionally followed by pre-release and build 917 * information, in one of the following formats: </p> 918 * 919 * <blockquote><pre> 920 * $VNUM(-$PRE)?\+$BUILD(-$OPT)? 921 * $VNUM-$PRE(-$OPT)? 922 * $VNUM(+-$OPT)? 923 * </pre></blockquote> 924 * 925 * <p> where: </p> 926 * 927 * <ul> 928 * 929 * <li><p> <a id="pre">{@code $PRE}</a>, matching {@code ([a-zA-Z0-9]+)} 930 * — A pre-release identifier. Typically {@code ea}, for a 931 * potentially unstable early-access release under active development, or 932 * {@code internal}, for an internal developer build. </p></li> 933 * 934 * <li><p> <a id="build">{@code $BUILD}</a>, matching {@code 935 * (0|[1-9][0-9]*)} — The build number, incremented for each promoted 936 * build. {@code $BUILD} is reset to {@code 1} when any portion of {@code 937 * $VNUM} is incremented. </p></li> 938 * 939 * <li><p> <a id="opt">{@code $OPT}</a>, matching {@code ([-a-zA-Z0-9.]+)} 940 * — Additional build information, if desired. In the case of an 941 * {@code internal} build this will often contain the date and time of the 942 * build. </p></li> 943 * 944 * </ul> 945 * 946 * <p> A version string {@code 10-ea} matches {@code $VNUM = "10"} and 947 * {@code $PRE = "ea"}. The version string {@code 10+-ea} matches 948 * {@code $VNUM = "10"} and {@code $OPT = "ea"}. </p> 949 * 950 * <p> When comparing two version strings, the value of {@code $OPT}, if 951 * present, may or may not be significant depending on the chosen 952 * comparison method. The comparison methods {@link #compareTo(Version) 953 * compareTo()} and {@link #compareToIgnoreOptional(Version) 954 * compareToIgnoreOptional()} should be used consistently with the 955 * corresponding methods {@link #equals(Object) equals()} and {@link 956 * #equalsIgnoreOptional(Object) equalsIgnoreOptional()}. </p> 957 * 958 * <p> A <em>short version string</em>, {@code $SVSTR}, often useful in 959 * less formal contexts, is a version number optionally followed by a 960 * pre-release identifier:</p> 961 * 962 * <blockquote><pre> 963 * $VNUM(-$PRE)? 964 * </pre></blockquote> 965 * 966 * <p>This is a <a href="./doc-files/ValueBased.html">value-based</a> 967 * class; use of identity-sensitive operations (including reference equality 968 * ({@code ==}), identity hash code, or synchronization) on instances of 969 * {@code Version} may have unpredictable results and should be avoided. 970 * </p> 971 * 972 * @since 9 973 */ 974 public static final class Version 975 implements Comparable<Version> 976 { 977 private final List<Integer> version; 978 private final Optional<String> pre; 979 private final Optional<Integer> build; 980 private final Optional<String> optional; 981 982 /* 983 * List of version number components passed to this constructor MUST 984 * be at least unmodifiable (ideally immutable). In the case on an 985 * unmodifiable list, the caller MUST hand the list over to this 986 * constructor and never change the underlying list. 987 */ 988 private Version(List<Integer> unmodifiableListOfVersions, 989 Optional<String> pre, 990 Optional<Integer> build, 991 Optional<String> optional) 992 { 993 this.version = unmodifiableListOfVersions; 994 this.pre = pre; 995 this.build = build; 996 this.optional = optional; 997 } 998 999 /** 1000 * Parses the given string as a valid 1001 * <a href="#verStr">version string</a> containing a 1002 * <a href="#verNum">version number</a> followed by pre-release and 1003 * build information. 1004 * 1005 * @param s 1006 * A string to interpret as a version 1007 * 1008 * @throws IllegalArgumentException 1009 * If the given string cannot be interpreted as a valid 1010 * version 1011 * 1012 * @throws NullPointerException 1013 * If the given string is {@code null} 1014 * 1015 * @throws NumberFormatException 1016 * If an element of the version number or the build number 1017 * cannot be represented as an {@link Integer} 1018 * 1019 * @return The Version of the given string 1020 */ 1021 public static Version parse(String s) { 1022 if (s == null) 1023 throw new NullPointerException(); 1024 1025 // Shortcut to avoid initializing VersionPattern when creating 1026 // feature-version constants during startup 1027 if (isSimpleNumber(s)) { 1028 return new Version(List.of(Integer.parseInt(s)), 1029 Optional.empty(), Optional.empty(), Optional.empty()); 1030 } 1031 Matcher m = VersionPattern.VSTR_PATTERN.matcher(s); 1032 if (!m.matches()) 1033 throw new IllegalArgumentException("Invalid version string: '" 1034 + s + "'"); 1035 1036 // $VNUM is a dot-separated list of integers of arbitrary length 1037 String[] split = m.group(VersionPattern.VNUM_GROUP).split("\\."); 1038 Integer[] version = new Integer[split.length]; 1039 for (int i = 0; i < split.length; i++) { 1040 version[i] = Integer.parseInt(split[i]); 1041 } 1042 1043 Optional<String> pre = Optional.ofNullable( 1044 m.group(VersionPattern.PRE_GROUP)); 1045 1046 String b = m.group(VersionPattern.BUILD_GROUP); 1047 // $BUILD is an integer 1048 Optional<Integer> build = (b == null) 1049 ? Optional.empty() 1050 : Optional.of(Integer.parseInt(b)); 1051 1052 Optional<String> optional = Optional.ofNullable( 1053 m.group(VersionPattern.OPT_GROUP)); 1054 1055 // empty '+' 1056 if (!build.isPresent()) { 1057 if (m.group(VersionPattern.PLUS_GROUP) != null) { 1058 if (optional.isPresent()) { 1059 if (pre.isPresent()) 1060 throw new IllegalArgumentException("'+' found with" 1061 + " pre-release and optional components:'" + s 1062 + "'"); 1063 } else { 1064 throw new IllegalArgumentException("'+' found with neither" 1065 + " build or optional components: '" + s + "'"); 1066 } 1067 } else { 1068 if (optional.isPresent() && !pre.isPresent()) { 1069 throw new IllegalArgumentException("optional component" 1070 + " must be preceeded by a pre-release component" 1071 + " or '+': '" + s + "'"); 1072 } 1073 } 1074 } 1075 return new Version(List.of(version), pre, build, optional); 1076 } 1077 1078 private static boolean isSimpleNumber(String s) { 1079 for (int i = 0; i < s.length(); i++) { 1080 char c = s.charAt(i); 1081 char lowerBound = (i > 0) ? '0' : '1'; 1082 if (c < lowerBound || c > '9') { 1083 return false; 1084 } 1085 } 1086 return true; 1087 } 1088 1089 /** 1090 * Returns the value of the <a href="#FEATURE">feature</a> element of 1091 * the version number. 1092 * 1093 * @return The value of the feature element 1094 * 1095 * @since 10 1096 */ 1097 public int feature() { 1098 return version.get(0); 1099 } 1100 1101 /** 1102 * Returns the value of the <a href="#INTERIM">interim</a> element of 1103 * the version number, or zero if it is absent. 1104 * 1105 * @return The value of the interim element, or zero 1106 * 1107 * @since 10 1108 */ 1109 public int interim() { 1110 return (version.size() > 1 ? version.get(1) : 0); 1111 } 1112 1113 /** 1114 * Returns the value of the <a href="#UPDATE">update</a> element of the 1115 * version number, or zero if it is absent. 1116 * 1117 * @return The value of the update element, or zero 1118 * 1119 * @since 10 1120 */ 1121 public int update() { 1122 return (version.size() > 2 ? version.get(2) : 0); 1123 } 1124 1125 /** 1126 * Returns the value of the <a href="#PATCH">patch</a> element of the 1127 * version number, or zero if it is absent. 1128 * 1129 * @return The value of the patch element, or zero 1130 * 1131 * @since 10 1132 */ 1133 public int patch() { 1134 return (version.size() > 3 ? version.get(3) : 0); 1135 } 1136 1137 /** 1138 * Returns the value of the major element of the version number. 1139 * 1140 * @deprecated As of Java SE 10, the first element of a version 1141 * number is not the major-release number but the feature-release 1142 * counter, incremented for every time-based release. Use the {@link 1143 * #feature()} method in preference to this method. For compatibility, 1144 * this method returns the value of the <a href="#FEATURE">feature</a> 1145 * element. 1146 * 1147 * @return The value of the feature element 1148 */ 1149 @Deprecated(since = "10") 1150 public int major() { 1151 return feature(); 1152 } 1153 1154 /** 1155 * Returns the value of the minor element of the version number, or 1156 * zero if it is absent. 1157 * 1158 * @deprecated As of Java SE 10, the second element of a version 1159 * number is not the minor-release number but the interim-release 1160 * counter, incremented for every interim release. Use the {@link 1161 * #interim()} method in preference to this method. For compatibility, 1162 * this method returns the value of the <a href="#INTERIM">interim</a> 1163 * element, or zero if it is absent. 1164 * 1165 * @return The value of the interim element, or zero 1166 */ 1167 @Deprecated(since = "10") 1168 public int minor() { 1169 return interim(); 1170 } 1171 1172 /** 1173 * Returns the value of the security element of the version number, or 1174 * zero if it is absent. 1175 * 1176 * @deprecated As of Java SE 10, the third element of a version 1177 * number is not the security level but the update-release counter, 1178 * incremented for every update release. Use the {@link #update()} 1179 * method in preference to this method. For compatibility, this method 1180 * returns the value of the <a href="#UPDATE">update</a> element, or 1181 * zero if it is absent. 1182 * 1183 * @return The value of the update element, or zero 1184 */ 1185 @Deprecated(since = "10") 1186 public int security() { 1187 return update(); 1188 } 1189 1190 /** 1191 * Returns an unmodifiable {@link java.util.List List} of the integers 1192 * represented in the <a href="#verNum">version number</a>. 1193 * The {@code List} always contains at least one element corresponding to 1194 * the <a href="#FEATURE">feature version number</a>. 1195 * 1196 * @return An unmodifiable list of the integers 1197 * represented in the version number 1198 */ 1199 public List<Integer> version() { 1200 return version; 1201 } 1202 1203 /** 1204 * Returns the optional <a href="#pre">pre-release</a> information. 1205 * 1206 * @return The optional pre-release information as a String 1207 */ 1208 public Optional<String> pre() { 1209 return pre; 1210 } 1211 1212 /** 1213 * Returns the <a href="#build">build number</a>. 1214 * 1215 * @return The optional build number. 1216 */ 1217 public Optional<Integer> build() { 1218 return build; 1219 } 1220 1221 /** 1222 * Returns <a href="#opt">optional</a> additional identifying build 1223 * information. 1224 * 1225 * @return Additional build information as a String 1226 */ 1227 public Optional<String> optional() { 1228 return optional; 1229 } 1230 1231 /** 1232 * Compares this version to another. 1233 * 1234 * <p> Each of the components in the <a href="#verStr">version</a> is 1235 * compared in the following order of precedence: version numbers, 1236 * pre-release identifiers, build numbers, optional build information. 1237 * </p> 1238 * 1239 * <p> Comparison begins by examining the sequence of version numbers. 1240 * If one sequence is shorter than another, then the missing elements 1241 * of the shorter sequence are considered to be less than the 1242 * corresponding elements of the longer sequence. </p> 1243 * 1244 * <p> A version with a pre-release identifier is always considered to 1245 * be less than a version without one. Pre-release identifiers are 1246 * compared numerically when they consist only of digits, and 1247 * lexicographically otherwise. Numeric identifiers are considered to 1248 * be less than non-numeric identifiers. </p> 1249 * 1250 * <p> A version without a build number is always less than one with a 1251 * build number; otherwise build numbers are compared numerically. </p> 1252 * 1253 * <p> The optional build information is compared lexicographically. 1254 * During this comparison, a version with optional build information is 1255 * considered to be greater than a version without one. </p> 1256 * 1257 * @param obj 1258 * The object to be compared 1259 * 1260 * @return A negative integer, zero, or a positive integer if this 1261 * {@code Version} is less than, equal to, or greater than the 1262 * given {@code Version} 1263 * 1264 * @throws NullPointerException 1265 * If the given object is {@code null} 1266 */ 1267 @Override 1268 public int compareTo(Version obj) { 1269 return compare(obj, false); 1270 } 1271 1272 /** 1273 * Compares this version to another disregarding optional build 1274 * information. 1275 * 1276 * <p> Two versions are compared by examining the version string as 1277 * described in {@link #compareTo(Version)} with the exception that the 1278 * optional build information is always ignored. </p> 1279 * 1280 * <p> This method provides ordering which is consistent with 1281 * {@code equalsIgnoreOptional()}. </p> 1282 * 1283 * @param obj 1284 * The object to be compared 1285 * 1286 * @return A negative integer, zero, or a positive integer if this 1287 * {@code Version} is less than, equal to, or greater than the 1288 * given {@code Version} 1289 * 1290 * @throws NullPointerException 1291 * If the given object is {@code null} 1292 */ 1293 public int compareToIgnoreOptional(Version obj) { 1294 return compare(obj, true); 1295 } 1296 1297 private int compare(Version obj, boolean ignoreOpt) { 1298 if (obj == null) 1299 throw new NullPointerException(); 1300 1301 int ret = compareVersion(obj); 1302 if (ret != 0) 1303 return ret; 1304 1305 ret = comparePre(obj); 1306 if (ret != 0) 1307 return ret; 1308 1309 ret = compareBuild(obj); 1310 if (ret != 0) 1311 return ret; 1312 1313 if (!ignoreOpt) 1314 return compareOptional(obj); 1315 1316 return 0; 1317 } 1318 1319 private int compareVersion(Version obj) { 1320 int size = version.size(); 1321 int oSize = obj.version().size(); 1322 int min = Math.min(size, oSize); 1323 for (int i = 0; i < min; i++) { 1324 int val = version.get(i); 1325 int oVal = obj.version().get(i); 1326 if (val != oVal) 1327 return val - oVal; 1328 } 1329 return size - oSize; 1330 } 1331 1332 private int comparePre(Version obj) { 1333 Optional<String> oPre = obj.pre(); 1334 if (!pre.isPresent()) { 1335 if (oPre.isPresent()) 1336 return 1; 1337 } else { 1338 if (!oPre.isPresent()) 1339 return -1; 1340 String val = pre.get(); 1341 String oVal = oPre.get(); 1342 if (val.matches("\\d+")) { 1343 return (oVal.matches("\\d+") 1344 ? (new BigInteger(val)).compareTo(new BigInteger(oVal)) 1345 : -1); 1346 } else { 1347 return (oVal.matches("\\d+") 1348 ? 1 1349 : val.compareTo(oVal)); 1350 } 1351 } 1352 return 0; 1353 } 1354 1355 private int compareBuild(Version obj) { 1356 Optional<Integer> oBuild = obj.build(); 1357 if (oBuild.isPresent()) { 1358 return (build.isPresent() 1359 ? build.get().compareTo(oBuild.get()) 1360 : -1); 1361 } else if (build.isPresent()) { 1362 return 1; 1363 } 1364 return 0; 1365 } 1366 1367 private int compareOptional(Version obj) { 1368 Optional<String> oOpt = obj.optional(); 1369 if (!optional.isPresent()) { 1370 if (oOpt.isPresent()) 1371 return -1; 1372 } else { 1373 if (!oOpt.isPresent()) 1374 return 1; 1375 return optional.get().compareTo(oOpt.get()); 1376 } 1377 return 0; 1378 } 1379 1380 /** 1381 * Returns a string representation of this version. 1382 * 1383 * @return The version string 1384 */ 1385 @Override 1386 public String toString() { 1387 StringBuilder sb 1388 = new StringBuilder(version.stream() 1389 .map(Object::toString) 1390 .collect(Collectors.joining("."))); 1391 1392 pre.ifPresent(v -> sb.append("-").append(v)); 1393 1394 if (build.isPresent()) { 1395 sb.append("+").append(build.get()); 1396 if (optional.isPresent()) 1397 sb.append("-").append(optional.get()); 1398 } else { 1399 if (optional.isPresent()) { 1400 sb.append(pre.isPresent() ? "-" : "+-"); 1401 sb.append(optional.get()); 1402 } 1403 } 1404 1405 return sb.toString(); 1406 } 1407 1408 /** 1409 * Determines whether this {@code Version} is equal to another object. 1410 * 1411 * <p> Two {@code Version}s are equal if and only if they represent the 1412 * same version string. 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 * 1420 */ 1421 @Override 1422 public boolean equals(Object obj) { 1423 boolean ret = equalsIgnoreOptional(obj); 1424 if (!ret) 1425 return false; 1426 1427 Version that = (Version)obj; 1428 return (this.optional().equals(that.optional())); 1429 } 1430 1431 /** 1432 * Determines whether this {@code Version} is equal to another 1433 * disregarding optional build information. 1434 * 1435 * <p> Two {@code Version}s are equal if and only if they represent the 1436 * same version string disregarding the optional build information. 1437 * 1438 * @param obj 1439 * The object to which this {@code Version} is to be compared 1440 * 1441 * @return {@code true} if, and only if, the given object is a {@code 1442 * Version} that is identical to this {@code Version} 1443 * ignoring the optional build information 1444 * 1445 */ 1446 public boolean equalsIgnoreOptional(Object obj) { 1447 if (this == obj) 1448 return true; 1449 if (!(obj instanceof Version)) 1450 return false; 1451 1452 Version that = (Version)obj; 1453 return (this.version().equals(that.version()) 1454 && this.pre().equals(that.pre()) 1455 && this.build().equals(that.build())); 1456 } 1457 1458 /** 1459 * Returns the hash code of this version. 1460 * 1461 * @return The hashcode of this version 1462 */ 1463 @Override 1464 public int hashCode() { 1465 int h = 1; 1466 int p = 17; 1467 1468 h = p * h + version.hashCode(); 1469 h = p * h + pre.hashCode(); 1470 h = p * h + build.hashCode(); 1471 h = p * h + optional.hashCode(); 1472 1473 return h; 1474 } 1475 } 1476 1477 private static class VersionPattern { 1478 // $VNUM(-$PRE)?(\+($BUILD)?(\-$OPT)?)? 1479 // RE limits the format of version strings 1480 // ([1-9][0-9]*(?:(?:\.0)*\.[1-9][0-9]*)*)(?:-([a-zA-Z0-9]+))?(?:(\+)(0|[1-9][0-9]*)?)?(?:-([-a-zA-Z0-9.]+))? 1481 1482 private static final String VNUM 1483 = "(?<VNUM>[1-9][0-9]*(?:(?:\\.0)*\\.[1-9][0-9]*)*)"; 1484 private static final String PRE = "(?:-(?<PRE>[a-zA-Z0-9]+))?"; 1485 private static final String BUILD 1486 = "(?:(?<PLUS>\\+)(?<BUILD>0|[1-9][0-9]*)?)?"; 1487 private static final String OPT = "(?:-(?<OPT>[-a-zA-Z0-9.]+))?"; 1488 private static final String VSTR_FORMAT = VNUM + PRE + BUILD + OPT; 1489 1490 static final Pattern VSTR_PATTERN = Pattern.compile(VSTR_FORMAT); 1491 1492 static final String VNUM_GROUP = "VNUM"; 1493 static final String PRE_GROUP = "PRE"; 1494 static final String PLUS_GROUP = "PLUS"; 1495 static final String BUILD_GROUP = "BUILD"; 1496 static final String OPT_GROUP = "OPT"; 1497 } 1498 }