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