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.apache.maven.artifact.versioning;
20  
21  import java.util.ArrayList;
22  import java.util.Collections;
23  import java.util.Iterator;
24  import java.util.List;
25  import java.util.Map;
26  import java.util.Objects;
27  import java.util.WeakHashMap;
28  
29  import org.apache.maven.artifact.Artifact;
30  
31  /**
32   * Construct a version range from a specification.
33   *
34   * @author <a href="mailto:brett@apache.org">Brett Porter</a>
35   */
36  public class VersionRange {
37      private static final Map<String, VersionRange> CACHE_SPEC =
38              Collections.<String, VersionRange>synchronizedMap(new WeakHashMap<String, VersionRange>());
39  
40      private static final Map<String, VersionRange> CACHE_VERSION =
41              Collections.<String, VersionRange>synchronizedMap(new WeakHashMap<String, VersionRange>());
42  
43      private final ArtifactVersion recommendedVersion;
44  
45      private final List<Restriction> restrictions;
46  
47      private VersionRange(ArtifactVersion recommendedVersion, List<Restriction> restrictions) {
48          this.recommendedVersion = recommendedVersion;
49          this.restrictions = Collections.unmodifiableList(restrictions);
50      }
51  
52      public ArtifactVersion getRecommendedVersion() {
53          return recommendedVersion;
54      }
55  
56      /**
57       * Returns the intervals used to match versions against this range.
58       *
59       * <p>If this list is empty, {@link #containsVersion(ArtifactVersion)} returns {@code false}.
60       * A recommended version may still be available from {@link #getRecommendedVersion()}.</p>
61       *
62       * @return an unmodifiable, non-null list of version restrictions
63       */
64      public List<Restriction> getRestrictions() {
65          return restrictions;
66      }
67  
68      /**
69       * @deprecated VersionRange is immutable, cloning is not useful and even more an issue against the cache
70       * @return a clone
71       */
72      @Deprecated
73      public VersionRange cloneOf() {
74          List<Restriction> copiedRestrictions = null;
75  
76          if (restrictions != null) {
77              copiedRestrictions = new ArrayList<>();
78  
79              if (!restrictions.isEmpty()) {
80                  copiedRestrictions.addAll(restrictions);
81              }
82          }
83  
84          return new VersionRange(recommendedVersion, copiedRestrictions);
85      }
86  
87      /**
88       * <p>
89       * Create a version range from a string representation
90       * </p>
91       * Some spec examples are:
92       * <ul>
93       * <li><code>1.0</code> Version 1.0 as a recommended version</li>
94       * <li><code>[1.0]</code> Version 1.0 explicitly only</li>
95       * <li><code>[1.0,2.0)</code> Versions 1.0 (included) to 2.0 (not included)</li>
96       * <li><code>[1.0,2.0]</code> Versions 1.0 to 2.0 (both included)</li>
97       * <li><code>[1.5,)</code> Versions 1.5 and higher</li>
98       * <li><code>(,1.0],[1.2,)</code> Versions up to 1.0 (included) and 1.2 or higher</li>
99       * </ul>
100      *
101      * @param spec string representation of a version or version range
102      * @return a new {@link VersionRange} object that represents the spec
103      * @throws InvalidVersionSpecificationException
104      *
105      */
106     public static VersionRange createFromVersionSpec(String spec) throws InvalidVersionSpecificationException {
107         if (spec == null) {
108             return null;
109         }
110 
111         VersionRange cached = CACHE_SPEC.get(spec);
112         if (cached != null) {
113             return cached;
114         }
115 
116         List<Restriction> restrictions = new ArrayList<>();
117         String process = spec;
118         ArtifactVersion version = null;
119         ArtifactVersion upperBound = null;
120         ArtifactVersion lowerBound = null;
121 
122         while (process.startsWith("[") || process.startsWith("(")) {
123             int index1 = process.indexOf(')');
124             int index2 = process.indexOf(']');
125 
126             int index = index2;
127             if (index2 < 0 || index1 < index2) {
128                 if (index1 >= 0) {
129                     index = index1;
130                 }
131             }
132 
133             if (index < 0) {
134                 throw new InvalidVersionSpecificationException("Unbounded range: " + spec);
135             }
136 
137             Restriction restriction = parseRestriction(process.substring(0, index + 1));
138             if (lowerBound == null) {
139                 lowerBound = restriction.getLowerBound();
140             }
141             if (upperBound != null) {
142                 if (restriction.getLowerBound() == null
143                         || restriction.getLowerBound().compareTo(upperBound) < 0) {
144                     throw new InvalidVersionSpecificationException("Ranges overlap: " + spec);
145                 }
146             }
147             restrictions.add(restriction);
148             upperBound = restriction.getUpperBound();
149 
150             process = process.substring(index + 1).trim();
151 
152             if (process.length() > 0 && process.startsWith(",")) {
153                 process = process.substring(1).trim();
154             }
155         }
156 
157         if (process.length() > 0) {
158             if (restrictions.size() > 0) {
159                 throw new InvalidVersionSpecificationException(
160                         "Only fully-qualified sets allowed in multiple set scenario: " + spec);
161             } else {
162                 version = new DefaultArtifactVersion(process);
163                 restrictions.add(Restriction.EVERYTHING);
164             }
165         }
166 
167         cached = new VersionRange(version, restrictions);
168         CACHE_SPEC.put(spec, cached);
169         return cached;
170     }
171 
172     private static Restriction parseRestriction(String spec) throws InvalidVersionSpecificationException {
173         boolean lowerBoundInclusive = spec.startsWith("[");
174         boolean upperBoundInclusive = spec.endsWith("]");
175 
176         String process = spec.substring(1, spec.length() - 1).trim();
177 
178         Restriction restriction;
179 
180         int index = process.indexOf(',');
181 
182         if (index < 0) {
183             if (!lowerBoundInclusive || !upperBoundInclusive) {
184                 throw new InvalidVersionSpecificationException("Single version must be surrounded by []: " + spec);
185             }
186 
187             ArtifactVersion version = new DefaultArtifactVersion(process);
188 
189             restriction = new Restriction(version, lowerBoundInclusive, version, upperBoundInclusive);
190         } else {
191             String lowerBound = process.substring(0, index).trim();
192             String upperBound = process.substring(index + 1).trim();
193 
194             ArtifactVersion lowerVersion = null;
195             if (lowerBound.length() > 0) {
196                 lowerVersion = new DefaultArtifactVersion(lowerBound);
197             }
198             ArtifactVersion upperVersion = null;
199             if (upperBound.length() > 0) {
200                 upperVersion = new DefaultArtifactVersion(upperBound);
201             }
202 
203             if (upperVersion != null && lowerVersion != null) {
204                 int result = upperVersion.compareTo(lowerVersion);
205                 if (result < 0 || (result == 0 && (!lowerBoundInclusive || !upperBoundInclusive))) {
206                     throw new InvalidVersionSpecificationException("Range defies version ordering: " + spec);
207                 }
208             }
209 
210             restriction = new Restriction(lowerVersion, lowerBoundInclusive, upperVersion, upperBoundInclusive);
211         }
212 
213         return restriction;
214     }
215 
216     public static VersionRange createFromVersion(String version) {
217         VersionRange cached = CACHE_VERSION.get(version);
218         if (cached == null) {
219             List<Restriction> restrictions = Collections.emptyList();
220             cached = new VersionRange(new DefaultArtifactVersion(version), restrictions);
221             CACHE_VERSION.put(version, cached);
222         }
223         return cached;
224     }
225 
226     /**
227      * Creates and returns a new <code>VersionRange</code> that is a restriction of this
228      * version range and the specified version range.
229      * <p>
230      * Note: Precedence is given to the recommended version from this version range over the
231      * recommended version from the specified version range.
232      * </p>
233      *
234      * @param restriction the <code>VersionRange</code> that will be used to restrict this version
235      *                    range.
236      * @return the <code>VersionRange</code> that is a restriction of this version range and the
237      *         specified version range.
238      *         <p>
239      *         The restrictions of the returned version range will be an intersection of the restrictions
240      *         of this version range and the specified version range if both version ranges have
241      *         restrictions. Otherwise, the restrictions on the returned range will be empty.
242      *         </p>
243      *         <p>
244      *         The recommended version of the returned version range will be the recommended version of
245      *         this version range, provided that ranges falls within the intersected restrictions. If
246      *         the restrictions are empty, this version range's recommended version is used if it is not
247      *         <code>null</code>. If it is <code>null</code>, the specified version range's recommended
248      *         version is used (provided it is non-<code>null</code>). If no recommended version can be
249      *         obtained, the returned version range's recommended version is set to <code>null</code>.
250      *         </p>
251      * @throws NullPointerException if the specified <code>VersionRange</code> is
252      *                              <code>null</code>.
253      */
254     public VersionRange restrict(VersionRange restriction) {
255         List<Restriction> r1 = this.restrictions;
256         List<Restriction> r2 = restriction.restrictions;
257         List<Restriction> restrictions;
258 
259         if (r1.isEmpty() || r2.isEmpty()) {
260             restrictions = Collections.emptyList();
261         } else {
262             restrictions = intersection(r1, r2);
263         }
264 
265         ArtifactVersion version = null;
266         if (restrictions.size() > 0) {
267             for (Restriction r : restrictions) {
268                 if (recommendedVersion != null && r.containsVersion(recommendedVersion)) {
269                     // if we find the original, use that
270                     version = recommendedVersion;
271                     break;
272                 } else if (version == null
273                         && restriction.getRecommendedVersion() != null
274                         && r.containsVersion(restriction.getRecommendedVersion())) {
275                     // use this if we can, but prefer the original if possible
276                     version = restriction.getRecommendedVersion();
277                 }
278             }
279         }
280         // Either the original or the specified version ranges have no restrictions
281         else if (recommendedVersion != null) {
282             // Use the original recommended version since it exists
283             version = recommendedVersion;
284         } else if (restriction.recommendedVersion != null) {
285             // Use the recommended version from the specified VersionRange since there is no
286             // original recommended version
287             version = restriction.recommendedVersion;
288         }
289         /* TODO should throw this immediately, but need artifact
290                 else
291                 {
292                     throw new OverConstrainedVersionException( "Restricting incompatible version ranges" );
293                 }
294         */
295 
296         return new VersionRange(version, restrictions);
297     }
298 
299     private List<Restriction> intersection(List<Restriction> r1, List<Restriction> r2) {
300         List<Restriction> restrictions = new ArrayList<>(r1.size() + r2.size());
301         Iterator<Restriction> i1 = r1.iterator();
302         Iterator<Restriction> i2 = r2.iterator();
303         Restriction res1 = i1.next();
304         Restriction res2 = i2.next();
305 
306         boolean done = false;
307         while (!done) {
308             if (res1.getLowerBound() == null
309                     || res2.getUpperBound() == null
310                     || res1.getLowerBound().compareTo(res2.getUpperBound()) <= 0) {
311                 if (res1.getUpperBound() == null
312                         || res2.getLowerBound() == null
313                         || res1.getUpperBound().compareTo(res2.getLowerBound()) >= 0) {
314                     ArtifactVersion lower;
315                     ArtifactVersion upper;
316                     boolean lowerInclusive;
317                     boolean upperInclusive;
318 
319                     // overlaps
320                     if (res1.getLowerBound() == null) {
321                         lower = res2.getLowerBound();
322                         lowerInclusive = res2.isLowerBoundInclusive();
323                     } else if (res2.getLowerBound() == null) {
324                         lower = res1.getLowerBound();
325                         lowerInclusive = res1.isLowerBoundInclusive();
326                     } else {
327                         int comparison = res1.getLowerBound().compareTo(res2.getLowerBound());
328                         if (comparison < 0) {
329                             lower = res2.getLowerBound();
330                             lowerInclusive = res2.isLowerBoundInclusive();
331                         } else if (comparison == 0) {
332                             lower = res1.getLowerBound();
333                             lowerInclusive = res1.isLowerBoundInclusive() && res2.isLowerBoundInclusive();
334                         } else {
335                             lower = res1.getLowerBound();
336                             lowerInclusive = res1.isLowerBoundInclusive();
337                         }
338                     }
339 
340                     if (res1.getUpperBound() == null) {
341                         upper = res2.getUpperBound();
342                         upperInclusive = res2.isUpperBoundInclusive();
343                     } else if (res2.getUpperBound() == null) {
344                         upper = res1.getUpperBound();
345                         upperInclusive = res1.isUpperBoundInclusive();
346                     } else {
347                         int comparison = res1.getUpperBound().compareTo(res2.getUpperBound());
348                         if (comparison < 0) {
349                             upper = res1.getUpperBound();
350                             upperInclusive = res1.isUpperBoundInclusive();
351                         } else if (comparison == 0) {
352                             upper = res1.getUpperBound();
353                             upperInclusive = res1.isUpperBoundInclusive() && res2.isUpperBoundInclusive();
354                         } else {
355                             upper = res2.getUpperBound();
356                             upperInclusive = res2.isUpperBoundInclusive();
357                         }
358                     }
359 
360                     // don't add if they are equal and one is not inclusive
361                     if (lower == null || upper == null || lower.compareTo(upper) != 0) {
362                         restrictions.add(new Restriction(lower, lowerInclusive, upper, upperInclusive));
363                     } else if (lowerInclusive && upperInclusive) {
364                         restrictions.add(new Restriction(lower, lowerInclusive, upper, upperInclusive));
365                     }
366 
367                     //noinspection ObjectEquality
368                     if (upper == res2.getUpperBound()) {
369                         // advance res2
370                         if (i2.hasNext()) {
371                             res2 = i2.next();
372                         } else {
373                             done = true;
374                         }
375                     } else {
376                         // advance res1
377                         if (i1.hasNext()) {
378                             res1 = i1.next();
379                         } else {
380                             done = true;
381                         }
382                     }
383                 } else {
384                     // move on to next in r1
385                     if (i1.hasNext()) {
386                         res1 = i1.next();
387                     } else {
388                         done = true;
389                     }
390                 }
391             } else {
392                 // move on to next in r2
393                 if (i2.hasNext()) {
394                     res2 = i2.next();
395                 } else {
396                     done = true;
397                 }
398             }
399         }
400 
401         return restrictions;
402     }
403 
404     public ArtifactVersion getSelectedVersion(Artifact artifact) throws OverConstrainedVersionException {
405         ArtifactVersion version;
406         if (recommendedVersion != null) {
407             version = recommendedVersion;
408         } else {
409             if (restrictions.size() == 0) {
410                 throw new OverConstrainedVersionException("The artifact has no valid ranges", artifact);
411             }
412 
413             version = null;
414         }
415         return version;
416     }
417 
418     public boolean isSelectedVersionKnown(Artifact artifact) throws OverConstrainedVersionException {
419         boolean value = false;
420         if (recommendedVersion != null) {
421             value = true;
422         } else {
423             if (restrictions.size() == 0) {
424                 throw new OverConstrainedVersionException("The artifact has no valid ranges", artifact);
425             }
426         }
427         return value;
428     }
429 
430     public String toString() {
431         if (recommendedVersion != null) {
432             return recommendedVersion.toString();
433         } else {
434             StringBuilder buf = new StringBuilder();
435             for (Iterator<Restriction> i = restrictions.iterator(); i.hasNext(); ) {
436                 Restriction r = i.next();
437 
438                 buf.append(r.toString());
439 
440                 if (i.hasNext()) {
441                     buf.append(',');
442                 }
443             }
444             return buf.toString();
445         }
446     }
447 
448     public ArtifactVersion matchVersion(List<ArtifactVersion> versions) {
449         // TODO could be more efficient by sorting the list and then moving along the restrictions in order?
450 
451         ArtifactVersion matched = null;
452         for (ArtifactVersion version : versions) {
453             if (containsVersion(version)) {
454                 // valid - check if it is greater than the currently matched version
455                 if (matched == null || version.compareTo(matched) > 0) {
456                     matched = version;
457                 }
458             }
459         }
460         return matched;
461     }
462 
463     public boolean containsVersion(ArtifactVersion version) {
464         for (Restriction restriction : restrictions) {
465             if (restriction.containsVersion(version)) {
466                 return true;
467             }
468         }
469         return false;
470     }
471 
472     public boolean hasRestrictions() {
473         return !restrictions.isEmpty() && recommendedVersion == null;
474     }
475 
476     public boolean equals(Object obj) {
477         if (this == obj) {
478             return true;
479         }
480         if (!(obj instanceof VersionRange)) {
481             return false;
482         }
483         VersionRange other = (VersionRange) obj;
484 
485         return Objects.equals(recommendedVersion, other.recommendedVersion)
486                 && Objects.equals(restrictions, other.restrictions);
487     }
488 
489     public int hashCode() {
490         int hash = 7;
491         hash = 31 * hash + (recommendedVersion == null ? 0 : recommendedVersion.hashCode());
492         hash = 31 * hash + (restrictions == null ? 0 : restrictions.hashCode());
493         return hash;
494     }
495 }