001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.eclipse.aether.util.version; 020 021import java.util.Collections; 022import java.util.Map; 023import java.util.WeakHashMap; 024import java.util.concurrent.atomic.AtomicLong; 025 026import org.eclipse.aether.ConfigurationProperties; 027import org.eclipse.aether.version.InvalidVersionSpecificationException; 028 029/** 030 * A version scheme using a generic version syntax and common sense sorting. 031 * <p> 032 * This scheme accepts versions of any form, interpreting a version as a sequence of numeric and alphabetic segments. 033 * The characters '-', '_', and '.' as well as the mere transitions from digit to letter and vice versa delimit the 034 * version segments. Delimiters are treated as equivalent. 035 * </p> 036 * <p> 037 * Numeric segments are compared mathematically, alphabetic segments are compared lexicographically and 038 * case-insensitively. However, the following qualifier strings are recognized and treated specially: "alpha" = "a" < 039 * "beta" = "b" < "milestone" = "m" < "cr" = "rc" < "snapshot" < "final" = "ga" < "sp". All of those 040 * well-known qualifiers are considered smaller/older than other strings. An empty segment/string is equivalent to 0. 041 * </p> 042 * <p> 043 * In addition to the above mentioned qualifiers, the tokens "min" and "max" may be used as final version segment to 044 * denote the smallest/greatest version having a given prefix. For example, "1.2.min" denotes the smallest version in 045 * the 1.2 line, "1.2.max" denotes the greatest version in the 1.2 line. A version range of the form "[M.N.*]" is short 046 * for "[M.N.min, M.N.max]". 047 * </p> 048 * <p> 049 * Numbers and strings are considered incomparable against each other. Where version segments of different kind would 050 * collide, comparison will instead assume that the previous segments are padded with trailing 0 or "ga" segments, 051 * respectively, until the kind mismatch is resolved, e.g. "1-alpha" = "1.0.0-alpha" < "1.0.1-ga" = "1.0.1". 052 * </p> 053 */ 054public class GenericVersionScheme extends VersionSchemeSupport { 055 056 // Using WeakHashMap wrapped in synchronizedMap for thread safety and memory-sensitive caching 057 private final Map<String, GenericVersion> versionCache = Collections.synchronizedMap(new WeakHashMap<>()); 058 059 // Cache statistics 060 private final AtomicLong cacheHits = new AtomicLong(0); 061 private final AtomicLong cacheMisses = new AtomicLong(0); 062 private final AtomicLong totalRequests = new AtomicLong(0); 063 064 // Static statistics across all instances 065 private static final AtomicLong GLOBAL_CACHE_HITS = new AtomicLong(0); 066 private static final AtomicLong GLOBAL_CACHE_MISSES = new AtomicLong(0); 067 private static final AtomicLong GLOBAL_TOTAL_REQUESTS = new AtomicLong(0); 068 private static final AtomicLong INSTANCE_COUNT = new AtomicLong(0); 069 070 static { 071 // Register shutdown hook to print statistics if enabled 072 if (isStatisticsEnabled()) { 073 Runtime.getRuntime().addShutdownHook(new Thread(GenericVersionScheme::printGlobalStatistics)); 074 } 075 } 076 077 public GenericVersionScheme() { 078 INSTANCE_COUNT.incrementAndGet(); 079 } 080 081 /** 082 * Checks if version scheme cache statistics should be printed. 083 * This checks both the system property and the configuration property. 084 */ 085 private static boolean isStatisticsEnabled() { 086 // Check system property first (for backwards compatibility and ease of use) 087 String sysProp = System.getProperty(ConfigurationProperties.VERSION_SCHEME_CACHE_DEBUG); 088 if (sysProp != null) { 089 return Boolean.parseBoolean(sysProp); 090 } 091 092 // Default to false if not configured 093 return ConfigurationProperties.DEFAULT_VERSION_SCHEME_CACHE_DEBUG; 094 } 095 096 @Override 097 public GenericVersion parseVersion(final String version) throws InvalidVersionSpecificationException { 098 totalRequests.incrementAndGet(); 099 GLOBAL_TOTAL_REQUESTS.incrementAndGet(); 100 101 GenericVersion existing = versionCache.get(version); 102 if (existing != null) { 103 cacheHits.incrementAndGet(); 104 GLOBAL_CACHE_HITS.incrementAndGet(); 105 return existing; 106 } else { 107 cacheMisses.incrementAndGet(); 108 GLOBAL_CACHE_MISSES.incrementAndGet(); 109 return versionCache.computeIfAbsent(version, GenericVersion::new); 110 } 111 } 112 113 /** 114 * Get cache statistics for this instance. 115 */ 116 public String getCacheStatistics() { 117 long hits = cacheHits.get(); 118 long misses = cacheMisses.get(); 119 long total = totalRequests.get(); 120 double hitRate = total > 0 ? (double) hits / total * 100.0 : 0.0; 121 122 return String.format( 123 "GenericVersionScheme Cache Stats: hits=%d, misses=%d, total=%d, hit-rate=%.2f%%, cache-size=%d", 124 hits, misses, total, hitRate, versionCache.size()); 125 } 126 127 /** 128 * Print global statistics across all instances. 129 */ 130 private static void printGlobalStatistics() { 131 long hits = GLOBAL_CACHE_HITS.get(); 132 long misses = GLOBAL_CACHE_MISSES.get(); 133 long total = GLOBAL_TOTAL_REQUESTS.get(); 134 long instances = INSTANCE_COUNT.get(); 135 double hitRate = total > 0 ? (double) hits / total * 100.0 : 0.0; 136 137 System.err.println("=== GenericVersionScheme Global Cache Statistics (WeakHashMap) ==="); 138 System.err.println(String.format("Total instances created: %d", instances)); 139 System.err.println(String.format("Total requests: %d", total)); 140 System.err.println(String.format("Cache hits: %d", hits)); 141 System.err.println(String.format("Cache misses: %d", misses)); 142 System.err.println(String.format("Hit rate: %.2f%%", hitRate)); 143 System.err.println( 144 String.format("Average requests per instance: %.2f", instances > 0 ? (double) total / instances : 0.0)); 145 System.err.println("=== End Cache Statistics ==="); 146 } 147 148 /** 149 * A handy main method that behaves similarly like maven-artifact ComparableVersion is, to make possible test 150 * and possibly compare differences between the two. 151 * <p> 152 * To check how "1.2.7" compares to "1.2-SNAPSHOT", for example, you can issue 153 * <pre>jbang --main=org.eclipse.aether.util.version.GenericVersionScheme org.apache.maven.resolver:maven-resolver-util:1.9.18 "1.2.7" "1.2-SNAPSHOT"</pre> 154 * command to command line, output is very similar to that of ComparableVersion on purpose. 155 */ 156 public static void main(String... args) { 157 System.out.println( 158 "Display parameters as parsed by Maven Resolver 'generic' scheme (in canonical form and as a list of tokens)" 159 + " and comparison result:"); 160 if (args.length == 0) { 161 return; 162 } 163 164 GenericVersionScheme scheme = new GenericVersionScheme(); 165 GenericVersion prev = null; 166 int i = 1; 167 for (String version : args) { 168 try { 169 GenericVersion c = scheme.parseVersion(version); 170 171 if (prev != null) { 172 int compare = prev.compareTo(c); 173 System.out.println( 174 " " + prev + ' ' + ((compare == 0) ? "==" : ((compare < 0) ? "<" : ">")) + ' ' + version); 175 } 176 177 System.out.println((i++) + ". " + version + " -> " + c.asString() + "; tokens: " + c.asItems()); 178 179 prev = c; 180 } catch (InvalidVersionSpecificationException e) { 181 System.err.println("Invalid version: " + version + " - " + e.getMessage()); 182 } 183 } 184 } 185}