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        boolean[] created = {false};
103        GenericVersion result;
104        synchronized (versionCache) {
105            result = versionCache.computeIfAbsent(version, v -> {
106                created[0] = true;
107                return new GenericVersion(v);
108            });
109        }
110        if (created[0]) {
111            cacheMisses.incrementAndGet();
112            GLOBAL_CACHE_MISSES.incrementAndGet();
113        } else {
114            cacheHits.incrementAndGet();
115            GLOBAL_CACHE_HITS.incrementAndGet();
116        }
117        return result;
118    }
119
120    /**
121     * Get cache statistics for this instance.
122     */
123    public String getCacheStatistics() {
124        long hits = cacheHits.get();
125        long misses = cacheMisses.get();
126        long total = totalRequests.get();
127        double hitRate = total > 0 ? (double) hits / total * 100.0 : 0.0;
128
129        return String.format(
130                "GenericVersionScheme Cache Stats: hits=%d, misses=%d, total=%d, hit-rate=%.2f%%, cache-size=%d",
131                hits, misses, total, hitRate, versionCache.size());
132    }
133
134    /**
135     * Print global statistics across all instances.
136     */
137    private static void printGlobalStatistics() {
138        long hits = GLOBAL_CACHE_HITS.get();
139        long misses = GLOBAL_CACHE_MISSES.get();
140        long total = GLOBAL_TOTAL_REQUESTS.get();
141        long instances = INSTANCE_COUNT.get();
142        double hitRate = total > 0 ? (double) hits / total * 100.0 : 0.0;
143
144        System.err.println("=== GenericVersionScheme Global Cache Statistics (WeakHashMap) ===");
145        System.err.println(String.format("Total instances created: %d", instances));
146        System.err.println(String.format("Total requests: %d", total));
147        System.err.println(String.format("Cache hits: %d", hits));
148        System.err.println(String.format("Cache misses: %d", misses));
149        System.err.println(String.format("Hit rate: %.2f%%", hitRate));
150        System.err.println(
151                String.format("Average requests per instance: %.2f", instances > 0 ? (double) total / instances : 0.0));
152        System.err.println("=== End Cache Statistics ===");
153    }
154
155    /**
156     * A handy main method that behaves similarly like maven-artifact ComparableVersion is, to make possible test
157     * and possibly compare differences between the two.
158     * <p>
159     * To check how "1.2.7" compares to "1.2-SNAPSHOT", for example, you can issue
160     * <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>
161     * command to command line, output is very similar to that of ComparableVersion on purpose.
162     */
163    public static void main(String... args) {
164        System.out.println(
165                "Display parameters as parsed by Maven Resolver 'generic' scheme (in canonical form and as a list of tokens)"
166                        + " and comparison result:");
167        if (args.length == 0) {
168            return;
169        }
170
171        GenericVersionScheme scheme = new GenericVersionScheme();
172        GenericVersion prev = null;
173        int i = 1;
174        for (String version : args) {
175            if (!StandardCharsets.US_ASCII.newEncoder().canEncode(version)) {
176                System.out.println("WW Use of non-ASCII characters for version strings is not recommended.");
177            }
178            try {
179                GenericVersion c = scheme.parseVersion(version);
180
181                if (prev != null) {
182                    int compare = prev.compareTo(c);
183                    System.out.println(
184                            "   " + prev + ' ' + ((compare == 0) ? "==" : ((compare < 0) ? "<" : ">")) + ' ' + version);
185                }
186
187                System.out.println((i++) + ". " + version + " -> " + c.asString() + "; tokens: " + c.asItems());
188
189                prev = c;
190            } catch (InvalidVersionSpecificationException e) {
191                System.err.println("Invalid version: " + version + " - " + e.getMessage());
192            }
193        }
194    }
195}