001package org.apache.maven.cli;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *  http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import java.io.IOException;
023import java.io.InputStream;
024import java.util.Date;
025import java.util.Locale;
026import java.util.Properties;
027import java.util.TimeZone;
028
029import org.codehaus.plexus.util.IOUtil;
030import org.codehaus.plexus.util.Os;
031import org.slf4j.Logger;
032
033/**
034 * Utility class used to report errors, statistics, application version info, etc.
035 *
036 * @author jdcasey
037 *
038 */
039public final class CLIReportingUtils
040{
041    // CHECKSTYLE_OFF: MagicNumber
042    public static final long MB = 1024 * 1024;
043
044    private static final long ONE_SECOND = 1000L;
045    private static final long ONE_MINUTE = 60 * ONE_SECOND;
046    private static final long ONE_HOUR = 60 * ONE_MINUTE;
047    private static final long ONE_DAY = 24 * ONE_HOUR;
048    // CHECKSTYLE_ON: MagicNumber
049
050    public static final String BUILD_VERSION_PROPERTY = "version";
051
052    public static String showVersion()
053    {
054        final String ls = System.getProperty( "line.separator" );
055        Properties properties = getBuildProperties();
056        StringBuilder version = new StringBuilder();
057        version.append( createMavenVersionString( properties ) ).append( ls );
058        version.append( reduce( properties.getProperty( "distributionShortName" ) + " home: "
059                            + System.getProperty( "maven.home", "<unknown maven home>" ) ) ).append( ls );
060        version.append( "Java version: " ).append(
061            System.getProperty( "java.version", "<unknown java version>" ) ).append( ", vendor: " ).append(
062            System.getProperty( "java.vendor", "<unknown vendor>" ) ).append( ls );
063        version.append( "Java home: " ).append( System.getProperty( "java.home", "<unknown java home>" ) ).append( ls );
064        version.append( "Default locale: " ).append( Locale.getDefault() ).append( ", platform encoding: " ).append(
065            System.getProperty( "file.encoding", "<unknown encoding>" ) ).append( ls );
066        version.append( "OS name: \"" ).append( Os.OS_NAME ).append( "\", version: \"" ).append( Os.OS_VERSION ).append(
067            "\", arch: \"" ).append( Os.OS_ARCH ).append( "\", family: \"" ).append( Os.OS_FAMILY ).append( "\"" );
068        return version.toString();
069    }
070
071    /**
072     * Create a human readable string containing the Maven version, buildnumber, and time of build
073     *
074     * @param buildProperties The build properties
075     * @return Readable build info
076     */
077    static String createMavenVersionString( Properties buildProperties )
078    {
079        String timestamp = reduce( buildProperties.getProperty( "timestamp" ) );
080        String version = reduce( buildProperties.getProperty( BUILD_VERSION_PROPERTY ) );
081        String rev = reduce( buildProperties.getProperty( "buildNumber" ) );
082        String distributionName = reduce( buildProperties.getProperty( "distributionName" ) );
083
084        String msg = distributionName + " ";
085        msg += ( version != null ? version : "<version unknown>" );
086        if ( rev != null || timestamp != null )
087        {
088            msg += " (";
089            msg += ( rev != null ? rev : "" );
090            if ( timestamp != null )
091            {
092                String ts = formatTimestamp( Long.valueOf( timestamp ) );
093                msg += ( rev != null ? "; " : "" ) + ts;
094            }
095            msg += ")";
096        }
097        return msg;
098    }
099
100    private static String reduce( String s )
101    {
102        return ( s != null ? ( s.startsWith( "${" ) && s.endsWith( "}" ) ? null : s ) : null );
103    }
104
105    static Properties getBuildProperties()
106    {
107        Properties properties = new Properties();
108        InputStream resourceAsStream = null;
109        try
110        {
111            resourceAsStream = MavenCli.class.getResourceAsStream( "/org/apache/maven/messages/build.properties" );
112
113            if ( resourceAsStream != null )
114            {
115                properties.load( resourceAsStream );
116            }
117        }
118        catch ( IOException e )
119        {
120            System.err.println( "Unable determine version from JAR file: " + e.getMessage() );
121        }
122        finally
123        {
124            IOUtil.close( resourceAsStream );
125        }
126
127        return properties;
128    }
129
130    public static void showError( Logger logger, String message, Throwable e, boolean showStackTrace )
131    {
132        if ( showStackTrace )
133        {
134            logger.error( message, e );
135        }
136        else
137        {
138            logger.error( message );
139
140            if ( e != null )
141            {
142                logger.error( e.getMessage() );
143
144                for ( Throwable cause = e.getCause(); cause != null; cause = cause.getCause() )
145                {
146                    logger.error( "Caused by: " + cause.getMessage() );
147                }
148            }
149        }
150    }
151
152    public static String formatTimestamp( long timestamp )
153    {
154        // Manual construction of the tz offset because only Java 7 is aware of ISO 8601 time zones
155        TimeZone tz = TimeZone.getDefault();
156        int offset = tz.getRawOffset();
157
158        // Raw offset ignores DST, so check if we are in DST now and add the offset
159        if ( tz.inDaylightTime( new Date( timestamp ) ) )
160        {
161            offset += tz.getDSTSavings();
162        }
163
164        // CHECKSTYLE_OFF: MagicNumber
165        long m = Math.abs( ( offset / ONE_MINUTE ) % 60 );
166        long h = Math.abs( ( offset / ONE_HOUR ) % 24 );
167        // CHECKSTYLE_ON: MagicNumber
168
169        int offsetDir = (int) Math.signum( (float) offset );
170        char offsetSign = offsetDir >= 0 ? '+' : '-';
171        return String.format( "%tFT%<tT%s%02d:%02d", timestamp, offsetSign, h, m );
172    }
173
174    public static String formatDuration( long duration )
175    {
176        // CHECKSTYLE_OFF: MagicNumber
177        long ms = duration % 1000;
178        long s = ( duration / ONE_SECOND ) % 60;
179        long m = ( duration / ONE_MINUTE ) % 60;
180        long h = ( duration / ONE_HOUR ) % 24;
181        long d = duration / ONE_DAY;
182        // CHECKSTYLE_ON: MagicNumber
183
184        String format;
185        if ( d > 0 )
186        {
187            format = "%d d %02d:%02d h";
188        }
189        else if ( h > 0 )
190        {
191            format = "%2$02d:%3$02d h";
192        }
193        else if ( m > 0 )
194        {
195            format = "%3$02d:%4$02d min";
196        }
197        else
198        {
199            format = "%4$d.%5$03d s";
200        }
201
202        return String.format( format, d, h, m, s, ms );
203    }
204
205}