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