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.nio.charset.StandardCharsets;
022import java.util.Collections;
023import java.util.Map;
024import java.util.WeakHashMap;
025import java.util.concurrent.atomic.AtomicLong;
026
027import org.eclipse.aether.ConfigurationProperties;
028import org.eclipse.aether.version.InvalidVersionSpecificationException;
029
030/**
031 * A version scheme using a generic version syntax and common sense sorting.
032 * <p>
033 * This scheme accepts versions of any form, interpreting a version as a sequence of numeric and alphabetic segments.
034 * The characters '-', '_', and '.' as well as the mere transitions from digit to letter and vice versa delimit the
035 * version segments. Delimiters are treated as equivalent.
036 * </p>
037 * <p>
038 * Numeric segments are compared mathematically, alphabetic segments are compared lexicographically and
039 * case-insensitively. However, the following qualifier strings are recognized and treated specially: "alpha" = "a" &lt;
040 * "beta" = "b" &lt; "milestone" = "m" &lt; "cr" = "rc" &lt; "snapshot" &lt; "final" = "ga" &lt; "sp". All of those
041 * well-known qualifiers are considered smaller/older than other strings. An empty segment/string is equivalent to 0.
042 * </p>
043 * <p>
044 * In addition to the above mentioned qualifiers, the tokens "min" and "max" may be used as final version segment to
045 * denote the smallest/greatest version having a given prefix. For example, "1.2.min" denotes the smallest version in
046 * 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
047 * for "[M.N.min, M.N.max]".
048 * </p>
049 * <p>
050 * Numbers and strings are considered incomparable against each other. Where version segments of different kind would
051 * collide, comparison will instead assume that the previous segments are padded with trailing 0 or "ga" segments,
052 * respectively, until the kind mismatch is resolved, e.g. "1-alpha" = "1.0.0-alpha" &lt; "1.0.1-ga" = "1.0.1".
053 * </p>
054 */
055public class GenericVersionScheme extends VersionSchemeSupport {
056
057    // Using WeakHashMap wrapped in synchronizedMap for thread safety and memory-sensitive caching
058    private final Map<String, GenericVersion> versionCache = Collections.synchronizedMap(new WeakHashMap<>());
059
060    // Cache statistics
061    private final AtomicLong cacheHits = new AtomicLong(0);
062    private final AtomicLong cacheMisses = new AtomicLong(0);
063    private final AtomicLong totalRequests = new AtomicLong(0);
064
065    // Static statistics across all instances
066    private static final AtomicLong GLOBAL_CACHE_HITS = new AtomicLong(0);
067    private static final AtomicLong GLOBAL_CACHE_MISSES = new AtomicLong(0);
068    private static final AtomicLong GLOBAL_TOTAL_REQUESTS = new AtomicLong(0);
069    private static final AtomicLong INSTANCE_COUNT = new AtomicLong(0);
070
071    static {
072        // Register shutdown hook to print statistics if enabled
073        if (isStatisticsEnabled()) {
074            Runtime.getRuntime().addShutdownHook(new Thread(GenericVersionScheme::printGlobalStatistics));
075        }
076    }
077
078    public GenericVersionScheme() {
079        INSTANCE_COUNT.incrementAndGet();
080    }
081
082    /**
083     * Checks if version scheme cache statistics should be printed.
084     * This checks both the system property and the configuration property.
085     */
086    private static boolean isStatisticsEnabled() {
087        // Check system property first (for backwards compatibility and ease of use)
088        String sysProp = System.getProperty(ConfigurationProperties.VERSION_SCHEME_CACHE_DEBUG);
089        if (sysProp != null) {
090            return Boolean.parseBoolean(sysProp);
091        }
092
093        // Default to false if not configured
094        return ConfigurationProperties.DEFAULT_VERSION_SCHEME_CACHE_DEBUG;
095    }
096
097    @Override
098    public GenericVersion parseVersion(final String version) throws InvalidVersionSpecificationException {
099        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}