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          if (isStatisticsEnabled()) {
73              Runtime.getRuntime().addShutdownHook(new Thread(GenericVersionScheme::printGlobalStatistics));
74          }
75      }
76  
77      public GenericVersionScheme() {
78          INSTANCE_COUNT.incrementAndGet();
79      }
80  
81      /**
82       * Checks if version scheme cache statistics should be printed.
83       * This checks both the system property and the configuration property.
84       */
85      private static boolean isStatisticsEnabled() {
86          // Check system property first (for backwards compatibility and ease of use)
87          String sysProp = System.getProperty(ConfigurationProperties.VERSION_SCHEME_CACHE_DEBUG);
88          if (sysProp != null) {
89              return Boolean.parseBoolean(sysProp);
90          }
91  
92          // Default to false if not configured
93          return ConfigurationProperties.DEFAULT_VERSION_SCHEME_CACHE_DEBUG;
94      }
95  
96      @Override
97      public GenericVersion parseVersion(final String version) throws InvalidVersionSpecificationException {
98          totalRequests.incrementAndGet();
99          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 }