/
JavadocUtil.java
1855 lines (1668 loc) · 66.7 KB
/
JavadocUtil.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.apache.maven.plugins.javadoc;
/*
* 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 org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import org.apache.maven.settings.Proxy;
import org.apache.maven.settings.Settings;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationOutputHandler;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.InvocationResult;
import org.apache.maven.shared.invoker.Invoker;
import org.apache.maven.shared.invoker.MavenInvocationException;
import org.apache.maven.shared.invoker.PrintStreamHandler;
import org.apache.maven.wagon.proxy.ProxyInfo;
import org.apache.maven.wagon.proxy.ProxyUtils;
import org.codehaus.plexus.languages.java.version.JavaVersion;
import org.codehaus.plexus.util.DirectoryScanner;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.IOUtil;
import org.codehaus.plexus.util.Os;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.cli.CommandLineException;
import org.codehaus.plexus.util.cli.CommandLineUtils;
import org.codehaus.plexus.util.cli.Commandline;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Modifier;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* Set of utilities methods for Javadoc.
*
* @author <a href="mailto:vincent.siveton@gmail.com">Vincent Siveton</a>
* @since 2.4
*/
public class JavadocUtil
{
/** The default timeout used when fetching url, i.e. 2000. */
public static final int DEFAULT_TIMEOUT = 2000;
/** Error message when VM could not be started using invoker. */
protected static final String ERROR_INIT_VM =
"Error occurred during initialization of VM, try to reduce the Java heap size for the MAVEN_OPTS "
+ "environment variable using -Xms:<size> and -Xmx:<size>.";
/**
* Method that removes the invalid directories in the specified directories. <b>Note</b>: All elements in
* <code>dirs</code> could be an absolute or relative against the project's base directory <code>String</code> path.
*
* @param project the current Maven project not null
* @param dirs the collection of <code>String</code> directories path that will be validated.
* @return a List of valid <code>String</code> directories absolute paths.
*/
public static Collection<Path> pruneDirs( MavenProject project, Collection<String> dirs )
{
final Path projectBasedir = project.getBasedir().toPath();
Set<Path> pruned = new LinkedHashSet<>( dirs.size() );
for ( String dir : dirs )
{
if ( dir == null )
{
continue;
}
Path directory = projectBasedir.resolve( dir );
if ( Files.isDirectory( directory ) )
{
pruned.add( directory.toAbsolutePath() );
}
}
return pruned;
}
/**
* Method that removes the invalid files in the specified files. <b>Note</b>: All elements in <code>files</code>
* should be an absolute <code>String</code> path.
*
* @param files the list of <code>String</code> files paths that will be validated.
* @return a List of valid <code>File</code> objects.
*/
protected static List<String> pruneFiles( Collection<String> files )
{
List<String> pruned = new ArrayList<>( files.size() );
for ( String f : files )
{
if ( !shouldPruneFile( f, pruned ) )
{
pruned.add( f );
}
}
return pruned;
}
/**
* Determine whether a file should be excluded from the provided list of paths, based on whether it exists and is
* already present in the list.
*
* @param f The files.
* @param pruned The list of pruned files..
* @return true if the file could be pruned false otherwise.
*/
public static boolean shouldPruneFile( String f, List<String> pruned )
{
if ( f != null )
{
File file = new File( f );
if ( file.isFile() && ( isEmpty( pruned ) || !pruned.contains( f ) ) )
{
return false;
}
}
return true;
}
/**
* Method that gets all the source files to be excluded from the javadoc on the given source paths.
*
* @param sourcePaths the path to the source files
* @param excludedPackages the package names to be excluded in the javadoc
* @return a List of the packages to be excluded in the generated javadoc
*/
protected static List<String> getExcludedPackages( Collection<Path> sourcePaths,
Collection<String> excludedPackages )
{
List<String> excludedNames = new ArrayList<>();
for ( Path sourcePath : sourcePaths )
{
excludedNames.addAll( getExcludedPackages( sourcePath, excludedPackages ) );
}
return excludedNames;
}
/**
* Convenience method to wrap an argument value in single quotes (i.e. <code>'</code>). Intended for values which
* may contain whitespaces. <br>
* To prevent javadoc error, the line separator (i.e. <code>\n</code>) are skipped.
*
* @param value the argument value.
* @return argument with quote
*/
protected static String quotedArgument( String value )
{
String arg = value;
if ( StringUtils.isNotEmpty( arg ) )
{
if ( arg.contains( "'" ) )
{
arg = StringUtils.replace( arg, "'", "\\'" );
}
arg = "'" + arg + "'";
// To prevent javadoc error
arg = StringUtils.replace( arg, "\n", " " );
}
return arg;
}
/**
* Convenience method to format a path argument so that it is properly interpreted by the javadoc tool. Intended for
* path values which may contain whitespaces.
*
* @param value the argument value.
* @return path argument with quote
*/
protected static String quotedPathArgument( String value )
{
String path = value;
if ( StringUtils.isNotEmpty( path ) )
{
path = path.replace( '\\', '/' );
if ( path.contains( "\'" ) )
{
String split[] = path.split( "\'" );
path = "";
for ( int i = 0; i < split.length; i++ )
{
if ( i != split.length - 1 )
{
path = path + split[i] + "\\'";
}
else
{
path = path + split[i];
}
}
}
path = "'" + path + "'";
}
return path;
}
/**
* Convenience method that copy all <code>doc-files</code> directories from <code>javadocDir</code> to the
* <code>outputDirectory</code>.
*
* @param outputDirectory the output directory
* @param javadocDir the javadoc directory
* @param excludedocfilessubdir the excludedocfilessubdir parameter
* @throws IOException if any
* @since 2.5
*/
protected static void copyJavadocResources( File outputDirectory, File javadocDir, String excludedocfilessubdir )
throws IOException
{
if ( !javadocDir.isDirectory() )
{
return;
}
List<String> excludes = new ArrayList<>( Arrays.asList( FileUtils.getDefaultExcludes() ) );
if ( StringUtils.isNotEmpty( excludedocfilessubdir ) )
{
StringTokenizer st = new StringTokenizer( excludedocfilessubdir, ":" );
String current;
while ( st.hasMoreTokens() )
{
current = st.nextToken();
excludes.add( "**/" + current + "/**" );
}
}
List<String> docFiles =
FileUtils.getDirectoryNames( javadocDir, "resources,**/doc-files",
StringUtils.join( excludes.iterator(), "," ), false, true );
for ( String docFile : docFiles )
{
File docFileOutput = new File( outputDirectory, docFile );
FileUtils.mkdir( docFileOutput.getAbsolutePath() );
FileUtils.copyDirectoryStructure( new File( javadocDir, docFile ), docFileOutput );
List<String> files =
FileUtils.getFileAndDirectoryNames( docFileOutput, StringUtils.join( excludes.iterator(), "," ), null,
true, true, true, true );
for ( String filename : files )
{
File file = new File( filename );
if ( file.isDirectory() )
{
FileUtils.deleteDirectory( file );
}
else
{
file.delete();
}
}
}
}
/**
* Method that gets the files or classes that would be included in the javadocs using the subpackages parameter.
*
* @param sourceDirectory the directory where the source files are located
* @param fileList the list of all relative files found in the sourceDirectory
* @param excludePackages package names to be excluded in the javadoc
* @return a StringBuilder that contains the appended file names of the files to be included in the javadoc
*/
protected static List<String> getIncludedFiles( File sourceDirectory, String[] fileList,
Collection<String> excludePackages )
{
List<String> files = new ArrayList<>();
List<Pattern> excludePackagePatterns = new ArrayList<>( excludePackages.size() );
for ( String excludePackage : excludePackages )
{
excludePackagePatterns.add( Pattern.compile( excludePackage.replace( '.', File.separatorChar )
.replace( "\\", "\\\\" )
.replace( "*", ".+" )
.concat( "[\\\\/][^\\\\/]+\\.java" )
) );
}
for ( String file : fileList )
{
boolean excluded = false;
for ( Pattern excludePackagePattern : excludePackagePatterns )
{
if ( excludePackagePattern.matcher( file ).matches() )
{
excluded = true;
break;
}
}
if ( !excluded )
{
files.add( file );
}
}
return files;
}
/**
* Method that gets the complete package names (including subpackages) of the packages that were defined in the
* excludePackageNames parameter.
*
* @param sourceDirectory the directory where the source files are located
* @param excludePackagenames package names to be excluded in the javadoc
* @return a List of the packagenames to be excluded
*/
protected static Collection<String> getExcludedPackages( final Path sourceDirectory,
Collection<String> excludePackagenames )
{
final String regexFileSeparator = File.separator.replace( "\\", "\\\\" );
final Collection<String> fileList = new ArrayList<>();
try
{
Files.walkFileTree( sourceDirectory, new SimpleFileVisitor<Path>()
{
@Override
public FileVisitResult visitFile( Path file, BasicFileAttributes attrs )
throws IOException
{
if ( file.getFileName().toString().endsWith( ".java" ) )
{
fileList.add( sourceDirectory.relativize( file.getParent() ).toString() );
}
return FileVisitResult.CONTINUE;
}
} );
}
catch ( IOException e )
{
// noop
}
List<String> files = new ArrayList<>();
for ( String excludePackagename : excludePackagenames )
{
// Usage of wildcard was bad specified and bad implemented, i.e. using String.contains()
// without respecting surrounding context
// Following implementation should match requirements as defined in the examples:
// - A wildcard at the beginning should match 1 or more folders
// - Any other wildcard must match exactly one folder
Pattern p = Pattern.compile( excludePackagename.replace( ".", regexFileSeparator )
.replaceFirst( "^\\*", ".+" )
.replace( "*", "[^" + regexFileSeparator + "]+" ) );
for ( String aFileList : fileList )
{
if ( p.matcher( aFileList ).matches() )
{
files.add( aFileList.replace( File.separatorChar, '.' ) );
}
}
}
return files;
}
/**
* Convenience method that gets the files to be included in the javadoc.
*
* @param sourceDirectory the directory where the source files are located
* @param excludePackages the packages to be excluded in the javadocs
* @param sourceFileIncludes files to include.
* @param sourceFileExcludes files to exclude.
*/
protected static List<String> getFilesFromSource( File sourceDirectory, List<String> sourceFileIncludes,
List<String> sourceFileExcludes,
Collection<String> excludePackages )
{
DirectoryScanner ds = new DirectoryScanner();
if ( sourceFileIncludes == null )
{
sourceFileIncludes = Collections.singletonList( "**/*.java" );
}
ds.setIncludes( sourceFileIncludes.toArray( new String[sourceFileIncludes.size()] ) );
if ( sourceFileExcludes != null && sourceFileExcludes.size() > 0 )
{
ds.setExcludes( sourceFileExcludes.toArray( new String[sourceFileExcludes.size()] ) );
}
ds.setBasedir( sourceDirectory );
ds.scan();
String[] fileList = ds.getIncludedFiles();
List<String> files = new ArrayList<>();
if ( fileList.length != 0 )
{
for ( String includedFile : getIncludedFiles( sourceDirectory, fileList, excludePackages ) )
{
files.add( includedFile );
}
}
return files;
}
/**
* Call the Javadoc tool and parse its output to find its version, i.e.:
*
* <pre>
* javadoc.exe( or.sh ) - J - version
* </pre>
*
* @param javadocExe not null file
* @return the javadoc version as float
* @throws IOException if javadocExe is null, doesn't exist or is not a file
* @throws CommandLineException if any
* @throws IllegalArgumentException if no output was found in the command line
* @throws PatternSyntaxException if the output contains a syntax error in the regular-expression pattern.
* @see #extractJavadocVersion(String)
*/
protected static JavaVersion getJavadocVersion( File javadocExe )
throws IOException, CommandLineException, IllegalArgumentException
{
if ( ( javadocExe == null ) || ( !javadocExe.exists() ) || ( !javadocExe.isFile() ) )
{
throw new IOException( "The javadoc executable '" + javadocExe + "' doesn't exist or is not a file. " );
}
Commandline cmd = new Commandline();
cmd.setExecutable( javadocExe.getAbsolutePath() );
cmd.setWorkingDirectory( javadocExe.getParentFile() );
cmd.createArg().setValue( "-J-version" );
CommandLineUtils.StringStreamConsumer out = new JavadocOutputStreamConsumer();
CommandLineUtils.StringStreamConsumer err = new JavadocOutputStreamConsumer();
int exitCode = CommandLineUtils.executeCommandLine( cmd, out, err );
if ( exitCode != 0 )
{
StringBuilder msg = new StringBuilder( "Exit code: " + exitCode + " - " + err.getOutput() );
msg.append( '\n' );
msg.append( "Command line was:" + CommandLineUtils.toString( cmd.getCommandline() ) );
throw new CommandLineException( msg.toString() );
}
if ( StringUtils.isNotEmpty( err.getOutput() ) )
{
return JavaVersion.parse( extractJavadocVersion( err.getOutput() ) );
}
else if ( StringUtils.isNotEmpty( out.getOutput() ) )
{
return JavaVersion.parse( extractJavadocVersion( out.getOutput() ) );
}
throw new IllegalArgumentException( "No output found from the command line 'javadoc -J-version'" );
}
/**
* Parse the output for 'javadoc -J-version' and return the javadoc version recognized. <br>
* Here are some output for 'javadoc -J-version' depending the JDK used:
* <table summary="Output for 'javadoc -J-version' per JDK">
* <tr>
* <th>JDK</th>
* <th>Output for 'javadoc -J-version'</th>
* </tr>
* <tr>
* <td>Sun 1.4</td>
* <td>java full version "1.4.2_12-b03"</td>
* </tr>
* <tr>
* <td>Sun 1.5</td>
* <td>java full version "1.5.0_07-164"</td>
* </tr>
* <tr>
* <td>IBM 1.4</td>
* <td>javadoc full version "J2RE 1.4.2 IBM Windows 32 build cn1420-20040626"</td>
* </tr>
* <tr>
* <td>IBM 1.5 (French JVM)</td>
* <td>javadoc version complète de "J2RE 1.5.0 IBM Windows 32 build pwi32pdev-20070426a"</td>
* </tr>
* <tr>
* <td>FreeBSD 1.5</td>
* <td>java full version "diablo-1.5.0-b01"</td>
* </tr>
* <tr>
* <td>BEA jrockit 1.5</td>
* <td>java full version "1.5.0_11-b03"</td>
* </tr>
* </table>
*
* @param output for 'javadoc -J-version'
* @return the version of the javadoc for the output, only digits and dots
* @throws PatternSyntaxException if the output doesn't match with the output pattern
* <tt>(?s).*?[^a-zA-Z]([0-9]+\\.?[0-9]*)(\\.([0-9]+))?.*</tt>.
* @throws IllegalArgumentException if the output is null
*/
protected static String extractJavadocVersion( String output )
throws IllegalArgumentException
{
if ( StringUtils.isEmpty( output ) )
{
throw new IllegalArgumentException( "The output could not be null." );
}
Pattern pattern = Pattern.compile( "(?s).*?[^a-zA-Z](([0-9]+\\.?[0-9]*)(\\.[0-9]+)?).*" );
Matcher matcher = pattern.matcher( output );
if ( !matcher.matches() )
{
throw new PatternSyntaxException( "Unrecognized version of Javadoc: '" + output + "'", pattern.pattern(),
pattern.toString().length() - 1 );
}
return matcher.group( 1 );
}
/**
* Parse a memory string which be used in the JVM arguments <code>-Xms</code> or <code>-Xmx</code>. <br>
* Here are some supported memory string depending the JDK used:
* <table summary="Memory argument support per JDK">
* <tr>
* <th>JDK</th>
* <th>Memory argument support for <code>-Xms</code> or <code>-Xmx</code></th>
* </tr>
* <tr>
* <td>SUN</td>
* <td>1024k | 128m | 1g | 1t</td>
* </tr>
* <tr>
* <td>IBM</td>
* <td>1024k | 1024b | 128m | 128mb | 1g | 1gb</td>
* </tr>
* <tr>
* <td>BEA</td>
* <td>1024k | 1024kb | 128m | 128mb | 1g | 1gb</td>
* </tr>
* </table>
*
* @param memory the memory to be parsed, not null.
* @return the memory parsed with a supported unit. If no unit specified in the <code>memory</code> parameter, the
* default unit is <code>m</code>. The units <code>g | gb</code> or <code>t | tb</code> will be converted in
* <code>m</code>.
* @throws IllegalArgumentException if the <code>memory</code> parameter is null or doesn't match any pattern.
*/
protected static String parseJavadocMemory( String memory )
throws IllegalArgumentException
{
if ( StringUtils.isEmpty( memory ) )
{
throw new IllegalArgumentException( "The memory could not be null." );
}
Pattern p = Pattern.compile( "^\\s*(\\d+)\\s*?\\s*$" );
Matcher m = p.matcher( memory );
if ( m.matches() )
{
return m.group( 1 ) + "m";
}
p = Pattern.compile( "^\\s*(\\d+)\\s*k(b)?\\s*$", Pattern.CASE_INSENSITIVE );
m = p.matcher( memory );
if ( m.matches() )
{
return m.group( 1 ) + "k";
}
p = Pattern.compile( "^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE );
m = p.matcher( memory );
if ( m.matches() )
{
return m.group( 1 ) + "m";
}
p = Pattern.compile( "^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE );
m = p.matcher( memory );
if ( m.matches() )
{
return ( Integer.parseInt( m.group( 1 ) ) * 1024 ) + "m";
}
p = Pattern.compile( "^\\s*(\\d+)\\s*t(b)?\\s*$", Pattern.CASE_INSENSITIVE );
m = p.matcher( memory );
if ( m.matches() )
{
return ( Integer.parseInt( m.group( 1 ) ) * 1024 * 1024 ) + "m";
}
throw new IllegalArgumentException( "Could convert not to a memory size: " + memory );
}
/**
* Validate if a charset is supported on this platform.
*
* @param charsetName the charsetName to be check.
* @return <code>true</code> if the given charset is supported by the JVM, <code>false</code> otherwise.
*/
protected static boolean validateEncoding( String charsetName )
{
if ( StringUtils.isEmpty( charsetName ) )
{
return false;
}
try
{
return Charset.isSupported( charsetName );
}
catch ( IllegalCharsetNameException e )
{
return false;
}
}
/**
* For security reasons, if an active proxy is defined and needs an authentication by username/password, hide the
* proxy password in the command line.
*
* @param cmdLine a command line, not null
* @param settings the user settings
* @return the cmdline with '*' for the http.proxyPassword JVM property
*/
protected static String hideProxyPassword( String cmdLine, Settings settings )
{
if ( cmdLine == null )
{
throw new IllegalArgumentException( "cmdLine could not be null" );
}
if ( settings == null )
{
return cmdLine;
}
Proxy activeProxy = settings.getActiveProxy();
if ( activeProxy != null && StringUtils.isNotEmpty( activeProxy.getHost() )
&& StringUtils.isNotEmpty( activeProxy.getUsername() )
&& StringUtils.isNotEmpty( activeProxy.getPassword() ) )
{
String pass = "-J-Dhttp.proxyPassword=\"" + activeProxy.getPassword() + "\"";
String hidepass =
"-J-Dhttp.proxyPassword=\"" + StringUtils.repeat( "*", activeProxy.getPassword().length() ) + "\"";
return StringUtils.replace( cmdLine, pass, hidepass );
}
return cmdLine;
}
/**
* Auto-detect the class names of the implementation of <code>com.sun.tools.doclets.Taglet</code> class from a given
* jar file. <br>
* <b>Note</b>: <code>JAVA_HOME/lib/tools.jar</code> is a requirement to find
* <code>com.sun.tools.doclets.Taglet</code> class.
*
* @param jarFile not null
* @return the list of <code>com.sun.tools.doclets.Taglet</code> class names from a given jarFile.
* @throws IOException if jarFile is invalid or not found, or if the <code>JAVA_HOME/lib/tools.jar</code> is not
* found.
* @throws ClassNotFoundException if any
* @throws NoClassDefFoundError if any
*/
protected static List<String> getTagletClassNames( File jarFile )
throws IOException, ClassNotFoundException, NoClassDefFoundError
{
List<String> classes = getClassNamesFromJar( jarFile );
ClassLoader cl;
// Needed to find com.sun.tools.doclets.Taglet class
File tools = new File( System.getProperty( "java.home" ), "../lib/tools.jar" );
if ( tools.exists() && tools.isFile() )
{
cl = new URLClassLoader( new URL[] { jarFile.toURI().toURL(), tools.toURI().toURL() }, null );
}
else
{
cl = new URLClassLoader( new URL[] { jarFile.toURI().toURL() }, ClassLoader.getSystemClassLoader() );
}
List<String> tagletClasses = new ArrayList<>();
Class<?> tagletClass;
try
{
tagletClass = cl.loadClass( "com.sun.tools.doclets.Taglet" );
}
catch ( ClassNotFoundException e )
{
tagletClass = cl.loadClass( "jdk.javadoc.doclet.Taglet" );
}
for ( String s : classes )
{
Class<?> c = cl.loadClass( s );
if ( tagletClass.isAssignableFrom( c ) && !Modifier.isAbstract( c.getModifiers() ) )
{
tagletClasses.add( c.getName() );
}
}
return tagletClasses;
}
/**
* Copy the given url to the given file.
*
* @param url not null url
* @param file not null file where the url will be created
* @throws IOException if any
* @since 2.6
*/
protected static void copyResource( URL url, File file )
throws IOException
{
if ( file == null )
{
throw new IOException( "The file can't be null." );
}
if ( url == null )
{
throw new IOException( "The url could not be null." );
}
FileUtils.copyURLToFile( url, file );
}
/**
* Invoke Maven for the given project file with a list of goals and properties, the output will be in the invokerlog
* file. <br>
* <b>Note</b>: the Maven Home should be defined in the <code>maven.home</code> Java system property or defined in
* <code>M2_HOME</code> system env variables.
*
* @param log a logger could be null.
* @param localRepositoryDir the localRepository not null.
* @param projectFile a not null project file.
* @param goals a not null goals list.
* @param properties the properties for the goals, could be null.
* @param invokerLog the log file where the invoker will be written, if null using <code>System.out</code>.
* @throws MavenInvocationException if any
* @since 2.6
*/
protected static void invokeMaven( Log log, File localRepositoryDir, File projectFile, List<String> goals,
Properties properties, File invokerLog )
throws MavenInvocationException
{
if ( projectFile == null )
{
throw new IllegalArgumentException( "projectFile should be not null." );
}
if ( !projectFile.isFile() )
{
throw new IllegalArgumentException( projectFile.getAbsolutePath() + " is not a file." );
}
if ( goals == null || goals.size() == 0 )
{
throw new IllegalArgumentException( "goals should be not empty." );
}
if ( localRepositoryDir == null || !localRepositoryDir.isDirectory() )
{
throw new IllegalArgumentException( "localRepositoryDir '" + localRepositoryDir
+ "' should be a directory." );
}
String mavenHome = getMavenHome( log );
if ( StringUtils.isEmpty( mavenHome ) )
{
String msg = "Could NOT invoke Maven because no Maven Home is defined. You need to have set the M2_HOME "
+ "system env variable or a maven.home Java system properties.";
if ( log != null )
{
log.error( msg );
}
else
{
System.err.println( msg );
}
return;
}
Invoker invoker = new DefaultInvoker();
invoker.setMavenHome( new File( mavenHome ) );
invoker.setLocalRepositoryDirectory( localRepositoryDir );
InvocationRequest request = new DefaultInvocationRequest();
request.setBaseDirectory( projectFile.getParentFile() );
request.setPomFile( projectFile );
request.setBatchMode( true );
if ( log != null )
{
request.setDebug( log.isDebugEnabled() );
}
else
{
request.setDebug( true );
}
request.setGoals( goals );
if ( properties != null )
{
request.setProperties( properties );
}
File javaHome = getJavaHome( log );
if ( javaHome != null )
{
request.setJavaHome( javaHome );
}
if ( log != null && log.isDebugEnabled() )
{
log.debug( "Invoking Maven for the goals: " + goals + " with "
+ ( properties == null ? "no properties" : "properties=" + properties ) );
}
InvocationResult result = invoke( log, invoker, request, invokerLog, goals, properties, null );
if ( result.getExitCode() != 0 )
{
String invokerLogContent = readFile( invokerLog, "UTF-8" );
// see DefaultMaven
if ( invokerLogContent != null && ( !invokerLogContent.contains( "Scanning for projects..." )
|| invokerLogContent.contains( OutOfMemoryError.class.getName() ) ) )
{
if ( log != null )
{
log.error( "Error occurred during initialization of VM, trying to use an empty MAVEN_OPTS..." );
if ( log.isDebugEnabled() )
{
log.debug( "Reinvoking Maven for the goals: " + goals + " with an empty MAVEN_OPTS..." );
}
}
result = invoke( log, invoker, request, invokerLog, goals, properties, "" );
}
}
if ( result.getExitCode() != 0 )
{
String invokerLogContent = readFile( invokerLog, "UTF-8" );
// see DefaultMaven
if ( invokerLogContent != null && ( !invokerLogContent.contains( "Scanning for projects..." )
|| invokerLogContent.contains( OutOfMemoryError.class.getName() ) ) )
{
throw new MavenInvocationException( ERROR_INIT_VM );
}
throw new MavenInvocationException( "Error when invoking Maven, consult the invoker log file: "
+ invokerLog.getAbsolutePath() );
}
}
/**
* Read the given file and return the content or null if an IOException occurs.
*
* @param javaFile not null
* @param encoding could be null
* @return the content with unified line separator of the given javaFile using the given encoding.
* @see FileUtils#fileRead(File, String)
* @since 2.6.1
*/
protected static String readFile( final File javaFile, final String encoding )
{
try
{
return FileUtils.fileRead( javaFile, encoding );
}
catch ( IOException e )
{
return null;
}
}
/**
* Split the given path with colon and semi-colon, to support Solaris and Windows path. Examples:
*
* <pre>
* splitPath( "/home:/tmp" ) = ["/home", "/tmp"]
* splitPath( "/home;/tmp" ) = ["/home", "/tmp"]
* splitPath( "C:/home:C:/tmp" ) = ["C:/home", "C:/tmp"]
* splitPath( "C:/home;C:/tmp" ) = ["C:/home", "C:/tmp"]
* </pre>
*
* @param path which can contain multiple paths separated with a colon (<code>:</code>) or a semi-colon
* (<code>;</code>), platform independent. Could be null.
* @return the path splitted by colon or semi-colon or <code>null</code> if path was <code>null</code>.
* @since 2.6.1
*/
protected static String[] splitPath( final String path )
{
if ( path == null )
{
return null;
}
List<String> subpaths = new ArrayList<>();
PathTokenizer pathTokenizer = new PathTokenizer( path );
while ( pathTokenizer.hasMoreTokens() )
{
subpaths.add( pathTokenizer.nextToken() );
}
return subpaths.toArray( new String[subpaths.size()] );
}
/**
* Unify the given path with the current System path separator, to be platform independent. Examples:
*
* <pre>
* unifyPathSeparator( "/home:/tmp" ) = "/home:/tmp" (Solaris box)
* unifyPathSeparator( "/home:/tmp" ) = "/home;/tmp" (Windows box)
* </pre>
*
* @param path which can contain multiple paths by separating them with a colon (<code>:</code>) or a semi-colon
* (<code>;</code>), platform independent. Could be null.
* @return the same path but separated with the current System path separator or <code>null</code> if path was
* <code>null</code>.
* @since 2.6.1
* @see #splitPath(String)
* @see File#pathSeparator
*/
protected static String unifyPathSeparator( final String path )
{
if ( path == null )
{
return null;
}