/
JavaAnnotationsMojoDescriptorExtractor.java
875 lines (750 loc) · 36.8 KB
/
JavaAnnotationsMojoDescriptorExtractor.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
package org.apache.maven.tools.plugin.extractor.annotations;
/*
* 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 javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
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.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.library.SortedClassLibraryBuilder;
import com.thoughtworks.qdox.model.DocletTag;
import com.thoughtworks.qdox.model.JavaAnnotatedElement;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;
import com.thoughtworks.qdox.model.JavaMember;
import com.thoughtworks.qdox.model.JavaMethod;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.ArtifactResolutionRequest;
import org.apache.maven.artifact.resolver.ArtifactResolutionResult;
import org.apache.maven.plugin.descriptor.DuplicateParameterException;
import org.apache.maven.plugin.descriptor.InvalidParameterException;
import org.apache.maven.plugin.descriptor.InvalidPluginDescriptorException;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.descriptor.Requirement;
import org.apache.maven.project.MavenProject;
import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.tools.plugin.ExtendedMojoDescriptor;
import org.apache.maven.tools.plugin.PluginToolsRequest;
import org.apache.maven.tools.plugin.extractor.ExtractionException;
import org.apache.maven.tools.plugin.extractor.GroupKey;
import org.apache.maven.tools.plugin.extractor.MojoDescriptorExtractor;
import org.apache.maven.tools.plugin.extractor.annotations.converter.ConverterContext;
import org.apache.maven.tools.plugin.extractor.annotations.converter.JavaClassConverterContext;
import org.apache.maven.tools.plugin.extractor.annotations.converter.JavadocBlockTagsToXhtmlConverter;
import org.apache.maven.tools.plugin.extractor.annotations.converter.JavadocInlineTagsToXhtmlConverter;
import org.apache.maven.tools.plugin.extractor.annotations.datamodel.ComponentAnnotationContent;
import org.apache.maven.tools.plugin.extractor.annotations.datamodel.ExecuteAnnotationContent;
import org.apache.maven.tools.plugin.extractor.annotations.datamodel.MojoAnnotationContent;
import org.apache.maven.tools.plugin.extractor.annotations.datamodel.ParameterAnnotationContent;
import org.apache.maven.tools.plugin.extractor.annotations.scanner.MojoAnnotatedClass;
import org.apache.maven.tools.plugin.extractor.annotations.scanner.MojoAnnotationsScanner;
import org.apache.maven.tools.plugin.extractor.annotations.scanner.MojoAnnotationsScannerRequest;
import org.apache.maven.tools.plugin.javadoc.JavadocLinkGenerator;
import org.apache.maven.tools.plugin.util.PluginUtils;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.StringUtils;
/**
* JavaMojoDescriptorExtractor, a MojoDescriptor extractor to read descriptors from java classes with annotations.
* Notice that source files are also parsed to get description, since and deprecation information.
*
* @author Olivier Lamy
* @since 3.0
*/
@Named( JavaAnnotationsMojoDescriptorExtractor.NAME )
@Singleton
public class JavaAnnotationsMojoDescriptorExtractor
extends AbstractLogEnabled
implements MojoDescriptorExtractor
{
public static final String NAME = "java-annotations";
private static final GroupKey GROUP_KEY = new GroupKey( GroupKey.JAVA_GROUP, 100 );
@Inject
private MojoAnnotationsScanner mojoAnnotationsScanner;
@Inject
private RepositorySystem repositorySystem;
@Inject
private ArchiverManager archiverManager;
@Inject
private JavadocInlineTagsToXhtmlConverter javadocInlineTagsToHtmlConverter;
@Inject
private JavadocBlockTagsToXhtmlConverter javadocBlockTagsToHtmlConverter;
@Override
public String getName()
{
return NAME;
}
@Override
public boolean isDeprecated()
{
return false; // this is the "current way" to write Java Mojos
}
@Override
public GroupKey getGroupKey()
{
return GROUP_KEY;
}
@Override
public List<MojoDescriptor> execute( PluginToolsRequest request )
throws ExtractionException, InvalidPluginDescriptorException
{
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses = scanAnnotations( request );
JavaProjectBuilder builder = scanJavadoc( request, mojoAnnotatedClasses.values() );
Map<String, JavaClass> javaClassesMap = discoverClasses( builder );
final JavadocLinkGenerator linkGenerator;
if ( request.getInternalJavadocBaseUrl() != null || ( request.getExternalJavadocBaseUrls() != null
&& !request.getExternalJavadocBaseUrls().isEmpty() ) )
{
linkGenerator = new JavadocLinkGenerator( request.getInternalJavadocBaseUrl(),
request.getInternalJavadocVersion(),
request.getExternalJavadocBaseUrls(),
request.getSettings() );
}
else
{
linkGenerator = null;
}
populateDataFromJavadoc( builder, mojoAnnotatedClasses, javaClassesMap, linkGenerator );
return toMojoDescriptors( mojoAnnotatedClasses, request.getPluginDescriptor() );
}
private Map<String, MojoAnnotatedClass> scanAnnotations( PluginToolsRequest request )
throws ExtractionException
{
MojoAnnotationsScannerRequest mojoAnnotationsScannerRequest = new MojoAnnotationsScannerRequest();
File output = new File( request.getProject().getBuild().getOutputDirectory() );
mojoAnnotationsScannerRequest.setClassesDirectories( Arrays.asList( output ) );
mojoAnnotationsScannerRequest.setDependencies( request.getDependencies() );
mojoAnnotationsScannerRequest.setProject( request.getProject() );
return mojoAnnotationsScanner.scan( mojoAnnotationsScannerRequest );
}
private JavaProjectBuilder scanJavadoc( PluginToolsRequest request,
Collection<MojoAnnotatedClass> mojoAnnotatedClasses )
throws ExtractionException
{
// found artifact from reactors to scan sources
// we currently only scan sources from reactors
List<MavenProject> mavenProjects = new ArrayList<>();
// if we need to scan sources from external artifacts
Set<Artifact> externalArtifacts = new HashSet<>();
JavaProjectBuilder builder = new JavaProjectBuilder( new SortedClassLibraryBuilder( ) );
builder.setEncoding( request.getEncoding() );
extendJavaProjectBuilder( builder, request.getProject() );
for ( MojoAnnotatedClass mojoAnnotatedClass : mojoAnnotatedClasses )
{
if ( Objects.equals( mojoAnnotatedClass.getArtifact().getArtifactId(),
request.getProject().getArtifact().getArtifactId() ) )
{
continue;
}
if ( !isMojoAnnnotatedClassCandidate( mojoAnnotatedClass ) )
{
// we don't scan sources for classes without mojo annotations
continue;
}
MavenProject mavenProject =
getFromProjectReferences( mojoAnnotatedClass.getArtifact(), request.getProject() );
if ( mavenProject != null )
{
mavenProjects.add( mavenProject );
}
else
{
externalArtifacts.add( mojoAnnotatedClass.getArtifact() );
}
}
// try to get artifact with sources classifier, extract somewhere then scan for @since, @deprecated
for ( Artifact artifact : externalArtifacts )
{
// parameter for test-sources too ?? olamy I need that for it test only
if ( StringUtils.equalsIgnoreCase( "tests", artifact.getClassifier() ) )
{
extendJavaProjectBuilderWithSourcesJar( builder, artifact, request, "test-sources" );
}
else
{
extendJavaProjectBuilderWithSourcesJar( builder, artifact, request, "sources" );
}
}
for ( MavenProject mavenProject : mavenProjects )
{
extendJavaProjectBuilder( builder, mavenProject );
}
return builder;
}
private boolean isMojoAnnnotatedClassCandidate( MojoAnnotatedClass mojoAnnotatedClass )
{
return mojoAnnotatedClass != null && mojoAnnotatedClass.hasAnnotations();
}
/**
* from sources scan to get @since and @deprecated and description of classes and fields.
*/
protected void populateDataFromJavadoc( JavaProjectBuilder javaProjectBuilder,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses,
Map<String, JavaClass> javaClassesMap,
JavadocLinkGenerator linkGenerator )
{
for ( Map.Entry<String, MojoAnnotatedClass> entry : mojoAnnotatedClasses.entrySet() )
{
JavaClass javaClass = javaClassesMap.get( entry.getKey() );
if ( javaClass == null )
{
continue;
}
// populate class-level content
MojoAnnotationContent mojoAnnotationContent = entry.getValue().getMojo();
if ( mojoAnnotationContent != null )
{
JavaClassConverterContext context =
new JavaClassConverterContext( javaClass, javaProjectBuilder,
mojoAnnotatedClasses, linkGenerator,
javaClass.getLineNumber() );
mojoAnnotationContent.setDescription(
getDescriptionFromElement( javaClass, context ) );
DocletTag since = findInClassHierarchy( javaClass, "since" );
if ( since != null )
{
mojoAnnotationContent.setSince( getRawValueFromTaglet ( since, context ) );
}
DocletTag deprecated = findInClassHierarchy( javaClass, "deprecated" );
if ( deprecated != null )
{
mojoAnnotationContent.setDeprecated( getRawValueFromTaglet ( deprecated, context ) );
}
}
Map<String, JavaAnnotatedElement> elementMap = extractParameterAnnotations( javaClass, javaClassesMap );
// populate parameters
Map<String, ParameterAnnotationContent> parameters =
getParametersParentHierarchy( entry.getValue(), mojoAnnotatedClasses );
parameters = new TreeMap<>( parameters );
for ( Map.Entry<String, ParameterAnnotationContent> parameter : parameters.entrySet() )
{
JavaAnnotatedElement element = elementMap.get( parameter.getKey() );
if ( element == null )
{
continue;
}
JavaClassConverterContext context =
new JavaClassConverterContext( javaClass, ( (JavaMember) element ).getDeclaringClass(),
javaProjectBuilder, mojoAnnotatedClasses,
linkGenerator, element.getLineNumber() );
ParameterAnnotationContent parameterAnnotationContent = parameter.getValue();
parameterAnnotationContent.setDescription(
getDescriptionFromElement( element, context ) );
DocletTag deprecated = element.getTagByName( "deprecated" );
if ( deprecated != null )
{
parameterAnnotationContent.setDeprecated( getRawValueFromTaglet ( deprecated, context ) );
}
DocletTag since = element.getTagByName( "since" );
if ( since != null )
{
parameterAnnotationContent.setSince( getRawValueFromTaglet ( since, context ) );
}
}
// populate components
Map<String, ComponentAnnotationContent> components = entry.getValue().getComponents();
for ( Map.Entry<String, ComponentAnnotationContent> component : components.entrySet() )
{
JavaAnnotatedElement element = elementMap.get( component.getKey() );
if ( element == null )
{
continue;
}
JavaClassConverterContext context =
new JavaClassConverterContext( javaClass, ( (JavaMember) element ).getDeclaringClass(),
javaProjectBuilder, mojoAnnotatedClasses,
linkGenerator, javaClass.getLineNumber() );
ComponentAnnotationContent componentAnnotationContent = component.getValue();
componentAnnotationContent.setDescription(
getDescriptionFromElement( element, context ) );
DocletTag deprecated = element.getTagByName( "deprecated" );
if ( deprecated != null )
{
componentAnnotationContent.setDeprecated( getRawValueFromTaglet ( deprecated, context ) );
}
DocletTag since = element.getTagByName( "since" );
if ( since != null )
{
componentAnnotationContent.setSince( getRawValueFromTaglet ( since, context ) );
}
}
}
}
/**
* Returns the XHTML description from the given element.
* This may refer to either goal, parameter or component.
* @param element the element for which to generate the description
* @param context the context with which to call the converter
* @return the generated description
*/
String getDescriptionFromElement( JavaAnnotatedElement element, JavaClassConverterContext context )
{
String comment = element.getComment();
if ( comment == null )
{
return null;
}
StringBuilder description = new StringBuilder( javadocInlineTagsToHtmlConverter.convert( comment, context ) );
for ( DocletTag docletTag : element.getTags() )
{
// also consider see block tags
if ( "see".equals( docletTag.getName() ) )
{
description.append( javadocBlockTagsToHtmlConverter.convert( docletTag, context ) );
}
}
return description.toString();
}
String getRawValueFromTaglet( DocletTag docletTag, ConverterContext context )
{
// just resolve inline tags and convert to XHTML
return javadocInlineTagsToHtmlConverter.convert( docletTag.getValue(), context );
}
/**
* @param javaClass not null
* @param tagName not null
* @return docletTag instance
*/
private DocletTag findInClassHierarchy( JavaClass javaClass, String tagName )
{
try
{
DocletTag tag = javaClass.getTagByName( tagName );
if ( tag == null )
{
JavaClass superClass = javaClass.getSuperJavaClass();
if ( superClass != null )
{
tag = findInClassHierarchy( superClass, tagName );
}
}
return tag;
}
catch ( NoClassDefFoundError e )
{
getLogger().warn( "Failed extracting tag '" + tagName + "' from class " + javaClass );
throw e;
}
}
/**
* extract fields that are either parameters or components.
* Also extract methods that are parameters
*
* @param javaClass not null
* @return map with Mojo parameters names as keys
*/
private Map<String, JavaAnnotatedElement> extractParameterAnnotations( JavaClass javaClass,
Map<String, JavaClass> javaClassesMap )
{
try
{
Map<String, JavaAnnotatedElement> rawParams = new TreeMap<>();
// we have to add the parent fields first, so that they will be overwritten by the local fields if
// that actually happens...
JavaClass superClass = javaClass.getSuperJavaClass();
if ( superClass != null )
{
if ( !superClass.getFields().isEmpty() || !superClass.getMethods().isEmpty() )
{
rawParams = extractParameterAnnotations( superClass, javaClassesMap );
}
// maybe sources comes from scan of sources artifact
superClass = javaClassesMap.get( superClass.getFullyQualifiedName() );
if ( superClass != null && ( !superClass.getFields().isEmpty() || !superClass.getMethods().isEmpty() ) )
{
rawParams = extractParameterAnnotations( superClass, javaClassesMap );
}
}
else
{
rawParams = new TreeMap<>();
}
for ( JavaField field : javaClass.getFields() )
{
rawParams.put( field.getName(), field );
}
for ( JavaMethod method : javaClass.getMethods() )
{
if ( isPublicSetterMethod( method ) )
{
rawParams.put(
StringUtils.lowercaseFirstLetter( method.getName().substring( 3 ) ), method );
}
}
return rawParams;
}
catch ( NoClassDefFoundError e )
{
getLogger().warn( "Failed extracting parameters from " + javaClass );
throw e;
}
}
private boolean isPublicSetterMethod( JavaMethod method )
{
return method.isPublic()
&& !method.isStatic()
&& method.getName().length() > 3
&& ( method.getName().startsWith( "add" ) || method.getName().startsWith( "set" ) )
&& "void".equals( method.getReturnType().getValue() )
&& method.getParameters().size() == 1;
}
protected Map<String, JavaClass> discoverClasses( JavaProjectBuilder builder )
{
Collection<JavaClass> javaClasses = builder.getClasses();
if ( javaClasses == null || javaClasses.size() < 1 )
{
return Collections.emptyMap();
}
Map<String, JavaClass> javaClassMap = new HashMap<>( javaClasses.size() );
for ( JavaClass javaClass : javaClasses )
{
javaClassMap.put( javaClass.getFullyQualifiedName(), javaClass );
}
return javaClassMap;
}
protected void extendJavaProjectBuilderWithSourcesJar( JavaProjectBuilder builder,
Artifact artifact, PluginToolsRequest request,
String classifier )
throws ExtractionException
{
try
{
Artifact sourcesArtifact =
repositorySystem.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(),
artifact.getVersion(), artifact.getType(), classifier );
ArtifactResolutionRequest req = new ArtifactResolutionRequest();
req.setArtifact( sourcesArtifact );
req.setLocalRepository( request.getLocal() );
req.setRemoteRepositories( request.getRemoteRepos() );
ArtifactResolutionResult res = repositorySystem.resolve( req );
if ( res.hasMissingArtifacts() || res.hasExceptions() )
{
getLogger().warn(
"Unable to get sources artifact for " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getVersion() + ". Some javadoc tags (@since, @deprecated and comments) won't be used" );
return;
}
if ( sourcesArtifact.getFile() == null || !sourcesArtifact.getFile().exists() )
{
// could not get artifact sources
return;
}
// extract sources to target/maven-plugin-plugin-sources/${groupId}/${artifact}/sources
File extractDirectory = new File( request.getProject().getBuild().getDirectory(),
"maven-plugin-plugin-sources/" + sourcesArtifact.getGroupId() + "/"
+ sourcesArtifact.getArtifactId() + "/" + sourcesArtifact.getVersion()
+ "/" + sourcesArtifact.getClassifier() );
extractDirectory.mkdirs();
UnArchiver unArchiver = archiverManager.getUnArchiver( "jar" );
unArchiver.setSourceFile( sourcesArtifact.getFile() );
unArchiver.setDestDirectory( extractDirectory );
unArchiver.extract();
extendJavaProjectBuilder( builder,
Arrays.asList( extractDirectory ),
request.getDependencies() );
}
catch ( ArchiverException | NoSuchArchiverException e )
{
throw new ExtractionException( e.getMessage(), e );
}
}
private void extendJavaProjectBuilder( JavaProjectBuilder builder,
final MavenProject project )
{
List<File> sources = new ArrayList<>();
for ( String source : project.getCompileSourceRoots() )
{
sources.add( new File( source ) );
}
// TODO be more dynamic
File generatedPlugin = new File( project.getBasedir(), "target/generated-sources/plugin" );
if ( !project.getCompileSourceRoots().contains( generatedPlugin.getAbsolutePath() )
&& generatedPlugin.exists() )
{
sources.add( generatedPlugin );
}
extendJavaProjectBuilder( builder, sources, project.getArtifacts() );
}
private void extendJavaProjectBuilder( JavaProjectBuilder builder,
List<File> sourceDirectories,
Set<Artifact> artifacts )
{
// Build isolated Classloader with only the artifacts of the project (none of this plugin)
List<URL> urls = new ArrayList<>( artifacts.size() );
for ( Artifact artifact : artifacts )
{
try
{
urls.add( artifact.getFile().toURI().toURL() );
}
catch ( MalformedURLException e )
{
// noop
}
}
builder.addClassLoader( new URLClassLoader( urls.toArray( new URL[0] ), ClassLoader.getSystemClassLoader() ) );
for ( File source : sourceDirectories )
{
builder.addSourceTree( source );
}
}
private List<MojoDescriptor> toMojoDescriptors( Map<String, MojoAnnotatedClass> mojoAnnotatedClasses,
PluginDescriptor pluginDescriptor )
throws DuplicateParameterException, InvalidParameterException
{
List<MojoDescriptor> mojoDescriptors = new ArrayList<>( mojoAnnotatedClasses.size() );
for ( MojoAnnotatedClass mojoAnnotatedClass : mojoAnnotatedClasses.values() )
{
// no mojo so skip it
if ( mojoAnnotatedClass.getMojo() == null )
{
continue;
}
ExtendedMojoDescriptor mojoDescriptor = new ExtendedMojoDescriptor( true );
//mojoDescriptor.setRole( mojoAnnotatedClass.getClassName() );
//mojoDescriptor.setRoleHint( "default" );
mojoDescriptor.setImplementation( mojoAnnotatedClass.getClassName() );
mojoDescriptor.setLanguage( "java" );
MojoAnnotationContent mojo = mojoAnnotatedClass.getMojo();
mojoDescriptor.setDescription( mojo.getDescription() );
mojoDescriptor.setSince( mojo.getSince() );
mojo.setDeprecated( mojo.getDeprecated() );
mojoDescriptor.setProjectRequired( mojo.requiresProject() );
mojoDescriptor.setRequiresReports( mojo.requiresReports() );
mojoDescriptor.setComponentConfigurator( mojo.configurator() );
mojoDescriptor.setInheritedByDefault( mojo.inheritByDefault() );
mojoDescriptor.setInstantiationStrategy( mojo.instantiationStrategy().id() );
mojoDescriptor.setAggregator( mojo.aggregator() );
mojoDescriptor.setDependencyResolutionRequired( mojo.requiresDependencyResolution().id() );
mojoDescriptor.setDependencyCollectionRequired( mojo.requiresDependencyCollection().id() );
mojoDescriptor.setDirectInvocationOnly( mojo.requiresDirectInvocation() );
mojoDescriptor.setDeprecated( mojo.getDeprecated() );
mojoDescriptor.setThreadSafe( mojo.threadSafe() );
ExecuteAnnotationContent execute = findExecuteInParentHierarchy( mojoAnnotatedClass, mojoAnnotatedClasses );
if ( execute != null )
{
mojoDescriptor.setExecuteGoal( execute.goal() );
mojoDescriptor.setExecuteLifecycle( execute.lifecycle() );
if ( execute.phase() != null )
{
mojoDescriptor.setExecutePhase( execute.phase().id() );
}
}
mojoDescriptor.setExecutionStrategy( mojo.executionStrategy() );
// ???
//mojoDescriptor.alwaysExecute(mojo.a)
mojoDescriptor.setGoal( mojo.name() );
mojoDescriptor.setOnlineRequired( mojo.requiresOnline() );
mojoDescriptor.setPhase( mojo.defaultPhase().id() );
// Parameter annotations
Map<String, ParameterAnnotationContent> parameters =
getParametersParentHierarchy( mojoAnnotatedClass, mojoAnnotatedClasses );
for ( ParameterAnnotationContent parameterAnnotationContent : new TreeSet<>( parameters.values() ) )
{
org.apache.maven.plugin.descriptor.Parameter parameter =
new org.apache.maven.plugin.descriptor.Parameter();
String name =
StringUtils.isEmpty( parameterAnnotationContent.name() ) ? parameterAnnotationContent.getFieldName()
: parameterAnnotationContent.name();
parameter.setName( name );
parameter.setAlias( parameterAnnotationContent.alias() );
parameter.setDefaultValue( parameterAnnotationContent.defaultValue() );
parameter.setImplementation( parameterAnnotationContent.getImplementationClassName() );
parameter.setDeprecated( parameterAnnotationContent.getDeprecated() );
parameter.setDescription( parameterAnnotationContent.getDescription() );
parameter.setEditable( !parameterAnnotationContent.readonly() );
String property = parameterAnnotationContent.property();
if ( StringUtils.contains( property, '$' ) || StringUtils.contains( property, '{' )
|| StringUtils.contains( property, '}' ) )
{
throw new InvalidParameterException(
"Invalid property for parameter '" + parameter.getName() + "', " + "forbidden characters ${}: "
+ property, null );
}
parameter.setExpression( StringUtils.isEmpty( property ) ? "" : "${" + property + "}" );
StringBuilder type = new StringBuilder( parameterAnnotationContent.getClassName() );
if ( !parameterAnnotationContent.getTypeParameters().isEmpty() )
{
type.append( parameterAnnotationContent.getTypeParameters().stream()
.collect( Collectors.joining( ", ", "<", ">" ) ) );
}
parameter.setType( type.toString() );
parameter.setSince( parameterAnnotationContent.getSince() );
parameter.setRequired( parameterAnnotationContent.required() );
mojoDescriptor.addParameter( parameter );
}
// Component annotations
Map<String, ComponentAnnotationContent> components =
getComponentsParentHierarchy( mojoAnnotatedClass, mojoAnnotatedClasses );
for ( ComponentAnnotationContent componentAnnotationContent : new TreeSet<>( components.values() ) )
{
org.apache.maven.plugin.descriptor.Parameter parameter =
new org.apache.maven.plugin.descriptor.Parameter();
parameter.setName( componentAnnotationContent.getFieldName() );
// recognize Maven-injected objects as components annotations instead of parameters
String expression = PluginUtils.MAVEN_COMPONENTS.get( componentAnnotationContent.getRoleClassName() );
if ( expression == null )
{
// normal component
parameter.setRequirement( new Requirement( componentAnnotationContent.getRoleClassName(),
componentAnnotationContent.hint() ) );
}
else
{
// not a component but a Maven object to be transformed into an expression/property: deprecated
getLogger().warn( "Deprecated @Component annotation for '" + parameter.getName() + "' field in "
+ mojoAnnotatedClass.getClassName()
+ ": replace with @Parameter( defaultValue = \"" + expression
+ "\", readonly = true )" );
parameter.setDefaultValue( expression );
parameter.setType( componentAnnotationContent.getRoleClassName() );
parameter.setRequired( true );
}
parameter.setDeprecated( componentAnnotationContent.getDeprecated() );
parameter.setSince( componentAnnotationContent.getSince() );
// same behaviour as JavaMojoDescriptorExtractor
//parameter.setRequired( ... );
parameter.setEditable( false );
mojoDescriptor.addParameter( parameter );
}
mojoDescriptor.setPluginDescriptor( pluginDescriptor );
mojoDescriptors.add( mojoDescriptor );
}
return mojoDescriptors;
}
protected ExecuteAnnotationContent findExecuteInParentHierarchy( MojoAnnotatedClass mojoAnnotatedClass,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
if ( mojoAnnotatedClass.getExecute() != null )
{
return mojoAnnotatedClass.getExecute();
}
String parentClassName = mojoAnnotatedClass.getParentClassName();
if ( StringUtils.isEmpty( parentClassName ) )
{
return null;
}
MojoAnnotatedClass parent = mojoAnnotatedClasses.get( parentClassName );
if ( parent == null )
{
return null;
}
return findExecuteInParentHierarchy( parent, mojoAnnotatedClasses );
}
protected Map<String, ParameterAnnotationContent> getParametersParentHierarchy(
MojoAnnotatedClass mojoAnnotatedClass,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
List<ParameterAnnotationContent> parameterAnnotationContents = new ArrayList<>();
parameterAnnotationContents =
getParametersParent( mojoAnnotatedClass, parameterAnnotationContents, mojoAnnotatedClasses );
// move to parent first to build the Map
Collections.reverse( parameterAnnotationContents );
Map<String, ParameterAnnotationContent> map = new HashMap<>( parameterAnnotationContents.size() );
for ( ParameterAnnotationContent parameterAnnotationContent : parameterAnnotationContents )
{
map.put( parameterAnnotationContent.getFieldName(), parameterAnnotationContent );
}
return map;
}
protected List<ParameterAnnotationContent> getParametersParent( MojoAnnotatedClass mojoAnnotatedClass,
List<ParameterAnnotationContent> parameterAnnotationContents,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
parameterAnnotationContents.addAll( mojoAnnotatedClass.getParameters().values() );
String parentClassName = mojoAnnotatedClass.getParentClassName();
if ( parentClassName != null )
{
MojoAnnotatedClass parent = mojoAnnotatedClasses.get( parentClassName );
if ( parent != null )
{
return getParametersParent( parent, parameterAnnotationContents, mojoAnnotatedClasses );
}
}
return parameterAnnotationContents;
}
protected Map<String, ComponentAnnotationContent> getComponentsParentHierarchy(
MojoAnnotatedClass mojoAnnotatedClass,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
List<ComponentAnnotationContent> componentAnnotationContents = new ArrayList<>();
componentAnnotationContents =
getComponentParent( mojoAnnotatedClass, componentAnnotationContents, mojoAnnotatedClasses );
// move to parent first to build the Map
Collections.reverse( componentAnnotationContents );
Map<String, ComponentAnnotationContent> map = new HashMap<>( componentAnnotationContents.size() );
for ( ComponentAnnotationContent componentAnnotationContent : componentAnnotationContents )
{
map.put( componentAnnotationContent.getFieldName(), componentAnnotationContent );
}
return map;
}
protected List<ComponentAnnotationContent> getComponentParent( MojoAnnotatedClass mojoAnnotatedClass,
List<ComponentAnnotationContent> componentAnnotationContents,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
componentAnnotationContents.addAll( mojoAnnotatedClass.getComponents().values() );
String parentClassName = mojoAnnotatedClass.getParentClassName();
if ( parentClassName != null )
{
MojoAnnotatedClass parent = mojoAnnotatedClasses.get( parentClassName );
if ( parent != null )
{
return getComponentParent( parent, componentAnnotationContents, mojoAnnotatedClasses );
}
}
return componentAnnotationContents;
}
protected MavenProject getFromProjectReferences( Artifact artifact, MavenProject project )
{
if ( project.getProjectReferences() == null || project.getProjectReferences().isEmpty() )
{
return null;
}
Collection<MavenProject> mavenProjects = project.getProjectReferences().values();
for ( MavenProject mavenProject : mavenProjects )
{
if ( Objects.equals( mavenProject.getId(), artifact.getId() ) )
{
return mavenProject;
}
}
return null;
}
}