-
Notifications
You must be signed in to change notification settings - Fork 267
/
DefaultVersionsHelper.java
1061 lines (966 loc) · 39.4 KB
/
DefaultVersionsHelper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.codehaus.mojo.versions.api;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.ArtifactUtils;
import org.apache.maven.artifact.manager.WagonManager;
import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.artifact.versioning.ArtifactVersion;
import org.apache.maven.artifact.versioning.DefaultArtifactVersion;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.settings.Settings;
import org.apache.maven.wagon.ConnectionException;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.UnsupportedProtocolException;
import org.apache.maven.wagon.Wagon;
import org.apache.maven.wagon.authentication.AuthenticationException;
import org.apache.maven.wagon.authorization.AuthorizationException;
import org.codehaus.mojo.versions.PluginUpdatesDetails;
import org.codehaus.mojo.versions.Property;
import org.codehaus.mojo.versions.model.IgnoreVersion;
import org.codehaus.mojo.versions.model.Rule;
import org.codehaus.mojo.versions.model.RuleSet;
import org.codehaus.mojo.versions.model.io.xpp3.RuleXpp3Reader;
import org.codehaus.mojo.versions.ordering.VersionComparator;
import org.codehaus.mojo.versions.ordering.VersionComparators;
import org.codehaus.mojo.versions.utils.DependencyBuilder;
import org.codehaus.mojo.versions.utils.DependencyComparator;
import org.codehaus.mojo.versions.utils.PluginComparator;
import org.codehaus.mojo.versions.utils.RegexUtils;
import org.codehaus.mojo.versions.utils.VersionsExpressionEvaluator;
import org.codehaus.mojo.versions.utils.WagonUtils;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
/**
* Helper class that provides common functionality required by both the mojos and the reports.
*
* @author Stephen Connolly
* @since 1.0-alpha-3
*/
public class DefaultVersionsHelper
implements VersionsHelper
{
private static final String CLASSPATH_PROTOCOL = "classpath";
private static final String TYPE_EXACT = "exact";
private static final String TYPE_REGEX = "regex";
private static final int LOOKUP_PARALLEL_THREADS = 5;
/**
* The artifact comparison rules to use.
*
* @since 1.0-alpha-3
*/
private RuleSet ruleSet;
/**
* The artifact metadata source to use.
*
* @since 1.0-alpha-3
*/
private ArtifactMetadataSource artifactMetadataSource;
/**
* The local repository to consult.
*
* @since 1.0-alpha-3
*/
private ArtifactRepository localRepository;
/**
* The remote artifact repositories to consult.
*
* @since 1.0-alpha-3
*/
private List<ArtifactRepository> remoteArtifactRepositories;
/**
* The remote plugin repositories to consult.
*
* @since 1.0-alpha-3
*/
private List<ArtifactRepository> remotePluginRepositories;
private RepositorySystem repositorySystem;
/**
* The {@link Log} to send log messages to.
*
* @since 1.0-alpha-3
*/
private Log log;
/**
* The maven session.
*
* @since 1.0-beta-1
*/
private MavenSession mavenSession;
/**
* The artifact resolver.
*
* @since 1.3
*/
private ArtifactResolver artifactResolver;
private MojoExecution mojoExecution;
/**
* A cache mapping artifacts to their best fitting rule, since looking up
* this information can be quite costly.
*
* @since 2.12
*/
private final Map<String, Rule> artifactBestFitRule = new HashMap<>();
/**
* Private constructor used by the builder
*/
private DefaultVersionsHelper()
{
}
@Deprecated
private static RuleSet getRuleSet( Wagon wagon, String remoteURI )
throws IOException, AuthorizationException, TransferFailedException, ResourceDoesNotExistException
{
File tempFile = File.createTempFile( "ruleset", ".xml" );
try
{
wagon.get( remoteURI, tempFile );
try ( InputStream is = Files.newInputStream( tempFile.toPath() ) )
{
return readRulesFromStream( is );
}
}
finally
{
if ( !tempFile.delete() )
{
// maybe we can delete this later
tempFile.deleteOnExit();
}
}
}
private static RuleSet readRulesFromStream( InputStream stream )
throws IOException
{
RuleXpp3Reader reader = new RuleXpp3Reader();
try ( BufferedInputStream bis = new BufferedInputStream( stream ) )
{
return reader.read( bis );
}
catch ( XmlPullParserException e )
{
throw new IOException( e );
}
}
static boolean exactMatch( String wildcardRule, String value )
{
Pattern p = Pattern.compile( RegexUtils.convertWildcardsToRegex( wildcardRule, true ) );
return p.matcher( value ).matches();
}
static boolean match( String wildcardRule, String value )
{
Pattern p = Pattern.compile( RegexUtils.convertWildcardsToRegex( wildcardRule, false ) );
return p.matcher( value ).matches();
}
/**
* <p>Creates the enriched version of the ruleSet given as parameter; the ruleSet will contain the
* set of ignored versions passed on top of its own (if defined).</p>
*
* <p>If the {@code originalRuleSet} is {@code null}, a new {@linkplain RuleSet} will be created as
* a result.</p>
*
* <p><em>The method does not change the {@code originalRuleSet} object.</em></p>
*
* @param ignoredVersions collection of ignored version to enrich the clone of the original rule set
* @param originalRuleSet original rule set
* @return new RuleSet object containing the (if passed) cloned version of the rule set, enriched with
* the given set of ignored versions
*/
@SuppressWarnings( "checkstyle:AvoidNestedBlocks" )
private static RuleSet enrichRuleSet( Collection<String> ignoredVersions, RuleSet originalRuleSet )
{
RuleSet ruleSet = new RuleSet();
if ( originalRuleSet != null )
{
ruleSet.setComparisonMethod( originalRuleSet.getComparisonMethod() );
if ( originalRuleSet.getRules() != null )
{
ruleSet.setRules( new ArrayList<>( originalRuleSet.getRules() ) );
}
if ( originalRuleSet.getIgnoreVersions() != null )
{
ruleSet.setIgnoreVersions( new ArrayList<>( originalRuleSet.getIgnoreVersions() ) );
}
}
if ( ruleSet.getIgnoreVersions() == null )
{
ruleSet.setIgnoreVersions( new ArrayList<>() );
}
ruleSet.getIgnoreVersions().addAll( ignoredVersions.stream().map( v ->
{
IgnoreVersion ignoreVersion = new IgnoreVersion();
ignoreVersion.setType( TYPE_REGEX );
ignoreVersion.setVersion( v );
return ignoreVersion;
} ).collect( Collectors.toList() ) );
return ruleSet;
}
private static RuleSet getRulesFromClasspath( String uri, Log logger )
throws MojoExecutionException
{
logger.debug( "Going to load rules from \"" + uri + "\"" );
String choppedUrl = uri.substring( CLASSPATH_PROTOCOL.length() + 3 );
URL url = DefaultVersionsHelper.class.getResource( choppedUrl );
if ( null == url )
{
String message = "Resource \"" + uri + "\" not found in classpath.";
throw new MojoExecutionException( message );
}
try
{
RuleSet rules = readRulesFromStream( url.openStream() );
logger.debug( "Loaded rules from \"" + uri + "\" successfully" );
return rules;
}
catch ( IOException e )
{
throw new MojoExecutionException( "Could not load specified rules from " + uri, e );
}
}
private static RuleSet getRulesViaWagon( String rulesUri, Log logger, String serverId, String id,
WagonManager wagonManager, Settings settings )
throws MojoExecutionException
{
RuleSet loadedRules;
int split = rulesUri.lastIndexOf( '/' );
String baseUri = rulesUri;
String fileUri = "";
if ( split != -1 )
{
baseUri = rulesUri.substring( 0, split ) + '/';
fileUri = split + 1 < rulesUri.length() ? rulesUri.substring( split + 1 ) : "";
}
try
{
Wagon wagon = WagonUtils.createWagon( serverId, baseUri, wagonManager, settings, logger );
try
{
logger.debug( "Trying to load ruleset from file \"" + fileUri + "\" in " + baseUri );
loadedRules = getRuleSet( wagon, fileUri );
}
finally
{
logger.debug( "Rule set loaded" );
if ( wagon != null )
{
try
{
wagon.disconnect();
}
catch ( ConnectionException e )
{
logger.warn( "Could not disconnect wagon!", e );
}
}
}
}
catch ( TransferFailedException e )
{
throw new MojoExecutionException( "Could not transfer rules from " + rulesUri, e );
}
catch ( AuthorizationException e )
{
throw new MojoExecutionException( "Authorization failure trying to load rules from " + rulesUri, e );
}
catch ( ResourceDoesNotExistException | IOException e )
{
throw new MojoExecutionException( "Could not load specified rules from " + rulesUri, e );
}
catch ( AuthenticationException e )
{
throw new MojoExecutionException( "Authentication failure trying to load rules from " + rulesUri, e );
}
catch ( UnsupportedProtocolException e )
{
throw new MojoExecutionException( "Unsupported protocol for " + rulesUri, e );
}
catch ( ConnectionException e )
{
throw new MojoExecutionException( "Could not establish connection to " + rulesUri, e );
}
return loadedRules;
}
static boolean isClasspathUri( String uri )
{
return ( uri != null && uri.startsWith( CLASSPATH_PROTOCOL + ":" ) );
}
@Override
public Log getLog()
{
return log;
}
@Override
public ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePluginRepositories )
throws ArtifactMetadataRetrievalException
{
List<ArtifactRepository> remoteRepositories = usePluginRepositories
? remotePluginRepositories : remoteArtifactRepositories;
final List<ArtifactVersion> versions =
artifactMetadataSource.retrieveAvailableVersions( artifact, localRepository, remoteRepositories );
final List<IgnoreVersion> ignoredVersions = getIgnoredVersions( artifact );
if ( !ignoredVersions.isEmpty() )
{
if ( getLog().isDebugEnabled() )
{
getLog().debug( "Found ignored versions: " + showIgnoredVersions( ignoredVersions ) );
}
final Iterator<ArtifactVersion> i = versions.iterator();
while ( i.hasNext() )
{
final String version = i.next().toString();
for ( final IgnoreVersion ignoreVersion : ignoredVersions )
{
if ( TYPE_REGEX.equals( ignoreVersion.getType() ) )
{
Pattern p = Pattern.compile( ignoreVersion.getVersion() );
if ( p.matcher( version ).matches() )
{
if ( getLog().isDebugEnabled() )
{
getLog().debug( "Version " + version + " for artifact "
+ ArtifactUtils.versionlessKey( artifact )
+ " found on ignore list: "
+ ignoreVersion );
}
i.remove();
break;
}
}
else if ( TYPE_EXACT.equals( ignoreVersion.getType() ) )
{
if ( version.equals( ignoreVersion.getVersion() ) )
{
if ( getLog().isDebugEnabled() )
{
getLog().debug( "Version " + version + " for artifact "
+ ArtifactUtils.versionlessKey( artifact )
+ " found on ignore list: "
+ ignoreVersion );
}
i.remove();
break;
}
}
}
}
}
return new ArtifactVersions( artifact, versions, getVersionComparator( artifact ) );
}
/**
* Returns a list of versions which should not be considered when looking for updates.
*
* @param artifact The artifact
* @return List of ignored version
*/
private List<IgnoreVersion> getIgnoredVersions( Artifact artifact )
{
final List<IgnoreVersion> ret = new ArrayList<>();
for ( final IgnoreVersion ignoreVersion : ruleSet.getIgnoreVersions() )
{
if ( !TYPE_EXACT.equals( ignoreVersion.getType() ) && !TYPE_REGEX.equals( ignoreVersion.getType() ) )
{
getLog().warn( "The type attribute '" + ignoreVersion.getType() + "' for global ignoreVersion["
+ ignoreVersion + "] is not valid." + " Please use either '" + TYPE_EXACT + "' or '"
+ TYPE_REGEX
+ "'." );
}
else
{
ret.add( ignoreVersion );
}
}
final Rule rule = getBestFitRule( artifact.getGroupId(), artifact.getArtifactId() );
if ( rule != null )
{
for ( IgnoreVersion ignoreVersion : rule.getIgnoreVersions() )
{
if ( !TYPE_EXACT.equals( ignoreVersion.getType() ) && !TYPE_REGEX.equals( ignoreVersion.getType() ) )
{
getLog().warn( "The type attribute '" + ignoreVersion.getType() + "' for " + rule + " is not valid."
+ " Please use either '" + TYPE_EXACT + "' or '" + TYPE_REGEX + "'." );
}
else
{
ret.add( ignoreVersion );
}
}
}
return ret;
}
/**
* Pretty print a list of ignored versions.
*
* @param ignoredVersions A list of ignored versions
* @return A String representation of the list
*/
private String showIgnoredVersions( List<IgnoreVersion> ignoredVersions )
{
StringBuilder buf = new StringBuilder();
Iterator<IgnoreVersion> iterator = ignoredVersions.iterator();
while ( iterator.hasNext() )
{
IgnoreVersion ignoreVersion = iterator.next();
buf.append( ignoreVersion );
if ( iterator.hasNext() )
{
buf.append( ", " );
}
}
return buf.toString();
}
@Override
public void resolveArtifact( Artifact artifact, boolean usePluginRepositories )
throws ArtifactResolutionException, ArtifactNotFoundException
{
List<ArtifactRepository> remoteRepositories =
usePluginRepositories ? remotePluginRepositories : remoteArtifactRepositories;
artifactResolver.resolve( artifact, remoteRepositories, localRepository );
}
@Override
public VersionComparator getVersionComparator( Artifact artifact )
{
return getVersionComparator( artifact.getGroupId(), artifact.getArtifactId() );
}
@Override
public VersionComparator getVersionComparator( String groupId, String artifactId )
{
Rule rule = getBestFitRule( groupId, artifactId );
final String comparisonMethod = rule == null ? ruleSet.getComparisonMethod() : rule.getComparisonMethod();
return VersionComparators.getVersionComparator( comparisonMethod );
}
/**
* Find the rule, if any, which best fits the artifact details given.
*
* @param groupId Group id of the artifact
* @param artifactId Artifact id of the artifact
* @return Rule which best describes the given artifact
*/
protected Rule getBestFitRule( String groupId, String artifactId )
{
String groupArtifactId = groupId + ':' + artifactId;
if ( artifactBestFitRule.containsKey( groupArtifactId ) )
{
return artifactBestFitRule.get( groupArtifactId );
}
Rule bestFit = null;
final List<Rule> rules = ruleSet.getRules();
int bestGroupIdScore = Integer.MAX_VALUE;
int bestArtifactIdScore = Integer.MAX_VALUE;
boolean exactGroupId = false;
boolean exactArtifactId = false;
for ( Rule rule : rules )
{
int groupIdScore = RegexUtils.getWildcardScore( rule.getGroupId() );
if ( groupIdScore > bestGroupIdScore )
{
continue;
}
boolean exactMatch = exactMatch( rule.getGroupId(), groupId );
boolean match = exactMatch || match( rule.getGroupId(), groupId );
if ( !match || ( exactGroupId && !exactMatch ) )
{
continue;
}
if ( bestGroupIdScore > groupIdScore )
{
bestArtifactIdScore = Integer.MAX_VALUE;
exactArtifactId = false;
}
bestGroupIdScore = groupIdScore;
if ( exactMatch && !exactGroupId )
{
exactGroupId = true;
bestArtifactIdScore = Integer.MAX_VALUE;
exactArtifactId = false;
}
int artifactIdScore = RegexUtils.getWildcardScore( rule.getArtifactId() );
if ( artifactIdScore > bestArtifactIdScore )
{
continue;
}
exactMatch = exactMatch( rule.getArtifactId(), artifactId );
match = exactMatch || match( rule.getArtifactId(), artifactId );
if ( !match || ( exactArtifactId && !exactMatch ) )
{
continue;
}
bestArtifactIdScore = artifactIdScore;
if ( exactMatch && !exactArtifactId )
{
exactArtifactId = true;
}
bestFit = rule;
}
artifactBestFitRule.put( groupArtifactId, bestFit );
return bestFit;
}
@Override
public Artifact createPluginArtifact( String groupId, String artifactId, String version )
{
Plugin plugin = new Plugin();
plugin.setGroupId( groupId );
plugin.setArtifactId( artifactId );
plugin.setVersion( StringUtils.isNotBlank( version ) ? version : "[0,]" );
return repositorySystem.createPluginArtifact( plugin );
}
@Override
public Artifact createDependencyArtifact( String groupId, String artifactId, String version, String type,
String classifier, String scope, boolean optional )
{
return repositorySystem.createDependencyArtifact( DependencyBuilder.newBuilder()
.withGroupId( groupId )
.withArtifactId( artifactId )
.withType( type )
.withClassifier( classifier )
.withScope( scope )
.withOptional( optional )
.withVersion( StringUtils.isNotBlank( version ) ? version : "[0,]" )
.build() );
}
@Override
public Artifact createDependencyArtifact( String groupId, String artifactId, String version, String type,
String classifier, String scope )
{
return createDependencyArtifact( groupId, artifactId, version, type, classifier, scope, false );
}
@Override
public Artifact createDependencyArtifact( Dependency dependency )
{
if ( StringUtils.isBlank( dependency.getVersion() ) )
{
dependency = dependency.clone();
dependency.setVersion( "[,0]" );
}
return repositorySystem.createDependencyArtifact( dependency );
}
@Override
public Set<Artifact> extractArtifacts( Collection<MavenProject> mavenProjects )
{
Set<Artifact> result = new HashSet<>();
for ( MavenProject project : mavenProjects )
{
result.add( project.getArtifact() );
}
return result;
}
@Override
public ArtifactVersion createArtifactVersion( String version )
{
return new DefaultArtifactVersion( version );
}
/**
* Returns a map of all possible updates per dependency. The lookup is done in parallel using
* {@code LOOKUP_PARALLEL_THREADS} threads.
*
* @param dependencies The set of {@link Dependency} instances to look up.
* @param usePluginRepositories Search the plugin repositories.
* @return map containing the ArtifactVersions object per dependency
* @throws ArtifactMetadataRetrievalException if the lookup does not succeed
*/
@Override
public Map<Dependency, ArtifactVersions> lookupDependenciesUpdates( Set<Dependency> dependencies,
boolean usePluginRepositories )
throws ArtifactMetadataRetrievalException
{
ExecutorService executor = Executors.newFixedThreadPool( LOOKUP_PARALLEL_THREADS );
try
{
Map<Dependency, ArtifactVersions> dependencyUpdates = new TreeMap<>( DependencyComparator.INSTANCE );
List<Future<? extends Pair<Dependency, ArtifactVersions>>> futures = dependencies.stream()
.map( dependency -> executor.submit( () -> new ImmutablePair<>
( dependency, lookupDependencyUpdates( dependency, usePluginRepositories ) ) ) )
.collect( Collectors.toList() );
for ( Future<? extends Pair<Dependency, ArtifactVersions>> details : futures )
{
Pair<Dependency, ArtifactVersions> pair = details.get();
dependencyUpdates.put( pair.getKey(), pair.getValue() );
}
return dependencyUpdates;
}
catch ( ExecutionException | InterruptedException ie )
{
throw new ArtifactMetadataRetrievalException( "Unable to acquire metadata for dependencies " + dependencies
+ ": " + ie.getMessage(), ie, null );
}
finally
{
executor.shutdown();
}
}
@Override
public ArtifactVersions lookupDependencyUpdates( Dependency dependency, boolean usePluginRepositories )
throws ArtifactMetadataRetrievalException
{
ArtifactVersions allVersions = lookupArtifactVersions( createDependencyArtifact( dependency ),
usePluginRepositories );
return new ArtifactVersions( allVersions.getArtifact(), Arrays.stream( allVersions.getAllUpdates() )
.collect( Collectors.toList() ), allVersions.getVersionComparator() );
}
@Override
public Map<Plugin, PluginUpdatesDetails> lookupPluginsUpdates( Set<Plugin> plugins, boolean allowSnapshots )
throws ArtifactMetadataRetrievalException
{
ExecutorService executor = Executors.newFixedThreadPool( LOOKUP_PARALLEL_THREADS );
try
{
Map<Plugin, PluginUpdatesDetails> pluginUpdates = new TreeMap<>( PluginComparator.INSTANCE );
List<Future<? extends Pair<Plugin, PluginUpdatesDetails>>> futures = plugins.stream()
.map( p -> executor.submit( () -> new ImmutablePair<>
( p, lookupPluginUpdates( p, allowSnapshots ) ) ) )
.collect( Collectors.toList() );
for ( Future<? extends Pair<Plugin, PluginUpdatesDetails>> details : futures )
{
Pair<Plugin, PluginUpdatesDetails> pair = details.get();
pluginUpdates.put( pair.getKey(), pair.getValue() );
}
return pluginUpdates;
}
catch ( ExecutionException | InterruptedException ie )
{
throw new ArtifactMetadataRetrievalException( "Unable to acquire metadata for plugins " + plugins + ": "
+ ie.getMessage(), ie, null );
}
finally
{
executor.shutdown();
}
}
@Override
public PluginUpdatesDetails lookupPluginUpdates( Plugin plugin, boolean allowSnapshots )
throws ArtifactMetadataRetrievalException
{
String version = plugin.getVersion() != null
? plugin.getVersion()
: "LATEST";
Set<Dependency> pluginDependencies = new TreeSet<>( DependencyComparator.INSTANCE );
if ( plugin.getDependencies() != null )
{
pluginDependencies.addAll( plugin.getDependencies() );
}
Map<Dependency, ArtifactVersions> pluginDependencyDetails =
lookupDependenciesUpdates( pluginDependencies, false );
ArtifactVersions allVersions =
lookupArtifactVersions( createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), version ),
true );
ArtifactVersions updatedVersions = new ArtifactVersions( allVersions.getArtifact(),
Arrays.stream( allVersions.getAllUpdates() ).collect( Collectors.toList() ),
allVersions.getVersionComparator() );
return new PluginUpdatesDetails( updatedVersions, pluginDependencyDetails, allowSnapshots );
}
@Override
public ExpressionEvaluator getExpressionEvaluator( MavenProject project )
{
return new VersionsExpressionEvaluator( mavenSession, mojoExecution );
}
@Override
public Map<Property, PropertyVersions> getVersionPropertiesMap( VersionPropertiesMapRequest request )
throws MojoExecutionException
{
Map<String, Property> properties = new HashMap<>();
if ( request.getPropertyDefinitions() != null )
{
Arrays.stream( request.getPropertyDefinitions() ).forEach( p -> properties.put( p.getName(), p ) );
}
Map<String, PropertyVersionsBuilder> builders = new HashMap<>();
if ( request.isAutoLinkItems() )
{
final PropertyVersionsBuilder[] propertyVersionsBuilders;
try
{
propertyVersionsBuilders = PomHelper.getPropertyVersionsBuilders( this, request.getMavenProject(),
request.isIncludeParent() );
}
catch ( ExpressionEvaluationException | IOException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
for ( PropertyVersionsBuilder propertyVersionsBuilder : propertyVersionsBuilders )
{
final String name = propertyVersionsBuilder.getName();
builders.put( name, propertyVersionsBuilder );
if ( !properties.containsKey( name ) )
{
final Property value = new Property( name );
getLog().debug( "Property ${" + name + "}: Adding inferred version range of "
+ propertyVersionsBuilder.getVersionRange() );
value.setVersion( propertyVersionsBuilder.getVersionRange() );
properties.put( name, value );
}
}
}
List<String> includePropertiesList = request.getIncludeProperties() != null
? Arrays.asList( request.getIncludeProperties().split( "\\s*,\\s*" ) )
: Collections.emptyList();
List<String> excludePropertiesList = request.getExcludeProperties() != null
? Arrays.asList( request.getExcludeProperties().split( "\\s*,\\s*" ) )
: Collections.emptyList();
getLog().debug( "Searching for properties associated with builders" );
Iterator<Property> i = properties.values().iterator();
while ( i.hasNext() )
{
Property property = i.next();
getLog().debug( "includePropertiesList:" + includePropertiesList + " property: " + property.getName() );
getLog().debug( "excludePropertiesList:" + excludePropertiesList + " property: " + property.getName() );
if ( !includePropertiesList.isEmpty() && !includePropertiesList.contains( property.getName() ) )
{
getLog().debug( "Skipping property ${" + property.getName() + "}" );
i.remove();
}
else if ( !excludePropertiesList.isEmpty() && excludePropertiesList.contains( property.getName() ) )
{
getLog().debug( "Ignoring property ${" + property.getName() + "}" );
i.remove();
}
}
i = properties.values().iterator();
Map<Property, PropertyVersions> propertyVersions = new LinkedHashMap<>( properties.size() );
while ( i.hasNext() )
{
Property property = i.next();
getLog().debug( "Property ${" + property.getName() + "}" );
PropertyVersionsBuilder builder = builders.get( property.getName() );
if ( builder == null || !builder.isAssociated() )
{
getLog().debug( "Property ${" + property.getName() + "}: Looks like this property is not "
+ "associated with any dependency..." );
builder = new PropertyVersionsBuilder( null, property.getName(), this );
}
if ( !property.isAutoLinkDependencies() )
{
getLog().debug( "Property ${" + property.getName() + "}: Removing any autoLinkDependencies" );
builder.clearAssociations();
}
Dependency[] dependencies = property.getDependencies();
if ( dependencies != null )
{
for ( Dependency dependency : dependencies )
{
getLog().debug( "Property ${" + property.getName() + "}: Adding association to " + dependency );
builder.addAssociation( this.createDependencyArtifact( dependency ), false );
}
}
try
{
final PropertyVersions versions = builder.newPropertyVersions();
if ( property.isAutoLinkDependencies() && StringUtils.isEmpty( property.getVersion() )
&& !StringUtils.isEmpty( builder.getVersionRange() ) )
{
getLog().debug( "Property ${" + property.getName() + "}: Adding inferred version range of "
+ builder.getVersionRange() );
property.setVersion( builder.getVersionRange() );
}
versions.setCurrentVersion( request.getMavenProject().getProperties()
.getProperty( property.getName() ) );
propertyVersions.put( property, versions );
}
catch ( ArtifactMetadataRetrievalException e )
{
throw new MojoExecutionException( e.getMessage(), e );
}
}
return propertyVersions;
}
/**
* Builder class for {@linkplain DefaultVersionsHelper}
*/
public static class Builder
{
private RepositorySystem repositorySystem;
private ArtifactResolver artifactResolver;
private ArtifactMetadataSource artifactMetadataSource;
private List<ArtifactRepository> remoteArtifactRepositories;
private List<ArtifactRepository> remotePluginRepositories;
private ArtifactRepository localRepository;
private Collection<String> ignoredVersions;
private RuleSet ruleSet;
private WagonManager wagonManager;
private Settings settings;
private String serverId;
private String rulesUri;
private Log log;
private MavenSession mavenSession;
private MojoExecution mojoExecution;
public Builder()
{
}
public Builder withRepositorySystem( RepositorySystem repositorySystem )
{
this.repositorySystem = repositorySystem;
return this;
}
public Builder withArtifactResolver( ArtifactResolver artifactResolver )
{
this.artifactResolver = artifactResolver;
return this;
}
public Builder withArtifactMetadataSource( ArtifactMetadataSource artifactMetadataSource )
{
this.artifactMetadataSource = artifactMetadataSource;
return this;
}
public Builder withRemoteArtifactRepositories(
List<ArtifactRepository> remoteArtifactRepositories )
{
this.remoteArtifactRepositories = remoteArtifactRepositories;
return this;
}
public Builder withRemotePluginRepositories(
List<ArtifactRepository> remotePluginRepositories )
{
this.remotePluginRepositories = remotePluginRepositories;
return this;
}
public Builder withLocalRepository( ArtifactRepository localRepository )
{
this.localRepository = localRepository;
return this;
}
public Builder withIgnoredVersions( Collection<String> ignoredVersions )
{
this.ignoredVersions = ignoredVersions;
return this;
}
public Builder withRuleSet( RuleSet ruleSet )
{
this.ruleSet = ruleSet;
return this;
}
public Builder withWagonManager( WagonManager wagonManager )
{
this.wagonManager = wagonManager;
return this;
}
public Builder withSettings( Settings settings )
{
this.settings = settings;
return this;
}
public Builder withServerId( String serverId )
{
this.serverId = serverId;
return this;
}
public Builder withRulesUri( String rulesUri )
{
this.rulesUri = rulesUri;
return this;
}
public Builder withLog( Log log )
{
this.log = log;
return this;