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