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