-
Notifications
You must be signed in to change notification settings - Fork 4
/
JPM.java
1393 lines (1236 loc) · 61 KB
/
JPM.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
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.jar.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.security.*;
import java.util.concurrent.*;
import java.util.regex.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
class ThisProject extends JPM.Project {
static{ // Optional task related examples:
JPM.ROOT.pluginsAfter.add(new JPM.Plugin("deploy").withExecute((project) -> {
// Register custom task named "deploy", and run your tasks code here.
// If this throws an exception the whole build stops.
}));
JPM.Build.GET.pluginsAfter.add(new JPM.Plugin("").withExecute((project) -> {
// Run something after/before another task.
// In this case after the "build" task
}));
}
public ThisProject(List<String> args) {
// Override default configurations
this.groupId = "com.mycompany";
this.artifactId = "my-project";
this.version = "1.0.0";
this.mainClass = "com.mycompany.MyMainClass";
this.jarName = "my-project.jar";
this.fatJarName = "my-project-with-dependencies.jar";
// Add some example dependencies
addDependency("junit", "junit", "4.13.2");
addDependency("org.apache.commons", "commons-lang3", "3.12.0");
//implementation("org.apache.commons:commons-lang3:3.12.0"); // Same as above but similar to Gradle DSL
// Add some compiler arguments
addCompilerArg("-Xlint:unchecked");
addCompilerArg("-Xlint:deprecation");
}
public static void main(String[] args) throws Exception {
JPM.main(args);
}
}
class ThirdPartyPlugins extends JPM.Plugins{
// Add third party plugins below:
// (If you want to develop a plugin take a look at "JPM.Clean" class further below to get started)
}
// 1JPM version 1.0.3 by Osiris-Team
// To upgrade JPM, replace the JPM class below with its newer version
public class JPM {
public static final Plugin ROOT = new Plugin("root");
public static void main(String[] args) throws Exception {
List<String> argList = new ArrayList<>(Arrays.asList(args));
if (argList.isEmpty()) {
System.out.println("Usage: java JPM.java <task>");
System.out.println("Use 'java JPM.java help' to see available tasks.");
return;
}
// Load third party plugins
new ThirdPartyPlugins();
// Execute tasks
ThisProject thisProject = new ThisProject(argList);
for (String arg : argList) {
long startTime = System.currentTimeMillis();
thisProject.executeRootTask(arg);
long endTime = System.currentTimeMillis();
System.out.println("Task '" + arg + "' completed in " + (endTime - startTime) + "ms");
}
System.out.println("All relevant files can be found inside /build at "+Paths.get(thisProject.buildDir));
}
//
// API and Models
//
public static interface ConsumerWithException<T> extends Serializable {
void accept(T t) throws Exception;
}
public static class Plugin {
public String id;
public ConsumerWithException<Project> execute = (project) -> {};
public List<Plugin> pluginsBefore = new CopyOnWriteArrayList<>();
public List<Plugin> pluginsAfter = new CopyOnWriteArrayList<>();
public Plugin(String id) {
this.id = id;
}
public Plugin withExecute(ConsumerWithException<Project> code){
this.execute = code;
return this;
}
public Plugin withPluginsBefore(Plugin... l) {
withPluginsBefore(Arrays.asList(l));
return this;
}
public Plugin withPluginsBefore(List<Plugin> l) {
this.pluginsBefore = l;
return this;
}
public Plugin withPluginsAfter(Plugin... l) {
withPluginsAfter(Arrays.asList(l));
return this;
}
public Plugin withPluginsAfter(List<Plugin> l) {
this.pluginsAfter = l;
return this;
}
public void execute(Project project) throws Exception {
for (Plugin plugin : pluginsBefore) {
plugin.execute(project);
}
execute.accept(project);
for (Plugin plugin : pluginsAfter) {
plugin.execute(project);
}
}
}
public static class Plugins {
}
public static class Dependency {
public String groupId;
public String artifactId;
public String version;
public String scope;
public List<Dependency> transitiveDependencies;
public Dependency(String groupId, String artifactId, String version) {
this(groupId, artifactId, version, "compile", new ArrayList<>());
}
public Dependency(String groupId, String artifactId, String version, String scope) {
this(groupId, artifactId, version, scope, new ArrayList<>());
}
public Dependency(String groupId, String artifactId, String version, String scope, List<Dependency> transitiveDependencies) {
this.groupId = groupId;
this.artifactId = artifactId;
this.version = version;
this.scope = scope;
this.transitiveDependencies = transitiveDependencies;
}
@Override
public String toString() {
return groupId + ":" + artifactId + ":" + version + ":" + scope;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Dependency that = (Dependency) o;
return Objects.equals(groupId, that.groupId) &&
Objects.equals(artifactId, that.artifactId) &&
Objects.equals(version, that.version) &&
Objects.equals(scope, that.scope);
}
@Override
public int hashCode() {
return Objects.hash(groupId, artifactId, version, scope);
}
}
public static class VersionRange {
private final String lowerBound;
private final boolean lowerInclusive;
private final String upperBound;
private final boolean upperInclusive;
public VersionRange(String range) {
Pattern pattern = Pattern.compile("([\\[\\(])([^,]+),([^\\]\\)]+)([\\]\\)])");
Matcher matcher = pattern.matcher(range);
if (matcher.matches()) {
lowerInclusive = "[".equals(matcher.group(1));
lowerBound = matcher.group(2);
upperBound = matcher.group(3);
upperInclusive = "]".equals(matcher.group(4));
} else {
lowerInclusive = true;
lowerBound = range;
upperBound = null;
upperInclusive = true;
}
}
public boolean includes(String version) {
int lowerComparison = compareVersions(version, lowerBound);
if (lowerComparison < 0 || (!lowerInclusive && lowerComparison == 0)) {
return false;
}
if (upperBound == null) {
return true;
}
int upperComparison = compareVersions(version, upperBound);
return upperComparison < 0 || (upperInclusive && upperComparison == 0);
}
}
public static class Project {
protected String srcDir = "src/main/java";
protected String testSrcDir = "src/test/java";
protected String buildDir = "build";
protected String classesDir = buildDir + "/classes";
protected String testClassesDir = buildDir + "/test-classes";
protected String jarName = "output.jar";
protected String fatJarName = "output-fat.jar";
protected String mainClass = "com.example.Main";
protected String libDir = "lib";
protected String groupId = "com.example";
protected String artifactId = "project";
protected String version = "1.0.0";
protected List<Dependency> dependencies = new ArrayList<>();
protected List<String> compilerArgs = new ArrayList<>();
public void executeRootTask(String task) throws Exception {
for (Plugin plugin : ROOT.pluginsAfter) {
if (plugin.id.equals(task)) {
plugin.execute(this);
return;
}
}
System.out.println("Unknown task: " + task);
}
public void implementation(String s){
String[] split = s.split(":");
if(split.length < 3) throw new RuntimeException("Does not contain all required details: "+s);
addDependency(split[0], split[1], split[2]);
}
public void addDependency(String groupId, String artifactId, String version) {
dependencies.add(new Dependency(groupId, artifactId, version));
}
public void addCompilerArg(String arg) {
compilerArgs.add(arg);
}
}
//
// Utility methods
//
public static void deleteDirectory(Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return FileVisitResult.CONTINUE;
}
});
}
public static List<String> getSourceFiles(String directory) throws IOException {
try (Stream<Path> walk = Files.walk(Paths.get(directory))) {
return walk.filter(Files::isRegularFile)
.map(Path::toString)
.filter(f -> f.endsWith(".java"))
.collect(Collectors.toList());
}
}
public static void runCommand(List<String> command) throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(command);
processBuilder.inheritIO();
Process process = processBuilder.start();
int exitCode = process.waitFor();
if (exitCode != 0) {
throw new RuntimeException("Command failed with exit code: " + exitCode);
}
}
public static void addToJar(JarOutputStream jos, Path sourceDir, String parentPath) throws IOException {
Files.walk(sourceDir)
.filter(Files::isRegularFile)
.forEach(file -> {
try {
String entryName = parentPath + sourceDir.relativize(file).toString().replace('\\', '/');
jos.putNextEntry(new JarEntry(entryName));
Files.copy(file, jos);
jos.closeEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
public static void addJarToFatJar(JarOutputStream jos, Path jarPath) throws IOException {
try (JarInputStream jis = new JarInputStream(Files.newInputStream(jarPath))) {
JarEntry entry;
while ((entry = jis.getNextJarEntry()) != null) {
if (!entry.isDirectory() && !entry.getName().startsWith("META-INF")) {
jos.putNextEntry(new JarEntry(entry.getName()));
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = jis.read(buffer)) != -1) {
jos.write(buffer, 0, bytesRead);
}
jos.closeEntry();
}
}
}
}
public static String getClasspathString(Project project, String... additionalPaths) throws IOException {
return String.join(File.pathSeparator, getClasspath(project));
}
public static List<String> getClasspath(Project project, String... additionalPaths) throws IOException {
List<String> classpath = new ArrayList<>();
if(additionalPaths != null)
for (String additionalPath : additionalPaths) {
classpath.add(additionalPath.replace("\\", "/"));
}
Path libDir = Paths.get(project.libDir);
if (Files.exists(libDir)) {
try (Stream<Path> walk = Files.walk(libDir)) {
classpath.addAll(walk.filter(file -> file.toString().endsWith(".jar")).map(path -> path.toString().replace("\\", "/"))
.collect(Collectors.toList()));
}
}
return classpath;
}
@Deprecated
public static void downloadDependency(Dependency dep, Path libDir) throws IOException {
String mavenRepoUrl = "https://repo1.maven.org/maven2/";
String artifactPath = dep.groupId.replace('.', '/') + '/' + dep.artifactId + '/' + dep.version + '/' +
dep.artifactId + '-' + dep.version + ".jar";
URL url = new URL(mavenRepoUrl + artifactPath);
Path targetPath = libDir.resolve(dep.artifactId + '-' + dep.version + ".jar");
System.out.println("Downloading: " + url);
try (InputStream in = url.openStream()) {
Files.copy(in, targetPath, StandardCopyOption.REPLACE_EXISTING);
}
}
public static byte[] readAllBytes(InputStream inputStream) throws IOException {
final int bufLen = 1024;
byte[] buf = new byte[bufLen];
int readLen;
IOException exception = null;
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
while ((readLen = inputStream.read(buf, 0, bufLen)) != -1)
outputStream.write(buf, 0, readLen);
return outputStream.toByteArray();
} catch (IOException e) {
exception = e;
throw e;
} finally {
if (exception == null) inputStream.close();
else try {
inputStream.close();
} catch (IOException e) {
exception.addSuppressed(e);
}
}
}
public static int compareVersions(String v1, String v2) {
String[] parts1 = v1.split("\\.");
String[] parts2 = v2.split("\\.");
int length = Math.max(parts1.length, parts2.length);
for (int i = 0; i < length; i++) {
int p1 = i < parts1.length ? Integer.parseInt(parts1[i]) : 0;
int p2 = i < parts2.length ? Integer.parseInt(parts2[i]) : 0;
if (p1 != p2) {
return Integer.compare(p1, p2);
}
}
return 0;
}
//
// Internal plugins
//
static {
ROOT.pluginsAfter.add(Clean.GET);
}
public static class Clean extends Plugin {
public static Clean GET = new Clean();
public Clean() {
super("clean");
withExecute((project) -> {
System.out.println("Cleaning build directory...");
Path buildPath = Paths.get(project.buildDir);
if (Files.exists(buildPath)) {
deleteDirectory(buildPath);
}
});
}
}
static {
ROOT.pluginsAfter.add(Compile.GET);
}
public static class Compile extends Plugin {
public static Compile GET = new Compile();
public Compile() {
super("compile");
withExecute((project) -> {
System.out.println("Compiling Java source files...");
Files.createDirectories(Paths.get(project.classesDir));
List<String> sourceFiles = getSourceFiles(project.srcDir);
List<String> compileCommand = new ArrayList<>(Arrays.asList(
"javac", "-d", project.classesDir, "-cp", getClasspathString(project)
));
compileCommand.addAll(project.compilerArgs);
compileCommand.addAll(sourceFiles);
runCommand(compileCommand);
});
withPluginsBefore(Clean.GET);
}
}
static {
ROOT.pluginsAfter.add(ProcessResources.GET);
}
public static class ProcessResources extends Plugin {
public static ProcessResources GET = new ProcessResources();
public ProcessResources() {
super("processResources");
withExecute((project) -> {
System.out.println("Processing resource files...");
Path resourcesDir = Paths.get("src/main/resources");
Path outputDir = Paths.get(project.classesDir);
if (Files.exists(resourcesDir)) {
Files.walk(resourcesDir)
.filter(Files::isRegularFile)
.forEach(source -> {
try {
Path relativePath = resourcesDir.relativize(source);
Path destination = outputDir.resolve(relativePath);
Files.createDirectories(destination.getParent());
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException("Failed to process resource: " + source, e);
}
});
}
});
withPluginsBefore(Compile.GET);
}
}
static {
ROOT.pluginsAfter.add(CompileTest.GET);
}
public static class CompileTest extends Plugin {
public static CompileTest GET = new CompileTest();
public CompileTest() {
super("compileTest");
withExecute((project) -> {
System.out.println("Compiling test Java source files...");
Files.createDirectories(Paths.get(project.testClassesDir));
List<String> sourceFiles = getSourceFiles(project.testSrcDir);
List<String> compileCommand = new ArrayList<>(Arrays.asList(
"javac", "-d", project.testClassesDir, "-cp",
getClasspathString(project, project.classesDir)
));
compileCommand.addAll(project.compilerArgs);
compileCommand.addAll(sourceFiles);
runCommand(compileCommand);
});
withPluginsBefore(Compile.GET);
}
}
static {
ROOT.pluginsAfter.add(Test.GET);
}
public static class Test extends Plugin {
public static Test GET = new Test();
public Test() {
super("test");
withExecute((project) -> {
System.out.println("Running tests...");
List<String> command = new ArrayList<>(Arrays.asList(
"java", "-cp", getClasspathString(project, project.classesDir, project.testClassesDir),
"org.junit.platform.console.ConsoleLauncher",
"--scan-classpath",
"--reports-dir=" + project.buildDir + "/test-results"
));
runCommand(command);
});
withPluginsBefore(CompileTest.GET);
}
}
static {
ROOT.pluginsAfter.add(Jar.GET);
}
public static class Jar extends Plugin {
public static Jar GET = new Jar();
public Jar() {
super("jar");
withExecute((project) -> {
System.out.println("Creating JAR file...");
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, project.mainClass);
try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream(Paths.get(project.jarName)), manifest)) {
Path classesDirPath = Paths.get(project.classesDir);
Files.walk(classesDirPath)
.filter(Files::isRegularFile)
.forEach(file -> {
try {
String entryName = classesDirPath.relativize(file).toString().replace('\\', '/');
jos.putNextEntry(new JarEntry(entryName));
Files.copy(file, jos);
jos.closeEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
});
withPluginsBefore(Compile.GET, ProcessResources.GET);
}
}
static {
ROOT.pluginsAfter.add(FatJar.GET);
}
public static class FatJar extends Plugin {
public static FatJar GET = new FatJar();
public FatJar() {
super("fatJar");
withExecute((project) -> {
System.out.println("Creating fat JAR...");
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, project.mainClass);
try (JarOutputStream jos = new JarOutputStream(Files.newOutputStream(Paths.get(project.fatJarName)), manifest)) {
// Add project classes
addToJar(jos, Paths.get(project.classesDir), "");
// Add dependencies
for (String dep : getClasspath(project)) {
Path depPath = Paths.get(dep);
if (Files.isRegularFile(depPath) && depPath.toString().endsWith(".jar")) {
addJarToFatJar(jos, depPath);
}
}
}
});
withPluginsBefore(Compile.GET, ProcessResources.GET);
}
}
static {
ROOT.pluginsAfter.add(Dependencies.GET);
}
public static class Dependencies extends Plugin {
public static Dependencies GET = new Dependencies();
public Dependencies() {
super("dependencies");
withExecute((project) -> {
System.out.println("Project dependencies:");
for (Dependency dep : project.dependencies) {
System.out.println("- " + dep);
}
});
}
}
static {
ROOT.pluginsAfter.add(DependencyUpdate.GET);
}
public static class DependencyUpdate extends Plugin {
public static DependencyUpdate GET = new DependencyUpdate();
public DependencyUpdate() {
super("dependencyUpdate");
withExecute((project) -> {
System.out.println("Checking for dependency updates...");
for (Dependency dep : project.dependencies) {
String latestVersion = getLatestVersion(dep);
if (!latestVersion.equals(dep.version)) {
System.out.println(dep + " can be updated to " + latestVersion);
} else {
System.out.println(dep + " is up to date");
}
}
});
}
private String getLatestVersion(Dependency dep) throws IOException {
String mavenMetadataUrl = String.format(
"https://repo1.maven.org/maven2/%s/%s/maven-metadata.xml",
dep.groupId.replace('.', '/'), dep.artifactId
);
URL url = new URL(mavenMetadataUrl);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.contains("<release>")) {
return line.replaceAll(".*<release>(.*)</release>.*", "$1").trim();
}
}
}
return dep.version; // Return current version if unable to find latest
}
}
static {
ROOT.pluginsAfter.add(Help.GET);
}
public static class Help extends Plugin {
public static Help GET = new Help();
public Help() {
super("help");
withExecute((project) -> {
System.out.println("Available tasks:");
for (Plugin plugin : ROOT.pluginsAfter) {
System.out.println("- " + plugin.id);
}
System.out.println("\nUse 'java JPM.java <task>' to run a task.");
});
}
}
static {
ROOT.pluginsAfter.add(ResolveDependencies.GET);
}
public static class ResolveDependencies extends Plugin {
public static ResolveDependencies GET = new ResolveDependencies();
public static final String MAVEN_CENTRAL = "https://repo1.maven.org/maven2/";
public static final Set<String> REPOSITORIES = new LinkedHashSet<>(Arrays.asList(MAVEN_CENTRAL));
public static final Map<String, Dependency> DEPENDENCY_CACHE = new ConcurrentHashMap<>();
public static final Map<String, String> VERSION_CACHE = new ConcurrentHashMap<>();
public static final Path LOCAL_REPO = Paths.get(System.getProperty("user.home"), ".m2", "repository");
public ResolveDependencies() {
super("resolveDependencies");
withExecute((project) -> {
updateCentralIndex();
resolveDependencies(project);
handleMultiProjectBuild(project);
generateDependencyReport(new HashSet<>(project.dependencies), Paths.get(project.buildDir, "dependency-report.txt"));
});
}
protected final Object lock = new Object();
protected void resolveDependencies(Project project) throws Exception {
System.out.println("Resolving dependencies...");
Path libDir = Paths.get(project.libDir);
Files.createDirectories(libDir);
Set<Dependency> resolvedDependencies = new LinkedHashSet<>();
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (Dependency dep : project.dependencies) {
resolveDependencyTree(futures, dep, resolvedDependencies, new LinkedHashSet<>(), new LinkedHashSet<>(REPOSITORIES));
}
int maxSeconds = 600 * 3;
for (int i = 0; i < maxSeconds; i++) {
Thread.sleep(1000);
boolean isAllDone = true;
for (CompletableFuture<Void> f : futures) {
if(!f.isDone()) {
isAllDone = false;
break;
}
}
if(isAllDone) break;
}
for (CompletableFuture<Void> f : futures) {
if(!f.isDone()) throw new Exception("There is still a task running after "+maxSeconds+" seconds. Terminated due to timeout reached.");
}
handleDependencyConflicts(resolvedDependencies);
for (Dependency dep : resolvedDependencies) {
downloadDependency(dep, libDir);
}
generateBuildSignature(resolvedDependencies, project);
}
protected void resolveDependencyTree(List<CompletableFuture<Void>> futures, Dependency dep,
Set<Dependency> resolvedDependencies, Set<String> visitedDeps, Set<String> currentRepositories) {
futures.add(CompletableFuture.runAsync(() -> {
try{
synchronized (lock){
String depKey = dep.toString();
if (visitedDeps.contains(depKey)) {
if (!resolvedDependencies.contains(dep)) {
System.out.println("Already resolved dependency detected (possibly circular): " + depKey);
return;
}
return;
}
visitedDeps.add(depKey);
Dependency cachedDep = DEPENDENCY_CACHE.get(depKey);
if (cachedDep != null) {
resolvedDependencies.add(cachedDep);
return;
}
}
String pomContent = downloadPom(dep, currentRepositories);
if(pomContent.isEmpty()) return;
Document pomDoc = parsePom(dep, pomContent);
resolveVersion(dep, pomContent, pomDoc, resolvedDependencies, visitedDeps, currentRepositories);
// Parse repositories before resolving transitive dependencies
Set<String> updatedRepositories = new HashSet<>(currentRepositories);
updatedRepositories.addAll(parseRepositories(pomDoc));
List<Dependency> transitiveDeps = getDependenciesUnsafe(pomDoc);
for (Dependency tDep : transitiveDeps) {
resolveVersion(tDep, pomContent, pomDoc, resolvedDependencies, visitedDeps, currentRepositories);
}
synchronized (lock){
dep.transitiveDependencies = transitiveDeps;
if(dep.scope == null) dep.scope = "compile";
String depKey = dep.toString();
DEPENDENCY_CACHE.put(depKey, dep);
if (!dep.scope.equals("import")) {
resolvedDependencies.add(dep);
}
}
for (Dependency transitiveDep : transitiveDeps) {
resolveDependencyTree(futures, transitiveDep, resolvedDependencies, visitedDeps, updatedRepositories);
}
} catch (Exception e) {
System.err.println("Error while 'resolveDependencyTree' for "+dep);
throw new CompletionException(e);
}
}));
}
protected String downloadPom(Dependency dep, Set<String> repositories) throws IOException {
Path localPomPath = getLocalArtifactPath(dep, "pom");
if (Files.exists(localPomPath)) {
System.out.println("Successfully fetched from cache: "+localPomPath);
return new String(Files.readAllBytes(localPomPath));
}
for (String repo : repositories) {
String pomUrl = String.format("%s%s/%s/%s/%s-%s.pom",
repo, dep.groupId.replace('.', '/'), dep.artifactId, dep.version, dep.artifactId, dep.version);
try {
URL url = new URL(pomUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true);
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (InputStream in = conn.getInputStream()) {
byte[] pomBytes = readAllBytes(in);
Files.createDirectories(localPomPath.getParent());
Files.write(localPomPath, pomBytes);
System.out.println("Successfully fetched from: " + pomUrl);
return new String(pomBytes);
}
} else if (responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
String newUrl = conn.getHeaderField("Location");
System.out.println("Redirected to: " + newUrl);
// Recursively call the method with the new URL
return downloadPomFromUrl(new URL(newUrl), localPomPath);
} else {
System.out.println("Failed to fetch dependency from URL: " + pomUrl + ". Response code: " + responseCode);
}
} catch (Exception e) {
System.out.println("Error fetching dependency from URL: " + pomUrl + ". " + e.getMessage());
// Try next repository
}
}
if(dep.scope != null && dep.scope.equals("provided")){
System.err.println("POM not found ignored since its scope is 'provided' for " + dep);
return "";
}
throw new IOException("POM not found for " + dep);
}
private String downloadPomFromUrl(URL url, Path localPomPath) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(true);
try (InputStream in = conn.getInputStream()) {
byte[] pomBytes = readAllBytes(in);
Files.createDirectories(localPomPath.getParent());
Files.write(localPomPath, pomBytes);
return new String(pomBytes);
}
}
protected Set<String> parseRepositories(Document pomDoc) {
Set<String> newRepositories = new HashSet<>();
NodeList repositoryNodes = pomDoc.getElementsByTagNameNS("http://maven.apache.org/POM/4.0.0", "repository");
List<Element> els = new ArrayList<>();
for (int i = 0; i < repositoryNodes.getLength(); i++) {
els.add((Element) repositoryNodes.item(i));
}
NodeList snapshotRepositoryNodes = pomDoc.getElementsByTagNameNS("http://maven.apache.org/POM/4.0.0", "snapshotRepository");
for (int i = 0; i < snapshotRepositoryNodes.getLength(); i++) {
els.add((Element) snapshotRepositoryNodes.item(i));
}
for (Element el : els) {
String url = getElementContent(el, "url");
if (url != null && !url.isEmpty()) {
if (!url.endsWith("/")) {
url += "/";
}
newRepositories.add(url);
}
}
return newRepositories;
}
protected Document parsePom(Dependency dep, String pomContent) throws Exception {
try{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true); // Enable namespace awareness
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new ByteArrayInputStream(pomContent.getBytes()));
} catch (Exception e) {
System.err.println("Error while 'parsePom' for "+dep);
System.err.println("Content of pom.xml (with "+pomContent.length()+" chars): \n"+pomContent);
throw e;
}
}
protected void resolveVersion(Dependency dep, String pomContent, Document pomDoc, Set<Dependency> resolvedDependencies, Set<String> visitedDeps, Set<String> currentRepositories) {
if(dep.version == null) { // VERSION EMPTY
// Check parent pom if dep exists inside it and try to retrieve version from there
NodeList parentNodes = pomDoc.getElementsByTagNameNS("http://maven.apache.org/POM/4.0.0", "parent");
if (parentNodes.getLength() <= 0) {
throw new NoParentException("Dep "+dep+" does not contain <parent> element! Content: \n"+pomContent);
}
Element parentElement = (Element) parentNodes.item(0);
String parentGroupId = getElementContent(parentElement, "groupId");
String parentArtifactId = getElementContent(parentElement, "artifactId");
String parentVersion = getElementContent(parentElement, "version");
try {
// Hope that the parent contains the version property
if(parentGroupId.equals("org.apache.maven") && parentArtifactId.equals("maven-parent"))
throw new NoParentException("Reached maven-parent, thus went through all parents without finding the version!");
Dependency parentDep = new Dependency(parentGroupId, parentArtifactId, parentVersion);
String parentPomContent = downloadPom(parentDep, currentRepositories);
if(parentPomContent.isEmpty()) throw new NullPointerException(parentPomContent);
Document parentPomDoc = parsePom(parentDep, parentPomContent);
if(parentArtifactId.equals("surefire") && dep.artifactId.equals("common-junit48"))
System.out.println("WOWS");
List<Dependency> dependencies = getDependenciesUnsafe(parentPomDoc);
for (Dependency depInParent : dependencies) {
if(depInParent.groupId.equals(dep.groupId) && depInParent.artifactId.equals(dep.artifactId)){
resolveVersion(depInParent, parentPomContent, parentPomDoc, resolvedDependencies, visitedDeps, currentRepositories);
dep.version = depInParent.version;
break;
}
}
if(dep.version == null){
// Go one up and try parent of parent (until there is no parent left)
resolveVersion(dep, parentPomContent, parentPomDoc, resolvedDependencies, visitedDeps, currentRepositories);
return;
}
} catch (Exception e) {
throw new RuntimeException("Error resolving dependency ("+dep+") version from parent POM ("+parentGroupId+":"+parentArtifactId+":"+parentVersion+")", e);
}
return;
}
if (!dep.version.startsWith("${") && !dep.version.startsWith("[") && !dep.version.contains(",")) {
return;
}
String cacheKey = dep.groupId + ":" + dep.artifactId + ":" + dep.version;
String cachedVersion = VERSION_CACHE.get(cacheKey);
if (cachedVersion != null) {
dep.version = cachedVersion;
return;
}
String resolvedVersion;
if (dep.version.startsWith("${")) {
resolvedVersion = resolveVersionFromProperty(dep, dep.version, pomContent, pomDoc);
} else {
List<String> availableVersions = getAvailableVersions(pomDoc);
Map<String, String> managedVersions = parseDependencyManagement(pomDoc);
String key = dep.groupId + ":" + dep.artifactId;
String priorityVersion = managedVersions.get(key);
if(priorityVersion != null) availableVersions.add(priorityVersion);
resolvedVersion = resolveVersionRange(dep.version, availableVersions);
}
if(resolvedVersion == null){ // VERSION AS PROPERTY
// Check parent pom if contains property
NodeList parentNodes = pomDoc.getElementsByTagNameNS("http://maven.apache.org/POM/4.0.0", "parent");
if (parentNodes.getLength() <= 0) {
throw new NoParentException("Error resolving property from parent POM, no <parent> element! Content: \n"+pomContent);
}
Element parentElement = (Element) parentNodes.item(0);
String parentGroupId = getElementContent(parentElement, "groupId");
String parentArtifactId = getElementContent(parentElement, "artifactId");
String parentVersion = getElementContent(parentElement, "version");
try {
// Hope that the parent contains the version property
if(parentGroupId.equals("org.apache.maven") && parentArtifactId.equals("maven-parent"))
throw new NoParentException("Reached maven-parent, thus went through all parents without finding the version!");
Dependency parentDep = new Dependency(parentGroupId, parentArtifactId, parentVersion);
String parentPomContent = downloadPom(parentDep, currentRepositories);
if(parentPomContent.isEmpty()) throw new NullPointerException(parentPomContent);
Document parentPomDoc = parsePom(parentDep, parentPomContent);
if(parentArtifactId.equals("surefire") && dep.artifactId.equals("common-junit48"))
System.out.println("WOWS");
resolvedVersion = resolveVersionFromProperty(dep, dep.version, parentPomContent, parentPomDoc);
if(resolvedVersion == null){
// Go one up into parent and try again
resolveVersion(dep, parentPomContent, parentPomDoc, resolvedDependencies, visitedDeps, currentRepositories);
return;
}
} catch (Exception e) {
throw new RuntimeException("Error resolving dependency ("+dep+") property version from parent POM ("+parentGroupId+":"+parentArtifactId+":"+parentVersion+")", e);
}
}
dep.version = resolvedVersion;
VERSION_CACHE.put(cacheKey, resolvedVersion);
}
protected String resolveVersionFromProperty(Dependency dep, String propertyRef, String pomContent, Document pomDoc) {
String propertyName = propertyRef.substring(2, propertyRef.length() - 1);
String value = resolveVersionFromProperty1(dep, propertyName, pomContent, pomDoc);
if (value == null) {
System.err.println("Property not found: " + propertyName);
return null;
}
return value.contains("${") ? resolveVersionFromProperty(dep, value, pomContent, pomDoc) : value;
}
protected String resolveVersionFromProperty1(Dependency dep, String propertyName, String pomContent, Document pomDoc) {
String[] propertyParts = propertyName.split("\\.");
// Check project properties
NodeList propertiesNodes = pomDoc.getElementsByTagNameNS("http://maven.apache.org/POM/4.0.0", "properties");
for (int i = 0; i < propertiesNodes.getLength(); i++) {
Element propertiesElement = (Element) propertiesNodes.item(i);
NodeList propertyNodes = propertiesElement.getChildNodes();
for (int j = 0; j < propertyNodes.getLength(); j++) {
Node propertyNode = propertyNodes.item(j);
if (propertyNode.getNodeType() == Node.ELEMENT_NODE &&
propertyNode.getLocalName().equals(propertyName)) {
return propertyNode.getTextContent().trim();