View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.util.version;
20  
21  import java.nio.charset.StandardCharsets;
22  import java.util.Collections;
23  import java.util.Map;
24  import java.util.WeakHashMap;
25  import java.util.concurrent.atomic.AtomicLong;
26  
27  import org.eclipse.aether.ConfigurationProperties;
28  import org.eclipse.aether.version.InvalidVersionSpecificationException;
29  
30  /**
31   * A version scheme using a generic version syntax and common sense sorting.
32   * <p>
33   * This scheme accepts versions of any form, interpreting a version as a sequence of numeric and alphabetic segments.
34   * The characters '-', '_', and '.' as well as the mere transitions from digit to letter and vice versa delimit the
35   * version segments. Delimiters are treated as equivalent.
36   * </p>
37   * <p>
38   * Numeric segments are compared mathematically, alphabetic segments are compared lexicographically and
39   * case-insensitively. However, the following qualifier strings are recognized and treated specially: "alpha" = "a" &lt;
40   * "beta" = "b" &lt; "milestone" = "m" &lt; "cr" = "rc" &lt; "snapshot" &lt; "final" = "ga" &lt; "sp". All of those
41   * well-known qualifiers are considered smaller/older than other strings. An empty segment/string is equivalent to 0.
42   * </p>
43   * <p>
44   * In addition to the above mentioned qualifiers, the tokens "min" and "max" may be used as final version segment to
45   * denote the smallest/greatest version having a given prefix. For example, "1.2.min" denotes the smallest version in
46   * 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
47   * for "[M.N.min, M.N.max]".
48   * </p>
49   * <p>
50   * Numbers and strings are considered incomparable against each other. Where version segments of different kind would
51   * collide, comparison will instead assume that the previous segments are padded with trailing 0 or "ga" segments,
52   * respectively, until the kind mismatch is resolved, e.g. "1-alpha" = "1.0.0-alpha" &lt; "1.0.1-ga" = "1.0.1".
53   * </p>
54   */
55  public class GenericVersionScheme extends VersionSchemeSupport {
56  
57      // Using WeakHashMap wrapped in synchronizedMap for thread safety and memory-sensitive caching
58      private final Map<String, GenericVersion> versionCache = Collections.synchronizedMap(new WeakHashMap<>());
59  
60      // Cache statistics
61      private final AtomicLong cacheHits = new AtomicLong(0);
62      private final AtomicLong cacheMisses = new AtomicLong(0);
63      private final AtomicLong totalRequests = new AtomicLong(0);
64  
65      // Static statistics across all instances
66      private static final AtomicLong GLOBAL_CACHE_HITS = new AtomicLong(0);
67      private static final AtomicLong GLOBAL_CACHE_MISSES = new AtomicLong(0);
68      private static final AtomicLong GLOBAL_TOTAL_REQUESTS = new AtomicLong(0);
69      private static final AtomicLong INSTANCE_COUNT = new AtomicLong(0);
70  
71      static {
72          // Register shutdown hook to print statistics if enabled
73          if (isStatisticsEnabled()) {
74              Runtime.getRuntime().addShutdownHook(new Thread(GenericVersionScheme::printGlobalStatistics));
75          }
76      }
77  
78      public GenericVersionScheme() {
79          INSTANCE_COUNT.incrementAndGet();
80      }
81  
82      /**
83       * Checks if version scheme cache statistics should be printed.
84       * This checks both the system property and the configuration property.
85       */
86      private static boolean isStatisticsEnabled() {
87          // Check system property first (for backwards compatibility and ease of use)
88          String sysProp = System.getProperty(ConfigurationProperties.VERSION_SCHEME_CACHE_DEBUG);
89          if (sysProp != null) {
90              return Boolean.parseBoolean(sysProp);
91          }
92  
93          // Default to false if not configured
94          return ConfigurationProperties.DEFAULT_VERSION_SCHEME_CACHE_DEBUG;
95      }
96  
97      @Override
98      public GenericVersion parseVersion(final String version) throws InvalidVersionSpecificationException {
99          totalRequests.incrementAndGet();
100         GLOBAL_TOTAL_REQUESTS.incrementAndGet();
101 
102         GenericVersion existing = versionCache.get(version);
103         if (existing != null) {
104             cacheHits.incrementAndGet();
105             GLOBAL_CACHE_HITS.incrementAndGet();
106             return existing;
107         } else {
108             cacheMisses.incrementAndGet();
109             GLOBAL_CACHE_MISSES.incrementAndGet();
110             return versionCache.computeIfAbsent(version, GenericVersion::new);
111         }
112     }
113 
114     /**
115      * Get cache statistics for this instance.
116      */
117     public String getCacheStatistics() {
118         long hits = cacheHits.get();
119         long misses = cacheMisses.get();
120         long total = totalRequests.get();
121         double hitRate = total > 0 ? (double) hits / total * 100.0 : 0.0;
122 
123         return String.format(
124                 "GenericVersionScheme Cache Stats: hits=%d, misses=%d, total=%d, hit-rate=%.2f%%, cache-size=%d",
125                 hits, misses, total, hitRate, versionCache.size());
126     }
127 
128     /**
129      * Print global statistics across all instances.
130      */
131     private static void printGlobalStatistics() {
132         long hits = GLOBAL_CACHE_HITS.get();
133         long misses = GLOBAL_CACHE_MISSES.get();
134         long total = GLOBAL_TOTAL_REQUESTS.get();
135         long instances = INSTANCE_COUNT.get();
136         double hitRate = total > 0 ? (double) hits / total * 100.0 : 0.0;
137 
138         System.err.println("=== GenericVersionScheme Global Cache Statistics (WeakHashMap) ===");
139         System.err.println(String.format("Total instances created: %d", instances));
140         System.err.println(String.format("Total requests: %d", total));
141         System.err.println(String.format("Cache hits: %d", hits));
142         System.err.println(String.format("Cache misses: %d", misses));
143         System.err.println(String.format("Hit rate: %.2f%%", hitRate));
144         System.err.println(
145                 String.format("Average requests per instance: %.2f", instances > 0 ? (double) total / instances : 0.0));
146         System.err.println("=== End Cache Statistics ===");
147     }
148 
149     /**
150      * A handy main method that behaves similarly like maven-artifact ComparableVersion is, to make possible test
151      * and possibly compare differences between the two.
152      * <p>
153      * To check how "1.2.7" compares to "1.2-SNAPSHOT", for example, you can issue
154      * <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>
155      * command to command line, output is very similar to that of ComparableVersion on purpose.
156      */
157     public static void main(String... args) {
158         System.out.println(
159                 "Display parameters as parsed by Maven Resolver 'generic' scheme (in canonical form and as a list of tokens)"
160                         + " and comparison result:");
161         if (args.length == 0) {
162             return;
163         }
164 
165         GenericVersionScheme scheme = new GenericVersionScheme();
166         GenericVersion prev = null;
167         int i = 1;
168         for (String version : args) {
169             if (!StandardCharsets.US_ASCII.newEncoder().canEncode(version)) {
170                 System.out.println("WW Use of non-ASCII characters for version strings is not recommended.");
171             }
172             try {
173                 GenericVersion c = scheme.parseVersion(version);
174 
175                 if (prev != null) {
176                     int compare = prev.compareTo(c);
177                     System.out.println(
178                             "   " + prev + ' ' + ((compare == 0) ? "==" : ((compare < 0) ? "<" : ">")) + ' ' + version);
179                 }
180 
181                 System.out.println((i++) + ". " + version + " -> " + c.asString() + "; tokens: " + c.asItems());
182 
183                 prev = c;
184             } catch (InvalidVersionSpecificationException e) {
185                 System.err.println("Invalid version: " + version + " - " + e.getMessage());
186             }
187         }
188     }
189 }