-
Notifications
You must be signed in to change notification settings - Fork 100
/
ExecMojo.java
1099 lines (952 loc) · 41.6 KB
/
ExecMojo.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.exec;
/*
* 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.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteResultHandler;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Executor;
import org.apache.commons.exec.OS;
import org.apache.commons.exec.ProcessDestroyer;
import org.apache.commons.exec.PumpStreamHandler;
import org.apache.commons.exec.ShutdownHookProcessDestroyer;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.filter.AndArtifactFilter;
import org.apache.maven.artifact.resolver.filter.IncludesArtifactFilter;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.toolchain.Toolchain;
import org.apache.maven.toolchain.ToolchainManager;
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 org.codehaus.plexus.util.cli.DefaultConsumer;
import org.codehaus.plexus.util.cli.StreamConsumer;
/**
* A Plugin for executing external programs.
*
* @author Jerome Lacoste ([email protected])
* @version $Id$
* @since 1.0
*/
@Mojo(name = "exec", threadSafe = true, requiresDependencyResolution = ResolutionScope.TEST)
public class ExecMojo extends AbstractExecMojo {
/**
* Trying to recognize whether the given {@link #executable} might be a {@code java} binary.
*/
private static final Pattern ENDS_WITH_JAVA = Pattern.compile("^.*java(\\.exe|\\.bin)?$", Pattern.CASE_INSENSITIVE);
/**
* <p>
* The executable. Can be a full path or the name of the executable. In the latter case, the executable must be in
* the PATH for the execution to work. Omit when using <code>executableDependency</code>.
* </p>
* <p>
* The plugin will search for the executable in the following order:
* <ol>
* <li>relative to the root of the project</li>
* <li>as toolchain executable</li>
* <li>relative to the working directory (Windows only)</li>
* <li>relative to the directories specified in the system property PATH (Windows Only)</li>
* </ol>
* Otherwise use the executable as is.
* </p>
*
* @since 1.0
*/
@Parameter(property = "exec.executable")
private String executable;
/**
* <p>
* Timeout in full milliseconds, default is {@code 0}.
* <p>
* <p>
* When set to a value larger than zero, the executable is forcefully
* terminated if it did not finish within this time, and the build will
* fail.
* </p>
*
* @since 3.0.0
*/
@Parameter(property = "exec.timeout", defaultValue = "0")
private int timeout;
/**
* <p>
* The toolchain. If omitted, <code>"jdk"</code> is assumed.
* </p>
*/
@Parameter(property = "exec.toolchain", defaultValue = "jdk")
private String toolchain;
/**
* The current working directory. Optional. If not specified, basedir will be used.
*
* @since 1.0
*/
@Parameter(property = "exec.workingdir")
private File workingDirectory;
/**
* Program standard and error output will be redirected to the file specified by this optional field. If not
* specified the standard Maven logging is used. <br/>
* <strong>Note:</strong> Be aware that <code>System.out</code> and <code>System.err</code> use buffering, so don't
* rely on the order!
*
* @since 1.1-beta-2
* @see java.lang.System#err
* @see java.lang.System#in
*/
@Parameter(property = "exec.outputFile")
private File outputFile;
/**
* Program standard input, output and error streams will be inherited from the maven process.
* This allow tighter control of the streams and the console.
*
* @since 3.0.1
* @see ProcessBuilder#inheritIO()
*/
@Parameter(property = "exec.inheritIo")
private boolean inheritIo;
/**
* When enabled, program standard and error output will be redirected to the
* Maven logger as <i>Info</i> and <i>Error</i> level logs, respectively. If not enabled the
* traditional behavior of program output being directed to standard System.out
* and System.err is used.<br>
* <br>
* NOTE: When enabled, to log the program standard out as Maven <i>Debug</i> level instead of
* <i>Info</i> level use {@code exec.quietLogs=true}. <br>
* <br>
* This option can be extremely helpful when combined with multithreaded builds
* for two reasons:<br>
* <ul>
* <li>Program output is suffixed with the owning thread name, making it easier
* to trace execution of a specific projects build thread.</li>
* <li>Program output will not get jumbled with other maven log messages.</li>
* </ul>
*
* For Example, if using {@code exec:exec} to run a script to echo a count from
* 1 to 100 as:
*
* <pre>
* for i in {1..100}
* do
* echo "${project.artifactId} - $i"
* done
* </pre>
*
* When this script is run multi-threaded on two modules, {@code module1} and
* {@code module2}, you might get output such as:
*
* <pre>
* [BuilderThread 1] [INFO] --- exec-maven-plugin:1.6.0:exec (test) @ module1 ---
* [BuilderThread 2] [INFO] --- exec-maven-plugin:1.6.0:exec (test) @ module2 ---
* ...
* module2 - 98
* modu
* module1 - 97
* module1 -
* le2 - 9899
* ...
* </pre>
*
* With this flag enabled, the output will instead come something similar to:
*
* <pre>
* ...
* [Exec Stream Pumper] [INFO] [BuilderThread 2] module2 - 98
* [Exec Stream Pumper] [INFO] [BuilderThread 1] module1 - 97
* [Exec Stream Pumper] [INFO] [BuilderThread 1] module1 - 98
* [Exec Stream Pumper] [INFO] [BuilderThread 2] module2 - 99
* ...
* </pre>
*
* NOTE 1: To show the thread in the Maven log, configure the Maven
* installations <i>conf/logging/simplelogger.properties</i> option:
* {@code org.slf4j.simpleLogger.showThreadName=true}<br>
*
* NOTE 2: This option is ignored when {@code exec.outputFile} is specified.
*
* @since 3.0.0
* @see java.lang.System#err
* @see java.lang.System#in
*/
@Parameter(property = "exec.useMavenLogger", defaultValue = "false")
private boolean useMavenLogger;
/**
* When combined with {@code exec.useMavenLogger=true}, prints all executed
* program output at debug level instead of the default info level to the Maven
* logger.
*
* @since 3.0.0
*/
@Parameter(property = "exec.quietLogs", defaultValue = "false")
private boolean quietLogs;
/**
* <p>
* A list of arguments passed to the {@code executable}, which should be of type <code><argument></code> or
* <code><classpath></code>. Can be overridden by using the <code>exec.args</code> environment variable.
* </p>
*
* @since 1.0
*/
@Parameter
private List<?> arguments; // TODO: Change ? into something more meaningful
/**
* @since 1.0
*/
@Parameter(readonly = true, required = true, defaultValue = "${basedir}")
private File basedir;
/**
* @since 3.0.0
*/
@Parameter(readonly = true, required = true, defaultValue = "${project.build.directory}")
private File buildDirectory;
/**
* <p>Environment variables to pass to the executed program. For example if you want to set the LANG var:
* <code><environmentVariables>
* <LANG>en_US</LANG>
* </environmentVariables>
* </code>
* </p>
*
* @since 1.1-beta-2
*/
@Parameter
private Map<String, String> environmentVariables = new HashMap<>();
/**
* Environment script to be merged with <i>environmentVariables</i> This script is platform specifics, on Unix its
* must be Bourne shell format. Use this feature if you have a need to create environment variable dynamically such
* as invoking Visual Studio environment script file
*
* @since 1.4.0
*/
@Parameter
private File environmentScript = null;
/**
* Exit codes to be resolved as successful execution for non-compliant applications (applications not returning 0
* for success).
*
* @since 1.1.1
*/
@Parameter
private int[] successCodes;
/**
* If set to true the classpath and the main class will be written to a MANIFEST.MF file and wrapped into a jar.
* Instead of '-classpath/-cp CLASSPATH mainClass' the exec plugin executes '-jar maven-exec.jar'.
*
* @since 1.1.2
*/
@Parameter(property = "exec.longClasspath", defaultValue = "false")
private boolean longClasspath;
/**
* If set to true the modulepath and the main class will be written as an @arg file
* Instead of '--module-path/-p MODULEPATH ' the exec plugin executes '@modulepath'.
*
* @since 1.1.2
*/
@Parameter(property = "exec.longModulepath", defaultValue = "true")
private boolean longModulepath;
/**
* Forces the plugin to recognize the given executable as java executable. This helps with {@link #longClasspath}
* and {@link #longModulepath} parameters.
*
* <p>You shouldn't normally be needing this unless you renamed your java binary or are executing tools
* other than {@code java} which need modulepath or classpath parameters in a separate file.</p>
*
* @since 3.1.1
*/
@Parameter(property = "exec.forceJava", defaultValue = "false")
private boolean forceJava;
/**
* If set to true the child process executes asynchronously and build execution continues in parallel.
*/
@Parameter(property = "exec.async", defaultValue = "false")
private boolean async;
/**
* If set to true, the asynchronous child process is destroyed upon JVM shutdown. If set to false, asynchronous
* child process continues execution after JVM shutdown. Applies only to asynchronous processes; ignored for
* synchronous processes.
*/
@Parameter(property = "exec.asyncDestroyOnShutdown", defaultValue = "true")
private boolean asyncDestroyOnShutdown = true;
/**
* Name of environment variable that will contain path to java executable provided by the toolchain (works only if JDK toolchain feature is used)
*
* @since 3.5.0
*/
@Parameter(property = "exec.toolchainJavaHomeEnvName", defaultValue = "TOOLCHAIN_JAVA_HOME")
private String toolchainJavaHomeEnvName = "TOOLCHAIN_JAVA_HOME";
@Component
private ToolchainManager toolchainManager;
public static final String CLASSPATH_TOKEN = "%classpath";
public static final String MODULEPATH_TOKEN = "%modulepath";
/**
* priority in the execute method will be to use System properties arguments over the pom specification.
*
* @throws MojoExecutionException if a failure happens
*/
public void execute() throws MojoExecutionException {
if (executable == null) {
if (executableDependency == null) {
throw new MojoExecutionException("The parameter 'executable' is missing or invalid");
}
executable = findExecutableArtifact().getFile().getAbsolutePath();
getLog().debug("using executable dependency " + executable);
}
if (isSkip()) {
getLog().info("skipping execute as per configuration");
return;
}
if (basedir == null) {
throw new IllegalStateException("basedir is null. Should not be possible.");
}
try {
handleWorkingDirectory();
String argsProp = getSystemProperty("exec.args");
List<String> commandArguments = new ArrayList<>();
if (hasCommandlineArgs()) {
handleCommandLineArgs(commandArguments);
} else if (!StringUtils.isEmpty(argsProp)) {
handleSystemPropertyArguments(argsProp, commandArguments);
} else {
if (arguments != null) {
handleArguments(commandArguments);
}
}
Map<String, String> enviro = handleSystemEnvVariables();
CommandLine commandLine = getExecutablePath(enviro, workingDirectory);
String[] args = commandArguments.toArray(new String[commandArguments.size()]);
commandLine.addArguments(args, false);
Executor exec = new ExtendedExecutor(inheritIo);
if (this.timeout > 0) {
exec.setWatchdog(new ExecuteWatchdog(this.timeout));
}
exec.setWorkingDirectory(workingDirectory);
fillSuccessCodes(exec);
if (OS.isFamilyOpenVms() && inheritIo) {
getLog().warn(
"The inheritIo flag is not supported on OpenVMS, execution will proceed without stream inheritance.");
}
getLog().debug("Executing command line: " + commandLine);
try {
int resultCode;
if (outputFile != null) {
if (!outputFile.getParentFile().exists()
&& !outputFile.getParentFile().mkdirs()) {
getLog().warn("Could not create non existing parent directories for log file: " + outputFile);
}
try (FileOutputStream outputStream = new FileOutputStream(outputFile)) {
resultCode = executeCommandLine(exec, commandLine, enviro, outputStream);
}
} else if (useMavenLogger) {
getLog().debug("Will redirect program output to Maven logger");
// If running parallel, append the projects original (i.e. current) thread name to the program
// output as a log prefix, to enable easy tracing of program output when intermixed with other
// Maven log output. NOTE: The accept(..) methods are running in PumpStreamHandler thread,
// which is why we capture the thread name prefix here.
final String logPrefix = getSession().isParallel()
? "[" + Thread.currentThread().getName() + "] "
: "";
Consumer<String> mavenOutRedirect = logMessage -> {
if (quietLogs) {
getLog().debug(logPrefix + logMessage);
} else {
getLog().info(logPrefix + logMessage);
}
};
Consumer<String> mavenErrRedirect = logMessage -> getLog().error(logPrefix + logMessage);
try (OutputStream out = new LineRedirectOutputStream(mavenOutRedirect);
OutputStream err = new LineRedirectOutputStream(mavenErrRedirect)) {
resultCode = executeCommandLine(exec, commandLine, enviro, out, err);
}
} else {
resultCode = executeCommandLine(exec, commandLine, enviro, System.out, System.err);
}
if (isResultCodeAFailure(resultCode)) {
String message = "Result of " + commandLine.toString() + " execution is: '" + resultCode + "'.";
getLog().error(message);
throw new MojoExecutionException(message);
}
} catch (ExecuteException e) {
if (exec.getWatchdog() != null && exec.getWatchdog().killedProcess()) {
final String message = "Timeout. Process runs longer than " + this.timeout + " ms.";
getLog().error(message);
throw new MojoExecutionException(message, e);
} else {
getLog().error("Command execution failed.", e);
throw new MojoExecutionException("Command execution failed.", e);
}
} catch (IOException e) {
getLog().error("Command execution failed.", e);
throw new MojoExecutionException("Command execution failed.", e);
}
registerSourceRoots();
} catch (IOException e) {
throw new MojoExecutionException("I/O Error", e);
}
}
private Map<String, String> handleSystemEnvVariables() throws MojoExecutionException {
// Avoid creating env vars that differ only in case on Windows.
// https://github.com/mojohaus/exec-maven-plugin/issues/328
// It is not enough to avoid duplicates; we must preserve the case found in the "natural" environment.
// https://developercommunity.visualstudio.com/t/Build-Error:-MSB6001-in-Maven-Build/10527486?sort=newest
Map<String, String> enviro = new HashMap<>(System.getenv());
if (environmentVariables != null) {
enviro.putAll(environmentVariables);
}
if (this.environmentScript != null) {
getLog().info("Pick up external environment script: " + this.environmentScript);
Map<String, String> envVarsFromScript = this.createEnvs(this.environmentScript);
if (envVarsFromScript != null) {
enviro.putAll(envVarsFromScript);
}
}
Toolchain tc = getToolchain();
if (tc != null && "jdk".equals(tc.getType())) {
String toolchainJava = tc.findTool("java");
if (toolchainJava != null) {
String toolchainJavaHome =
Paths.get(toolchainJava).getParent().getParent().toString();
enviro.put(toolchainJavaHomeEnvName, toolchainJavaHome);
}
}
if (this.getLog().isDebugEnabled()) {
Set<String> keys = new TreeSet<>(enviro.keySet());
for (String key : keys) {
this.getLog().debug("env: " + key + "=" + enviro.get(key));
}
}
return enviro;
}
/**
* This is a convenient method to make the execute method a little bit more readable. It will define the
* workingDirectory to be the baseDir in case of workingDirectory is null. If the workingDirectory does not exist it
* will created.
*
* @throws MojoExecutionException
*/
private void handleWorkingDirectory() throws MojoExecutionException {
if (workingDirectory == null) {
workingDirectory = basedir;
}
if (!workingDirectory.exists()) {
getLog().debug("Making working directory '" + workingDirectory.getAbsolutePath() + "'.");
if (!workingDirectory.mkdirs()) {
throw new MojoExecutionException(
"Could not make working directory: '" + workingDirectory.getAbsolutePath() + "'");
}
}
}
private void handleSystemPropertyArguments(String argsProp, List<String> commandArguments)
throws MojoExecutionException {
getLog().debug("got arguments from system properties: " + argsProp);
try {
String[] args = CommandLineUtils.translateCommandline(argsProp);
commandArguments.addAll(Arrays.asList(args));
} catch (Exception e) {
throw new MojoExecutionException("Couldn't parse systemproperty 'exec.args'");
}
}
private void handleCommandLineArgs(List<String> commandArguments) throws MojoExecutionException, IOException {
String[] args = parseCommandlineArgs();
for (int i = 0; i < args.length; i++) {
if (isLongClassPathArgument(args[i])) {
// it is assumed that starting from -cp or -classpath the arguments
// are: -classpath/-cp %classpath mainClass
// the arguments are replaced with: -jar $TMP/maven-exec.jar
// NOTE: the jar will contain the classpath and the main class
commandArguments.add("-jar");
File tmpFile = createJar(computePath(null), args[i + 2]);
commandArguments.add(tmpFile.getAbsolutePath());
i += 2;
} else if (args[i].contains(CLASSPATH_TOKEN)) {
commandArguments.add(args[i].replace(CLASSPATH_TOKEN, computeClasspathString(null)));
} else {
commandArguments.add(args[i]);
}
}
}
private void handleArguments(List<String> commandArguments) throws MojoExecutionException, IOException {
String specialArg = null;
for (int i = 0; i < arguments.size(); i++) {
Object argument = arguments.get(i);
if (specialArg != null) {
if (isLongClassPathArgument(specialArg) && argument instanceof Classpath) {
// it is assumed that starting from -cp or -classpath the arguments
// are: -classpath/-cp %classpath mainClass
// the arguments are replaced with: -jar $TMP/maven-exec.jar
// NOTE: the jar will contain the classpath and the main class
commandArguments.add("-jar");
File tmpFile = createJar(computePath((Classpath) argument), (String) arguments.get(++i));
commandArguments.add(tmpFile.getAbsolutePath());
} else if (isLongModulePathArgument(specialArg) && argument instanceof Modulepath) {
String filePath = new File(buildDirectory, "modulepath").getAbsolutePath();
StringBuilder modulePath = new StringBuilder();
modulePath.append('"');
for (Iterator<String> it =
computePath((Modulepath) argument).iterator();
it.hasNext(); ) {
modulePath.append(it.next().replace("\\", "\\\\"));
if (it.hasNext()) {
modulePath.append(File.pathSeparatorChar);
}
}
modulePath.append('"');
createArgFile(filePath, Arrays.asList("-p", modulePath.toString()));
commandArguments.add('@' + filePath);
} else {
commandArguments.add(specialArg);
}
specialArg = null;
continue;
}
if (argument instanceof Classpath) {
Classpath specifiedClasspath = (Classpath) argument;
commandArguments.add(computeClasspathString(specifiedClasspath));
} else if (argument instanceof Modulepath) {
Modulepath specifiedModulepath = (Modulepath) argument;
commandArguments.add(computeClasspathString(specifiedModulepath));
} else if ((argument instanceof String)
&& (isLongModulePathArgument((String) argument) || isLongClassPathArgument((String) argument))) {
specialArg = (String) argument;
} else if (argument == null) {
commandArguments.add("");
} else {
commandArguments.add((String) argument);
}
}
}
private void fillSuccessCodes(Executor exec) {
if (successCodes != null && successCodes.length > 0) {
exec.setExitValues(successCodes);
}
}
boolean isResultCodeAFailure(int result) {
if (successCodes == null || successCodes.length == 0) {
return result != 0;
}
for (int successCode : successCodes) {
if (successCode == result) {
return false;
}
}
return true;
}
private boolean isLongClassPathArgument(String arg) {
return isJavaExec() && longClasspath && ("-classpath".equals(arg) || "-cp".equals(arg));
}
private boolean isLongModulePathArgument(String arg) {
return isJavaExec() && longModulepath && ("--module-path".equals(arg) || "-p".equals(arg));
}
/**
* Returns {@code true} when a java binary is being executed.
*
* @return {@code true} when a java binary is being executed.
*/
private boolean isJavaExec() {
if (forceJava) {
return true;
}
if (this.executable.contains("%JAVA_HOME")
|| this.executable.contains("${JAVA_HOME}")
|| this.executable.contains("$JAVA_HOME")) {
// also applies to *most* other tools.
return true;
}
return ENDS_WITH_JAVA.matcher(this.executable).matches();
}
/**
* Compute the classpath from the specified Classpath. The computed classpath is based on the classpathScope. The
* plugin cannot know from maven the phase it is executed in. So we have to depend on the user to tell us he wants
* the scope in which the plugin is expected to be executed.
*
* @param specifiedClasspath Non null when the user restricted the dependencies, <code>null</code> otherwise (the
* default classpath will be used)
* @return a platform specific String representation of the classpath
*/
private String computeClasspathString(AbstractPath specifiedClasspath) throws MojoExecutionException {
List<String> resultList = computePath(specifiedClasspath);
StringBuffer theClasspath = new StringBuffer();
for (String str : resultList) {
addToClasspath(theClasspath, str);
}
return theClasspath.toString();
}
/**
* Compute the classpath from the specified Classpath. The computed classpath is based on the classpathScope. The
* plugin cannot know from maven the phase it is executed in. So we have to depend on the user to tell us he wants
* the scope in which the plugin is expected to be executed.
*
* @param specifiedClasspath Non null when the user restricted the dependencies, <code>null</code> otherwise (the
* default classpath will be used)
* @return a list of class path elements
*/
private List<String> computePath(AbstractPath specifiedClasspath) throws MojoExecutionException {
List<Artifact> artifacts = new ArrayList<>();
List<Path> theClasspathFiles = new ArrayList<>();
List<String> resultList = new ArrayList<>();
collectProjectArtifactsAndClasspath(artifacts, theClasspathFiles);
Set<Artifact> pluginDependencies = determineRelevantPluginDependencies();
if (pluginDependencies != null) {
artifacts.addAll(pluginDependencies);
}
if ((specifiedClasspath != null) && (specifiedClasspath.getDependencies() != null)) {
artifacts = filterArtifacts(artifacts, specifiedClasspath.getDependencies());
}
for (Path f : theClasspathFiles) {
resultList.add(f.toAbsolutePath().toString());
}
for (Artifact artifact : artifacts) {
getLog().debug("dealing with " + artifact);
resultList.add(artifact.getFile().getAbsolutePath());
}
return resultList;
}
private static void addToClasspath(StringBuffer theClasspath, String toAdd) {
if (theClasspath.length() > 0) {
theClasspath.append(File.pathSeparator);
}
theClasspath.append(toAdd);
}
private List<Artifact> filterArtifacts(List<Artifact> artifacts, Collection<String> dependencies) {
AndArtifactFilter filter = new AndArtifactFilter();
filter.add(new IncludesArtifactFilter(new ArrayList<>(dependencies))); // gosh
List<Artifact> filteredArtifacts = new ArrayList<>();
for (Artifact artifact : artifacts) {
if (filter.include(artifact)) {
getLog().debug("filtering in " + artifact);
filteredArtifacts.add(artifact);
}
}
return filteredArtifacts;
}
private ProcessDestroyer processDestroyer;
CommandLine getExecutablePath(Map<String, String> enviro, File dir) {
File execFile = new File(executable);
String exec = null;
if (execFile.isFile()) {
getLog().debug("Toolchains are ignored, 'executable' parameter is set to " + executable);
exec = execFile.getAbsolutePath();
}
if (exec == null) {
Toolchain tc = getToolchain();
// if the file doesn't exist & toolchain is null, the exec is probably in the PATH...
// we should probably also test for isFile and canExecute, but the second one is only
// available in SDK 6.
if (tc != null) {
getLog().info("Toolchain in exec-maven-plugin: " + tc);
exec = tc.findTool(executable);
} else {
if (OS.isFamilyWindows()) {
List<String> paths = this.getExecutablePaths(enviro);
paths.add(0, dir.getAbsolutePath());
exec = findExecutable(executable, paths);
}
}
}
if (exec == null) {
exec = executable;
}
CommandLine toRet;
if (OS.isFamilyWindows() && !hasNativeExtension(exec) && hasExecutableExtension(exec)) {
// run the windows batch script in isolation and exit at the end
final String comSpec = System.getenv("ComSpec");
toRet = new CommandLine(comSpec == null ? "cmd" : comSpec);
toRet.addArgument("/c");
toRet.addArgument(exec);
} else {
toRet = new CommandLine(exec);
}
return toRet;
}
static String findExecutable(final String executable, final List<String> paths) {
File f = null;
search:
for (final String path : paths) {
f = new File(path, executable);
if (!OS.isFamilyWindows() && f.isFile()) break;
else
for (final String extension : getExecutableExtensions()) {
f = new File(path, executable + extension);
if (f.isFile()) break search;
}
}
if (f == null || !f.exists()) return null;
return f.getAbsolutePath();
}
private static boolean hasNativeExtension(final String exec) {
final String lowerCase = exec.toLowerCase();
return lowerCase.endsWith(".exe") || lowerCase.endsWith(".com");
}
private static boolean hasExecutableExtension(final String exec) {
final String lowerCase = exec.toLowerCase();
for (final String ext : getExecutableExtensions()) if (lowerCase.endsWith(ext)) return true;
return false;
}
private static List<String> getExecutableExtensions() {
final String pathExt = System.getenv("PATHEXT");
return pathExt == null
? Arrays.asList(".bat", ".cmd")
: Arrays.asList(StringUtils.split(pathExt.toLowerCase(), File.pathSeparator));
}
private List<String> getExecutablePaths(Map<String, String> enviro) {
List<String> paths = new ArrayList<>();
paths.add("");
enviro.entrySet().stream()
.filter(entry -> "PATH".equalsIgnoreCase(entry.getKey()))
.map(Map.Entry::getValue)
.filter(Objects::nonNull)
.map(path -> path.split(File.pathSeparator))
.map(Arrays::asList)
.forEach(paths::addAll);
return paths;
}
protected int executeCommandLine(
Executor exec, CommandLine commandLine, Map<String, String> enviro, OutputStream out, OutputStream err)
throws IOException {
// note: don't use BufferedOutputStream here since it delays the outputs MEXEC-138
PumpStreamHandler psh = new PumpStreamHandler(out, err, System.in);
return executeCommandLine(exec, commandLine, enviro, psh);
}
protected int executeCommandLine(
Executor exec, CommandLine commandLine, Map<String, String> enviro, FileOutputStream outputFile)
throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(outputFile);
PumpStreamHandler psh = new PumpStreamHandler(bos);
return executeCommandLine(exec, commandLine, enviro, psh);
}
protected int executeCommandLine(
Executor exec, final CommandLine commandLine, Map<String, String> enviro, final PumpStreamHandler psh)
throws IOException {
exec.setStreamHandler(psh);
int result;
try {
psh.start();
if (async) {
if (asyncDestroyOnShutdown) {
exec.setProcessDestroyer(getProcessDestroyer());
}
exec.execute(commandLine, enviro, new ExecuteResultHandler() {
public void onProcessFailed(ExecuteException e) {
getLog().error("Async process failed for: " + commandLine, e);
}
public void onProcessComplete(int exitValue) {
getLog().info("Async process complete, exit value = " + exitValue + " for: " + commandLine);
try {
psh.stop();
} catch (IOException e) {
getLog().error("Error stopping async process stream handler for: " + commandLine, e);
}
}
});
result = 0;
} else {
result = exec.execute(commandLine, enviro);
}
} finally {
if (!async) {
psh.stop();
}
}
return result;
}
//
// methods used for tests purposes - allow mocking and simulate automatic setters
//
void setExecutable(String executable) {
this.executable = executable;
}
String getExecutable() {
return executable;
}
void setWorkingDirectory(String workingDir) {
setWorkingDirectory(new File(workingDir));
}
void setWorkingDirectory(File workingDir) {
this.workingDirectory = workingDir;
}
void setArguments(List<?> arguments) {
this.arguments = arguments;
}
void setBasedir(File basedir) {
this.basedir = basedir;
}
void setProject(MavenProject project) {
this.project = project;
}
protected String getSystemProperty(String key) {
return System.getProperty(key);
}
public void setSuccessCodes(Integer... list) {
this.successCodes = new int[list.length];
for (int index = 0; index < list.length; index++) {
successCodes[index] = list[index];
}
}
public int[] getSuccessCodes() {
return successCodes;
}
private Toolchain getToolchain() {
// session and toolchainManager can be null in tests ...
MavenSession session = getSession();
if (session != null && toolchainManager != null) {
return toolchainManager.getToolchainFromBuildContext(toolchain, session);
}
return null;
}
/**
* Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for all
* classpath elements. Copied from surefire (ForkConfiguration#createJar())
*
* @param classPath List<String> of all classpath elements.
* @return
* @throws IOException
*/
private File createJar(List<String> classPath, String mainClass) throws IOException {
File file = Files.createTempFile("maven-exec", ".jar").toFile();
file.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(file);
JarOutputStream jos = new JarOutputStream(fos)) {
jos.setLevel(JarOutputStream.STORED);
JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
jos.putNextEntry(je);
Manifest man = new Manifest();
// we can't use StringUtils.join here since we need to add a '/' to
// the end of directory entries - otherwise the jvm will ignore them.
StringBuilder cp = new StringBuilder();
for (String el : classPath) {
// NOTE: if File points to a directory, this entry MUST end in '/'.
cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " ");
}
man.getMainAttributes().putValue("Manifest-Version", "1.0");
man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
man.getMainAttributes().putValue("Main-Class", mainClass);
man.write(jos);