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.cli;
20  
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.text.SimpleDateFormat;
24  import java.util.Date;
25  import java.util.Locale;
26  import java.util.Properties;
27  
28  import org.apache.maven.cli.jline.MessageUtils;
29  import org.apache.maven.utils.Os;
30  import org.slf4j.Logger;
31  
32  /**
33   * Utility class used to report errors, statistics, application version info, etc.
34   *
35   */
36  public final class CLIReportingUtils {
37      // CHECKSTYLE_OFF: MagicNumber
38      public static final long MB = 1024 * 1024;
39  
40      private static final long ONE_SECOND = 1000L;
41  
42      private static final long ONE_MINUTE = 60 * ONE_SECOND;
43  
44      private static final long ONE_HOUR = 60 * ONE_MINUTE;
45  
46      private static final long ONE_DAY = 24 * ONE_HOUR;
47      // CHECKSTYLE_ON: MagicNumber
48  
49      public static final String BUILD_VERSION_PROPERTY = "version";
50  
51      public static String showVersion() {
52          final String ls = System.lineSeparator();
53          Properties properties = getBuildProperties();
54          StringBuilder version = new StringBuilder(256);
55          version.append(MessageUtils.builder().strong(createMavenVersionString(properties)))
56                  .append(ls);
57          version.append(reduce(properties.getProperty("distributionShortName") + " home: "
58                          + System.getProperty("maven.home", "<unknown Maven " + "home>")))
59                  .append(ls);
60          version.append("Java version: ")
61                  .append(System.getProperty("java.version", "<unknown Java version>"))
62                  .append(", vendor: ")
63                  .append(System.getProperty("java.vendor", "<unknown vendor>"))
64                  .append(", runtime: ")
65                  .append(System.getProperty("java.home", "<unknown runtime>"))
66                  .append(ls);
67          version.append("Default locale: ")
68                  .append(Locale.getDefault())
69                  .append(", platform encoding: ")
70                  .append(System.getProperty("file.encoding", "<unknown encoding>"))
71                  .append(ls);
72          version.append("OS name: \"")
73                  .append(Os.OS_NAME)
74                  .append("\", version: \"")
75                  .append(Os.OS_VERSION)
76                  .append("\", arch: \"")
77                  .append(Os.OS_ARCH)
78                  .append("\", family: \"")
79                  .append(Os.OS_FAMILY)
80                  .append('\"');
81          return version.toString();
82      }
83  
84      public static String showVersionMinimal() {
85          Properties properties = getBuildProperties();
86          String version = reduce(properties.getProperty(BUILD_VERSION_PROPERTY));
87          return (version != null ? version : "<version unknown>");
88      }
89  
90      /**
91       * Create a human-readable string containing the Maven version, buildnumber, and time of build
92       *
93       * @param buildProperties The build properties
94       * @return Readable build info
95       */
96      static String createMavenVersionString(Properties buildProperties) {
97          String timestamp = reduce(buildProperties.getProperty("timestamp"));
98          String version = reduce(buildProperties.getProperty(BUILD_VERSION_PROPERTY));
99          String rev = reduce(buildProperties.getProperty("buildNumber"));
100         String distributionName = reduce(buildProperties.getProperty("distributionName"));
101 
102         String msg = distributionName + " ";
103         msg += (version != null ? version : "<version unknown>");
104         if (rev != null || timestamp != null) {
105             msg += " (";
106             msg += (rev != null ? rev : "");
107             if (timestamp != null && !timestamp.isEmpty()) {
108                 String ts = formatTimestamp(Long.parseLong(timestamp));
109                 msg += (rev != null ? "; " : "") + ts;
110             }
111             msg += ")";
112         }
113         return msg;
114     }
115 
116     private static String reduce(String s) {
117         return (s != null ? (s.startsWith("${") && s.endsWith("}") ? null : s) : null);
118     }
119 
120     static Properties getBuildProperties() {
121         Properties properties = new Properties();
122 
123         try (InputStream resourceAsStream =
124                 MavenCli.class.getResourceAsStream("/org/apache/maven/messages/build.properties")) {
125 
126             if (resourceAsStream != null) {
127                 properties.load(resourceAsStream);
128             }
129         } catch (IOException e) {
130             System.err.println("Unable determine version from JAR file: " + e.getMessage());
131         }
132 
133         return properties;
134     }
135 
136     public static void showError(Logger logger, String message, Throwable e, boolean showStackTrace) {
137         if (logger == null) {
138             System.err.println(message);
139             if (showStackTrace && e != null) {
140                 e.printStackTrace(System.err);
141             }
142             return;
143         }
144         if (showStackTrace) {
145             logger.error(message, e);
146         } else {
147             logger.error(message);
148 
149             if (e != null) {
150                 logger.error(e.getMessage());
151 
152                 for (Throwable cause = e.getCause();
153                         cause != null && cause != cause.getCause();
154                         cause = cause.getCause()) {
155                     logger.error("Caused by: {}", cause.getMessage());
156                 }
157             }
158         }
159     }
160 
161     public static String formatTimestamp(long timestamp) {
162         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
163         return sdf.format(new Date(timestamp));
164     }
165 
166     public static String formatDuration(long duration) {
167         // CHECKSTYLE_OFF: MagicNumber
168         long ms = duration % 1000;
169         long s = (duration / ONE_SECOND) % 60;
170         long m = (duration / ONE_MINUTE) % 60;
171         long h = (duration / ONE_HOUR) % 24;
172         long d = duration / ONE_DAY;
173         // CHECKSTYLE_ON: MagicNumber
174 
175         String format;
176         if (d > 0) {
177             // Length 11+ chars
178             format = "%d d %02d:%02d h";
179         } else if (h > 0) {
180             // Length 7 chars
181             format = "%2$02d:%3$02d h";
182         } else if (m > 0) {
183             // Length 9 chars
184             format = "%3$02d:%4$02d min";
185         } else {
186             // Length 7-8 chars
187             format = "%4$d.%5$03d s";
188         }
189 
190         return String.format(format, d, h, m, s, ms);
191     }
192 }