1 /* 2 * Copyright (c) 2015, 2016, 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 jdk; 27 28 import java.math.BigInteger; 29 import java.security.AccessController; 30 import java.security.PrivilegedAction; 31 import java.util.regex.Matcher; 32 import java.util.regex.Pattern; 33 import java.util.stream.Collectors; 34 import java.util.Arrays; 35 import java.util.Collections; 36 import java.util.List; 37 import java.util.Optional; 38 39 /** 40 * A representation of the JDK version-string which contains a version 41 * number optionally followed by pre-release and build information. 42 * 43 * <h2><a name="verNum">Version numbers</a></h2> 44 * 45 * A <em>version number</em>, {@code $VNUM}, is a non-empty sequence of 46 * non-negative integer numerals, without leading or trailing zeroes, 47 * separated by period characters (U+002E); i.e., it matches the regular 48 * expression {@code ^[1-9][0-9]*(((\.0)*\.[1-9][0-9]*)*)*$}. The sequence may 49 * be of arbitrary length but the first three elements are assigned specific 50 * meanings, as follows: 51 * 52 * <blockquote><pre> 53 * $MAJOR.$MINOR.$SECURITY 54 * </pre></blockquote> 55 * 56 * <ul> 57 * 58 * <li><p> <a name="major">{@code $MAJOR}</a> --- The major version number, 59 * incremented for a major release that contains significant new features as 60 * specified in a new edition of the Java SE Platform Specification, 61 * <em>e.g.</em>, <a href="https://jcp.org/en/jsr/detail?id=337">JSR 337</a> 62 * for Java SE 8. Features may be removed in a major release, given 63 * advance notice at least one major release ahead of time, and incompatible 64 * changes may be made when justified. The {@code $MAJOR} version number of 65 * JDK 8 was {@code 8}; the {@code $MAJOR} version number of JDK 9 66 * is {@code 9}. </p></li> 67 * 68 * <li><p> <a name="minor">{@code $MINOR}</a> --- The minor version number, 69 * incremented for a minor update release that may contain compatible bug 70 * fixes, revisions to standard APIs mandated by a <a 71 * href="https://jcp.org/en/procedures/jcp2#5.3">Maintenance Release</a> of 72 * the relevant Platform Specification, and implementation features outside 73 * the scope of that Specification such as new JDK-specific APIs, additional 74 * service providers, new garbage collectors, and ports to new hardware 75 * architectures. {@code $MINOR} is reset to zero when {@code $MAJOR} is 76 * incremented. </p></li> 77 * 78 * <li><p> <a name="security">{@code $SECURITY}</a> --- The security level, 79 * incremented for a security-update release that contains critical fixes 80 * including those necessary to improve security. {@code $SECURITY} is reset 81 * to zero <strong>only</strong> when {@code $MAJOR} is incremented. A higher 82 * value of {@code $SECURITY} for a given {@code $MAJOR} value, therefore, 83 * always indicates a more secure release, regardless of the value of {@code 84 * $MINOR}. </p></li> 85 * 86 * </ul> 87 * 88 * <p> The fourth and later elements of a version number are free for use by 89 * downstream consumers of the JDK code base. Such a consumer may, 90 * <em>e.g.</em>, use the fourth element to identify patch releases which 91 * contain a small number of critical non-security fixes in addition to the 92 * security fixes in the corresponding security release. </p> 93 * 94 * <p> The version number does not include trailing zero elements; 95 * <em>i.e.</em>, {@code $SECURITY} is omitted if it has the value zero, and 96 * {@code $MINOR} is omitted if both {@code $MINOR} and {@code $SECURITY} have 97 * the value zero. </p> 98 * 99 * <p> The sequence of numerals in a version number is compared to another 100 * such sequence in numerical, pointwise fashion; <em>e.g.</em>, {@code 9.9.1} 101 * is less than {@code 9.10.0}. If one sequence is shorter than another then 102 * the missing elements of the shorter sequence are considered to be zero; 103 * <em>e.g.</em>, {@code 9.1.2} is equal to {@code 9.1.2.0} but less than 104 * {@code 9.1.2.1}. </p> 105 * 106 * <h2><a name="verStr">Version strings</a></h2> 107 * 108 * <p> A <em>version string</em> {@code $VSTR} consists of a version number 109 * {@code $VNUM}, as described above, optionally followed by pre-release and 110 * build information, in the format </p> 111 * 112 * <blockquote><pre> 113 * $VNUM(-$PRE)?(\+($BUILD)?(-$OPT)?)? 114 * </pre></blockquote> 115 * 116 * <p> where: </p> 117 * 118 * <ul> 119 * 120 * <li><p> <a name="pre">{@code $PRE}</a>, matching {@code ([a-zA-Z0-9]+)} --- 121 * A pre-release identifier. Typically {@code ea}, for an early-access 122 * release that's under active development and potentially unstable, or {@code 123 * internal}, for an internal developer build. 124 * 125 * <li><p> <a name="build">{@code $BUILD}</a>, matching {@code 126 * (0|[1-9][0-9]*)} --- The build number, incremented for each promoted build. 127 * {@code $BUILD} is reset to {@code 1} when any portion of {@code $VNUM} is 128 * incremented. </p> 129 * 130 * <li><p> <a name="opt">{@code $OPT}</a>, matching {@code ([-a-zA-Z0-9\.]+)} 131 * --- Additional build information, if desired. In the case of an {@code 132 * internal} build this will often contain the date and time of the 133 * build. </p> 134 * 135 * </ul> 136 * 137 * <p> When comparing two version strings the value of {@code $OPT}, if 138 * present, may or may not be significant depending on the chosen comparison 139 * method. The comparison methods {@link #compareTo(Version) compareTo()} and 140 * {@link #compareToIgnoreOpt(Version) compareToIgnoreOpt{}} should be used 141 * consistently with the corresponding methods {@link #equals(Object) equals()} 142 * and {@link #equalsIgnoreOpt(Object) equalsIgnoreOpt()}. </p> 143 * 144 * <p> A <em>short version string</em> ({@code $SVSTR}), often useful in less 145 * formal contexts, is simply {@code $VNUM} optionally ended with {@code 146 * -$PRE}. </p> 147 * 148 * @since 9 149 */ 150 public final class Version 151 implements Comparable<Version> 152 { 153 private final List<Integer> version; 154 private final Optional<String> pre; 155 private final Optional<Integer> build; 156 private final Optional<String> optional; 157 158 private static Version current; 159 160 // $VNUM(-$PRE)?(\+($BUILD)?(\-$OPT)?)? 161 // RE limits the format of version strings 162 // ([1-9][0-9]*(?:(?:\.0)*\.[1-9][0-9]*)*)(?:-([a-zA-Z0-9]+))?(?:(\+)(0|[1-9][0-9]*)?)?(?:-([-a-zA-Z0-9.]+))? 163 164 private static final String VNUM 165 = "(?<VNUM>[1-9][0-9]*(?:(?:\\.0)*\\.[1-9][0-9]*)*)"; 166 private static final String VNUM_GROUP = "VNUM"; 167 168 private static final String PRE = "(?:-(?<PRE>[a-zA-Z0-9]+))?"; 169 private static final String PRE_GROUP = "PRE"; 170 171 private static final String BUILD 172 = "(?:(?<PLUS>\\+)(?<BUILD>0|[1-9][0-9]*)?)?"; 173 private static final String PLUS_GROUP = "PLUS"; 174 private static final String BUILD_GROUP = "BUILD"; 175 176 private static final String OPT = "(?:-(?<OPT>[-a-zA-Z0-9.]+))?"; 177 private static final String OPT_GROUP = "OPT"; 178 179 private static final String VSTR_FORMAT 180 = "^" + VNUM + PRE + BUILD + OPT + "$"; 181 private static final Pattern VSTR_PATTERN = Pattern.compile(VSTR_FORMAT); 182 183 /** 184 * Constructs a valid JDK <a href="verStr">version string</a> containing a 185 * <a href="#verNum">version number</a> followed by pre-release and build 186 * information. 187 * 188 * @param s 189 * A string to be interpreted as a version 190 * 191 * @throws IllegalArgumentException 192 * If the given string cannot be interpreted a valid version 193 * 194 * @throws NullPointerException 195 * If {@code s} is {@code null} 196 * 197 * @throws NumberFormatException 198 * If an element of the version number or the build number cannot 199 * be represented as an {@link Integer} 200 */ 201 private Version(String s) { 202 if (s == null) 203 throw new NullPointerException(); 204 205 Matcher m = VSTR_PATTERN.matcher(s); 206 if (!m.matches()) 207 throw new IllegalArgumentException("Invalid version string: '" 208 + s + "'"); 209 210 // $VNUM is a dot-separated list of integers of arbitrary length 211 version 212 = Collections.unmodifiableList( 213 Arrays.stream(m.group(VNUM_GROUP).split("\\.")) 214 .map(Integer::parseInt) 215 .collect(Collectors.toList())); 216 217 pre = Optional.ofNullable(m.group(PRE_GROUP)); 218 219 String b = m.group(BUILD_GROUP); 220 // $BUILD is an integer 221 build = (b == null) 222 ? Optional.<Integer>empty() 223 : Optional.ofNullable(Integer.parseInt(b)); 224 225 optional = Optional.ofNullable(m.group(OPT_GROUP)); 226 227 // empty '+' 228 if ((m.group(PLUS_GROUP) != null) && !build.isPresent()) { 229 if (optional.isPresent()) { 230 if (pre.isPresent()) 231 throw new IllegalArgumentException("'+' found with" 232 + " pre-release and optional components:'" + s + "'"); 233 } else { 234 throw new IllegalArgumentException("'+' found with neither" 235 + " build or optional components: '" + s + "'"); 236 } 237 } 238 } 239 240 /** 241 * Parses the given string as a valid JDK <a 242 * href="#verStr">version string</a> containing a <a 243 * href="#verNum">version number</a> followed by pre-release and 244 * build information. 245 * 246 * @param s 247 * A string to interpret as a version 248 * 249 * @throws IllegalArgumentException 250 * If the given string cannot be interpreted a valid version 251 * 252 * @throws NullPointerException 253 * If the given string is {@code null} 254 * 255 * @throws NumberFormatException 256 * If an element of the version number or the build number cannot 257 * be represented as an {@link Integer} 258 * 259 * @return This version 260 */ 261 public static Version parse(String s) { 262 return new Version(s); 263 } 264 265 /** 266 * Returns {@code System.getProperty("java.version")} as a Version. 267 * 268 * @throws SecurityException 269 * If a security manager exists and its {@link 270 * SecurityManager#checkPropertyAccess(String) 271 * checkPropertyAccess} method does not allow access to the 272 * system property "java.version" 273 * 274 * @return {@code System.getProperty("java.version")} as a Version 275 */ 276 public static Version current() { 277 if (current == null) { 278 current = parse(AccessController.doPrivileged( 279 new PrivilegedAction<>() { 280 public String run() { 281 return System.getProperty("java.version"); 282 } 283 })); 284 } 285 return current; 286 } 287 288 /** 289 * Returns the <a href="#major">major</a> version number. 290 * 291 * @return The major version number 292 */ 293 public int major() { 294 return version.get(0); 295 } 296 297 /** 298 * Returns the <a href="#minor">minor</a> version number or zero if it was 299 * not set. 300 * 301 * @return The minor version number or zero if it was not set 302 */ 303 public int minor() { 304 return (version.size() > 1 ? version.get(1) : 0); 305 } 306 307 /** 308 * Returns the <a href="#security">security</a> version number or zero if 309 * it was not set. 310 * 311 * @return The security version number or zero if it was not set 312 */ 313 public int security() { 314 return (version.size() > 2 ? version.get(2) : 0); 315 } 316 317 /** 318 * Returns an unmodifiable {@link java.util.List List} of the 319 * integer numerals contained in the <a href="#verNum">version 320 * number</a>. The {@code List} always contains at least one 321 * element corresponding to the <a href="#major">major version 322 * number</a>. 323 * 324 * @return An unmodifiable list of the integer numerals 325 * contained in the version number 326 */ 327 public List<Integer> version() { 328 return version; 329 } 330 331 /** 332 * Returns the optional <a href="#pre">pre-release</a> information. 333 * 334 * @return The optional pre-release information as a String 335 */ 336 public Optional<String> pre() { 337 return pre; 338 } 339 340 /** 341 * Returns the <a href="#build">build number</a>. 342 * 343 * @return The optional build number. 344 */ 345 public Optional<Integer> build() { 346 return build; 347 } 348 349 /** 350 * Returns <a href="#opt">optional</a> additional identifying build 351 * information. 352 * 353 * @return Additional build information as a String 354 */ 355 public Optional<String> optional() { 356 return optional; 357 } 358 359 /** 360 * Compares this version to another. 361 * 362 * <p> Each of the components in the <a href="#verStr">version</a> is 363 * compared in the follow order of precedence: version numbers, 364 * pre-release identifiers, build numbers, optional build information. </p> 365 * 366 * <p> Comparison begins by examining the sequence of version numbers. If 367 * one sequence is shorter than another, then the missing elements of the 368 * shorter sequence are considered to be zero. </p> 369 * 370 * <p> A version with a pre-release identifier is always considered to be 371 * less than a version without one. Pre-release identifiers are compared 372 * numerically when they consist only of digits, and lexicographically 373 * otherwise. Numeric identifiers are considered to be less than 374 * non-numeric identifiers. </p> 375 * 376 * <p> A version without a build number is always less than one with a 377 * build number; otherwise build numbers are compared numerically. </p> 378 * 379 * <p> The optional build information is compared lexicographically. 380 * During this comparison, a version with optional build information is 381 * considered to be greater than a version without one. </p> 382 * 383 * <p> A version is not comparable to any other type of object. 384 * 385 * @param ob 386 * The object to be compared 387 * 388 * @return A negative integer, zero, or a positive integer if this 389 * {@code Version} is less than, equal to, or greater than the 390 * given {@code Version} 391 * 392 * @throws NullPointerException 393 * If the given object is {@code null} 394 */ 395 @Override 396 public int compareTo(Version ob) { 397 return compare(ob, false); 398 } 399 400 /** 401 * Compares this version to another disregarding optional build 402 * information. 403 * 404 * <p> Two versions are compared by examining the version string as 405 * described in {@link #compareTo(Version)} with the exception that the 406 * optional build information is always ignored. </p> 407 * 408 * <p> A version is not comparable to any other type of object. 409 * 410 * @param ob 411 * The object to be compared 412 * 413 * @return A negative integer, zero, or a positive integer if this 414 * {@code Version} is less than, equal to, or greater than the 415 * given {@code Version} 416 * 417 * @throws NullPointerException 418 * If the given object is {@code null} 419 */ 420 public int compareToIgnoreOpt(Version ob) { 421 return compare(ob, true); 422 } 423 424 private int compare(Version ob, boolean ignoreOpt) { 425 if (ob == null) 426 throw new NullPointerException("Invalid argument"); 427 428 int ret = compareVersion(ob); 429 if (ret != 0) 430 return ret; 431 432 ret = comparePre(ob); 433 if (ret != 0) 434 return ret; 435 436 ret = compareBuild(ob); 437 if (ret != 0) 438 return ret; 439 440 if (!ignoreOpt) 441 return compareOpt(ob); 442 443 return 0; 444 } 445 446 private int compareVersion(Version ob) { 447 int size = version.size(); 448 int oSize = ob.version().size(); 449 int min = Math.min(size, oSize); 450 for (int i = 0; i < min; i++) { 451 Integer val = version.get(i); 452 Integer oVal = ob.version().get(i); 453 if (val != oVal) 454 return val - oVal; 455 } 456 if (size != oSize) 457 return size - oSize; 458 return 0; 459 } 460 461 private int comparePre(Version ob) { 462 Optional<String> oPre = ob.pre(); 463 if (!pre.isPresent()) { 464 if (oPre.isPresent()) 465 return 1; 466 } else { 467 if (!oPre.isPresent()) 468 return -1; 469 String val = pre.get(); 470 String oVal = oPre.get(); 471 if (val.matches("\\d+")) { 472 return (oVal.matches("\\d+") 473 ? (new BigInteger(val)).compareTo(new BigInteger(oVal)) 474 : -1); 475 } else { 476 return (oVal.matches("\\d+") 477 ? 1 478 : val.compareTo(oVal)); 479 } 480 } 481 return 0; 482 } 483 484 private int compareBuild(Version ob) { 485 Optional<Integer> oBuild = ob.build(); 486 if (oBuild.isPresent()) { 487 return (build.isPresent() 488 ? build.get().compareTo(oBuild.get()) 489 : 1); 490 } else if (build.isPresent()) { 491 return -1; 492 } 493 return 0; 494 } 495 496 private int compareOpt(Version ob) { 497 Optional<String> oOpt = ob.optional(); 498 if (!optional.isPresent()) { 499 if (oOpt.isPresent()) 500 return -1; 501 } else { 502 if (!oOpt.isPresent()) 503 return 1; 504 return optional.get().compareTo(oOpt.get()); 505 } 506 return 0; 507 } 508 509 /** 510 * Returns a string representation of this version. 511 * 512 * @return The version string 513 */ 514 @Override 515 public String toString() { 516 StringBuilder sb 517 = new StringBuilder(version.stream() 518 .map(Object::toString) 519 .collect(Collectors.joining("."))); 520 pre.ifPresent(v -> sb.append("-").append(v)); 521 522 if (build.isPresent()) { 523 sb.append("+").append(build.get()); 524 if (optional.isPresent()) 525 sb.append("-").append(optional.get()); 526 } else { 527 if (optional.isPresent()) { 528 sb.append(pre.isPresent() ? "-" : "+-"); 529 sb.append(optional.get()); 530 } 531 } 532 533 return sb.toString(); 534 } 535 536 /** 537 * Determines whether this {@code Version} is equal to another object. 538 * 539 * <p> Two {@code Version}s are equal if and only if they represent the 540 * same version string. 541 * 542 * <p> This method satisfies the general contract of the {@link 543 * Object#equals(Object) Object.equals} method. </p> 544 * 545 * @param ob 546 * The object to which this {@code Version} is to be compared 547 * 548 * @return {@code true} if, and only if, the given object is a {@code 549 * Version} that is identical to this {@code Version} 550 * 551 */ 552 @Override 553 public boolean equals(Object ob) { 554 boolean ret = equalsIgnoreOpt(ob); 555 if (!ret) 556 return false; 557 558 Version that = (Version)ob; 559 return (this.optional().equals(that.optional())); 560 } 561 562 /** 563 * Determines whether this {@code Version} is equal to another 564 * disregarding optional build information. 565 * 566 * <p> Two {@code Version}s are equal if and only if they represent the 567 * same version string disregarding the optional build information. 568 * 569 * @param ob 570 * The object to which this {@code Version} is to be compared 571 * 572 * @return {@code true} if, and only if, the given object is a {@code 573 * Version} that is identical to this {@code Version} 574 * ignoring the optinal build information 575 * 576 */ 577 public boolean equalsIgnoreOpt(Object ob) { 578 if (this == ob) 579 return true; 580 if (!(ob instanceof Version)) 581 return false; 582 583 Version that = (Version)ob; 584 return (this.version().equals(that.version()) 585 && this.pre().equals(that.pre()) 586 && this.build().equals(that.build())); 587 } 588 589 /** 590 * Returns the hash code of this version. 591 * 592 * <p> This method satisfies the general contract of the {@link 593 * Object#hashCode Object.hashCode} method. 594 * 595 * @return The hashcode of this version 596 */ 597 @Override 598 public int hashCode() { 599 int h = 1; 600 int p = 17; 601 602 h = p * h + version.hashCode(); 603 h = p * h + pre.hashCode(); 604 h = p * h + build.hashCode(); 605 h = p * h + optional.hashCode(); 606 607 return h; 608 } 609 }