1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.plugins.jar;
20
21 import javax.inject.Named;
22 import javax.inject.Singleton;
23
24 import java.io.IOException;
25 import java.io.UncheckedIOException;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.util.HashMap;
29 import java.util.Map;
30 import java.util.Optional;
31
32 import org.apache.maven.toolchain.Toolchain;
33 import org.codehaus.plexus.util.cli.CommandLineException;
34 import org.codehaus.plexus.util.cli.CommandLineUtils;
35 import org.codehaus.plexus.util.cli.Commandline;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39
40
41
42 @Named
43 @Singleton
44 class ToolchainsJdkSpecification {
45
46 private final Logger logger = LoggerFactory.getLogger(ToolchainsJdkSpecification.class);
47
48 private final Map<Path, String> cache = new HashMap<>();
49
50 public synchronized Optional<String> getJDKSpecification(Toolchain toolchain) {
51 Optional<Path> javacPath = getJavacPath(toolchain);
52 return javacPath.map(path -> cache.computeIfAbsent(path, this::getSpecForPath));
53 }
54
55 private Optional<Path> getJavacPath(Toolchain toolchain) {
56 return Optional.ofNullable(toolchain.findTool("javac")).map(Paths::get).map(this::getCanonicalPath);
57 }
58
59 private Path getCanonicalPath(Path path) {
60 try {
61 return path.toRealPath();
62 } catch (IOException e) {
63 if (path.getParent() != null) {
64 return getCanonicalPath(path.getParent()).resolve(path.getFileName());
65 } else {
66 throw new UncheckedIOException(e);
67 }
68 }
69 }
70
71 private String getSpecForPath(Path path) {
72 try {
73 Commandline cl = new Commandline(path.toString());
74 cl.createArg().setValue("-version");
75 CommandLineUtils.StringStreamConsumer out = new CommandLineUtils.StringStreamConsumer();
76 CommandLineUtils.StringStreamConsumer err = new CommandLineUtils.StringStreamConsumer();
77 CommandLineUtils.executeCommandLine(cl, out, err);
78 String version = out.getOutput().trim();
79 if (version.isEmpty()) {
80 version = err.getOutput().trim();
81 }
82 if (version.startsWith("javac ")) {
83 version = version.substring(6);
84 if (version.startsWith("1.")) {
85 version = version.substring(0, 3);
86 } else {
87 version = version.substring(0, 2);
88 }
89 return version;
90 } else {
91 logger.warn("Unrecognized output form " + path + " -version - " + version);
92 return null;
93 }
94 } catch (CommandLineException | IndexOutOfBoundsException e) {
95 logger.warn("Failed to execute: " + path + " - " + e.getMessage());
96 return null;
97 }
98 }
99 }