elharo commented on code in PR #14:
URL: 
https://github.com/apache/maven-toolchains-plugin/pull/14#discussion_r1504330055


##########
src/main/java/org/apache/maven/plugins/toolchain/jdk/ToolchainDiscoverer.java:
##########
@@ -0,0 +1,332 @@
+/*
+ * 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.
+ */
+package org.apache.maven.plugins.toolchain.jdk;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Writer;
+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.Comparator;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.toolchain.model.PersistedToolchains;
+import org.apache.maven.toolchain.model.ToolchainModel;
+import org.apache.maven.toolchain.model.io.xpp3.MavenToolchainsXpp3Reader;
+import org.apache.maven.toolchain.model.io.xpp3.MavenToolchainsXpp3Writer;
+import org.codehaus.plexus.util.xml.Xpp3Dom;
+import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
+
+/**
+ * Implementation of ToolchainDiscoverer service
+ */
+public class ToolchainDiscoverer {
+
+    private static final String DISCOVERED_TOOLCHAINS_CACHE_XML = 
".m2/discovered-toolchains-cache.xml";
+
+    private final Log log;
+
+    private Map<Path, ToolchainModel> cache;
+    private boolean cacheModified;
+
+    public ToolchainDiscoverer(Log log) {
+        this.log = log;
+    }
+
+    /**
+     * Build the model for the current JDK toolchain
+     */
+    public ToolchainModel getCurrentJdkToolchain() {
+        Path currentJdkHome = 
getCanonicalPath(Paths.get(System.getProperty("java.home")));
+        if (!Files.exists(currentJdkHome.resolve("bin/javac"))
+                && !Files.exists(currentJdkHome.resolve("bin/javac.exe"))) {
+            // in case the current JVM is not a JDK
+            return null;
+        }
+
+        ToolchainModel model = new ToolchainModel();
+        model.setType("jdk");
+        Stream.of("java.version", "java.runtime.name", "java.runtime.version", 
"java.vendor", "java.vendor.version")
+                .forEach(k -> {
+                    String v = System.getProperty(k);
+                    if (v != null) {
+                        model.addProvide(k.substring(5), v);
+                    }
+                });
+        model.addProvide("current", "true");
+        Xpp3Dom config = new Xpp3Dom("configuration");
+        Xpp3Dom jdkHome = new Xpp3Dom("jdkHome");
+        jdkHome.setValue(currentJdkHome.toString());
+        config.addChild(jdkHome);
+        model.setConfiguration(config);
+        return model;
+    }
+
+    /**
+     * Returns a PersistedToolchains object containing a list of discovered 
toolchains,
+     * never <code>null</code>.
+     */
+    public PersistedToolchains discoverToolchains() {
+        try {
+            Set<Path> jdks = findJdks();
+            log.info("Found " + jdks.size() + " possible jdks: " + jdks);
+            cacheModified = false;
+            readCache();
+            Path currentJdkHome = 
getCanonicalPath(Paths.get(System.getProperty("java.home")));
+            List<ToolchainModel> tcs = jdks.parallelStream()
+                    .map(s -> getToolchainModel(currentJdkHome, s))
+                    .filter(Objects::nonNull)
+                    .sorted(getToolchainModelComparator())
+                    .collect(Collectors.toList());
+            if (this.cacheModified) {
+                writeCache();
+            }
+            PersistedToolchains ps = new PersistedToolchains();
+            ps.setToolchains(tcs);
+            return ps;
+        } catch (Exception e) {
+            if (log.isDebugEnabled()) {
+                log.warn("Error discovering toolchains: " + e, e);
+            } else {
+                log.warn("Error discovering toolchains (enable debug level for 
more information): " + e);
+            }
+            return new PersistedToolchains();
+        }
+    }
+
+    private void readCache() {
+        try {
+            cache = new ConcurrentHashMap<>();
+            Path cacheFile = getCacheFile();
+            if (Files.isRegularFile(cacheFile)) {
+                try (Reader r = Files.newBufferedReader(cacheFile)) {
+                    PersistedToolchains pt = new 
MavenToolchainsXpp3Reader().read(r, false);
+                    cache = pt.getToolchains().stream()
+                            
.collect(Collectors.toConcurrentMap(this::getJdkHome, Function.identity()));
+                }
+            }
+        } catch (IOException | XmlPullParserException e) {
+            log.warn("Error reading toolchains cache: " + e);
+        }
+    }
+
+    private void writeCache() {
+        try {
+            Path cacheFile = getCacheFile();
+            Files.createDirectories(cacheFile.getParent());
+            try (Writer w = Files.newBufferedWriter(cacheFile)) {
+                PersistedToolchains pt = new PersistedToolchains();
+                List<ToolchainModel> toolchains = new ArrayList<>();
+                for (ToolchainModel tc : cache.values()) {
+                    tc = tc.clone();
+                    tc.getProvides().remove("current");
+                    toolchains.add(tc);
+                }
+                pt.setToolchains(toolchains);
+                new MavenToolchainsXpp3Writer().write(w, pt);
+            }
+        } catch (IOException e) {
+            log.warn("Error writing toolchains cache: " + e);
+        }
+    }
+
+    private static Path getCacheFile() {
+        return 
Paths.get(System.getProperty("user.home")).resolve(DISCOVERED_TOOLCHAINS_CACHE_XML);
+    }
+
+    private Path getJdkHome(ToolchainModel toolchain) {
+        Xpp3Dom dom = (Xpp3Dom) toolchain.getConfiguration();
+        Xpp3Dom javahome = dom != null ? dom.getChild("jdkHome") : null;
+        String jdk = javahome != null ? javahome.getValue() : null;
+        return Paths.get(Objects.requireNonNull(jdk));
+    }
+
+    ToolchainModel getToolchainModel(Path currentJdkHome, Path jdk) {
+        log.debug("Computing model for " + jdk);
+
+        ToolchainModel model = cache.get(jdk);
+        if (model == null) {
+            model = doGetToolchainModel(jdk);
+            cache.put(jdk, model);
+            cacheModified = true;
+        }
+
+        if (Objects.equals(jdk, currentJdkHome)) {
+            model.getProvides().setProperty("current", "true");
+        }
+        return model;
+    }
+
+    ToolchainModel doGetToolchainModel(Path jdk) {
+        Path bin = jdk.resolve("bin");
+        Path java = bin.resolve("java");
+        if (!java.toFile().canExecute()) {
+            java = bin.resolve("java.exe");
+            if (!java.toFile().canExecute()) {
+                log.debug("JDK toolchain discovered at " + jdk + " will be 
ignored: unable to find java executable");
+                return null;
+            }
+        }
+        List<String> lines;
+        try {
+            Path temp = Files.createTempFile("jdk-opts-", ".out");
+            try {
+                new ProcessBuilder()
+                        .command(java.toString(), "-XshowSettings:properties", 
"-version")
+                        .redirectError(temp.toFile())
+                        .start()
+                        .waitFor();
+                lines = Files.readAllLines(temp);
+            } finally {
+                Files.delete(temp);
+            }
+        } catch (IOException | InterruptedException e) {
+            log.debug("JDK toolchain discovered at " + jdk + " will be 
ignored: unable to execute java: " + e);
+            return null;
+        }
+
+        Map<String, String> properties = new LinkedHashMap<>();
+        for (String name : Arrays.asList(
+                "java.version", "java.runtime.name", "java.runtime.version", 
"java.vendor", "java.vendor.version")) {
+            String v = lines.stream()

Review Comment:
   v --> value; in general avoid single letter variable names



##########
src/main/java/org/apache/maven/plugins/toolchain/jdk/ToolchainDiscoverer.java:
##########
@@ -0,0 +1,332 @@
+/*
+ * 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.
+ */
+package org.apache.maven.plugins.toolchain.jdk;
+
+import java.io.IOException;
+import java.io.Reader;
+import java.io.Writer;
+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.Comparator;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import org.apache.maven.plugin.logging.Log;
+import org.apache.maven.toolchain.model.PersistedToolchains;
+import org.apache.maven.toolchain.model.ToolchainModel;
+import org.apache.maven.toolchain.model.io.xpp3.MavenToolchainsXpp3Reader;
+import org.apache.maven.toolchain.model.io.xpp3.MavenToolchainsXpp3Writer;
+import org.codehaus.plexus.util.xml.Xpp3Dom;
+import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
+
+/**
+ * Implementation of ToolchainDiscoverer service
+ */
+public class ToolchainDiscoverer {
+
+    private static final String DISCOVERED_TOOLCHAINS_CACHE_XML = 
".m2/discovered-toolchains-cache.xml";
+
+    private final Log log;
+
+    private Map<Path, ToolchainModel> cache;
+    private boolean cacheModified;
+
+    public ToolchainDiscoverer(Log log) {
+        this.log = log;
+    }
+
+    /**
+     * Build the model for the current JDK toolchain
+     */
+    public ToolchainModel getCurrentJdkToolchain() {
+        Path currentJdkHome = 
getCanonicalPath(Paths.get(System.getProperty("java.home")));
+        if (!Files.exists(currentJdkHome.resolve("bin/javac"))
+                && !Files.exists(currentJdkHome.resolve("bin/javac.exe"))) {
+            // in case the current JVM is not a JDK
+            return null;
+        }
+
+        ToolchainModel model = new ToolchainModel();
+        model.setType("jdk");
+        Stream.of("java.version", "java.runtime.name", "java.runtime.version", 
"java.vendor", "java.vendor.version")
+                .forEach(k -> {
+                    String v = System.getProperty(k);
+                    if (v != null) {
+                        model.addProvide(k.substring(5), v);
+                    }
+                });
+        model.addProvide("current", "true");
+        Xpp3Dom config = new Xpp3Dom("configuration");
+        Xpp3Dom jdkHome = new Xpp3Dom("jdkHome");
+        jdkHome.setValue(currentJdkHome.toString());
+        config.addChild(jdkHome);
+        model.setConfiguration(config);
+        return model;
+    }
+
+    /**
+     * Returns a PersistedToolchains object containing a list of discovered 
toolchains,
+     * never <code>null</code>.
+     */
+    public PersistedToolchains discoverToolchains() {
+        try {
+            Set<Path> jdks = findJdks();
+            log.info("Found " + jdks.size() + " possible jdks: " + jdks);
+            cacheModified = false;
+            readCache();
+            Path currentJdkHome = 
getCanonicalPath(Paths.get(System.getProperty("java.home")));
+            List<ToolchainModel> tcs = jdks.parallelStream()
+                    .map(s -> getToolchainModel(currentJdkHome, s))
+                    .filter(Objects::nonNull)
+                    .sorted(getToolchainModelComparator())
+                    .collect(Collectors.toList());
+            if (this.cacheModified) {
+                writeCache();
+            }
+            PersistedToolchains ps = new PersistedToolchains();
+            ps.setToolchains(tcs);
+            return ps;
+        } catch (Exception e) {
+            if (log.isDebugEnabled()) {
+                log.warn("Error discovering toolchains: " + e, e);
+            } else {
+                log.warn("Error discovering toolchains (enable debug level for 
more information): " + e);
+            }
+            return new PersistedToolchains();
+        }
+    }
+
+    private void readCache() {
+        try {
+            cache = new ConcurrentHashMap<>();
+            Path cacheFile = getCacheFile();
+            if (Files.isRegularFile(cacheFile)) {
+                try (Reader r = Files.newBufferedReader(cacheFile)) {
+                    PersistedToolchains pt = new 
MavenToolchainsXpp3Reader().read(r, false);
+                    cache = pt.getToolchains().stream()
+                            
.collect(Collectors.toConcurrentMap(this::getJdkHome, Function.identity()));
+                }
+            }
+        } catch (IOException | XmlPullParserException e) {
+            log.warn("Error reading toolchains cache: " + e);
+        }
+    }
+
+    private void writeCache() {
+        try {
+            Path cacheFile = getCacheFile();
+            Files.createDirectories(cacheFile.getParent());
+            try (Writer w = Files.newBufferedWriter(cacheFile)) {
+                PersistedToolchains pt = new PersistedToolchains();
+                List<ToolchainModel> toolchains = new ArrayList<>();
+                for (ToolchainModel tc : cache.values()) {
+                    tc = tc.clone();
+                    tc.getProvides().remove("current");
+                    toolchains.add(tc);
+                }
+                pt.setToolchains(toolchains);
+                new MavenToolchainsXpp3Writer().write(w, pt);
+            }
+        } catch (IOException e) {
+            log.warn("Error writing toolchains cache: " + e);
+        }
+    }
+
+    private static Path getCacheFile() {
+        return 
Paths.get(System.getProperty("user.home")).resolve(DISCOVERED_TOOLCHAINS_CACHE_XML);
+    }
+
+    private Path getJdkHome(ToolchainModel toolchain) {
+        Xpp3Dom dom = (Xpp3Dom) toolchain.getConfiguration();
+        Xpp3Dom javahome = dom != null ? dom.getChild("jdkHome") : null;
+        String jdk = javahome != null ? javahome.getValue() : null;
+        return Paths.get(Objects.requireNonNull(jdk));
+    }
+
+    ToolchainModel getToolchainModel(Path currentJdkHome, Path jdk) {
+        log.debug("Computing model for " + jdk);
+
+        ToolchainModel model = cache.get(jdk);
+        if (model == null) {
+            model = doGetToolchainModel(jdk);
+            cache.put(jdk, model);
+            cacheModified = true;
+        }
+
+        if (Objects.equals(jdk, currentJdkHome)) {
+            model.getProvides().setProperty("current", "true");
+        }
+        return model;
+    }
+
+    ToolchainModel doGetToolchainModel(Path jdk) {
+        Path bin = jdk.resolve("bin");
+        Path java = bin.resolve("java");
+        if (!java.toFile().canExecute()) {
+            java = bin.resolve("java.exe");
+            if (!java.toFile().canExecute()) {
+                log.debug("JDK toolchain discovered at " + jdk + " will be 
ignored: unable to find java executable");
+                return null;
+            }
+        }
+        List<String> lines;
+        try {
+            Path temp = Files.createTempFile("jdk-opts-", ".out");
+            try {
+                new ProcessBuilder()
+                        .command(java.toString(), "-XshowSettings:properties", 
"-version")
+                        .redirectError(temp.toFile())
+                        .start()
+                        .waitFor();
+                lines = Files.readAllLines(temp);
+            } finally {
+                Files.delete(temp);
+            }
+        } catch (IOException | InterruptedException e) {
+            log.debug("JDK toolchain discovered at " + jdk + " will be 
ignored: unable to execute java: " + e);
+            return null;
+        }
+
+        Map<String, String> properties = new LinkedHashMap<>();
+        for (String name : Arrays.asList(
+                "java.version", "java.runtime.name", "java.runtime.version", 
"java.vendor", "java.vendor.version")) {
+            String v = lines.stream()
+                    .filter(l -> l.contains(name))
+                    .map(l -> l.replaceFirst(".*=\\s*(.*)", "$1"))
+                    .findFirst()
+                    .orElse(null);
+            String k = name.substring(5);

Review Comment:
   k --> ????



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscr...@maven.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to