View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.plugins.artifact.buildinfo;
20  
21  import java.io.IOException;
22  import java.util.ArrayList;
23  import java.util.List;
24  
25  import org.apache.maven.shared.utils.StringUtils;
26  import org.apache.maven.shared.utils.cli.CommandLineException;
27  import org.apache.maven.shared.utils.cli.CommandLineUtils;
28  import org.apache.maven.shared.utils.cli.Commandline;
29  import org.apache.maven.shared.utils.cli.StreamConsumer;
30  import org.apache.maven.toolchain.Toolchain;
31  
32  /**
33   * A helper to get JDK version from a JDK toolchain.
34   */
35  class JdkToolchainUtil {
36      static String getJavaVersion(Toolchain toolchain) {
37          String version = "unknown";
38          String java = toolchain.findTool("java");
39          if (java != null) {
40              try {
41                  Commandline cl = new Commandline(java + " -version");
42                  LineConsumer out = new LineConsumer();
43                  LineConsumer err = new LineConsumer();
44                  CommandLineUtils.executeCommandLine(cl, out, err);
45                  version = StringUtils.join(err.getLines().iterator(), ":");
46                  if (StringUtils.isEmpty(version)) {
47                      version = "unable to detect...";
48                  }
49              } catch (CommandLineException cle) {
50                  version = cle.toString();
51              }
52          }
53          return version;
54      }
55  
56      private static class LineConsumer implements StreamConsumer {
57          private final List<String> lines = new ArrayList<>();
58  
59          @Override
60          public void consumeLine(String line) throws IOException {
61              lines.add(line);
62          }
63  
64          List<String> getLines() {
65              return lines;
66          }
67      }
68  }