Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.apache.maven.plugins.help;
  
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you under the Apache License, Version 2.0 (the
   * "License"); you may not use this file except in compliance
  * with the License.  You may obtain a copy of the License at
  *
  *   http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing,
  * software distributed under the License is distributed on an
  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  * KIND, either express or implied.  See the License for the
  * specific language governing permissions and limitations
  * under the License.
  */
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 
 
Evaluates Maven expressions given by the user in an interactive mode.

Author(s):
Vincent Siveton
Version:
$Id: EvaluateMojo.java 926029 2010-03-22 11:07:32Z bentmann $
Since:
2.1
Goal:
evaluate
RequiresProject:
false
 
 public class EvaluateMojo
     extends AbstractMojo
 {
     // ----------------------------------------------------------------------
     // Mojo components
     // ----------------------------------------------------------------------
 
    
Maven Artifact Factory component.

Component:
 
     private ArtifactFactory artifactFactory;

    
Input handler, needed for command line handling.

Component:
 
     private InputHandler inputHandler;

    
Maven Project Builder component.

Component:
    private MavenProjectBuilder mavenProjectBuilder;

    

Component:
    private PathTranslator pathTranslator;

    
Artifact Resolver component.

Component:
    private ArtifactResolver resolver;

    

Component:
    // ----------------------------------------------------------------------
    // Mojo parameters
    // ----------------------------------------------------------------------

    
An artifact for evaluating Maven expressions.
Note: Should respect the Maven format, i.e. groupId:artifactId[:version][:classifier].

Parameter:
expression="${artifact}"
    private String artifact;

    
An expression to evaluate instead of prompting. Note that this must not include the surrounding ${...}.

Parameter:
expression="${expression}"
    private String expression;

    
Local Repository.

Parameter:
expression="${localRepository}"
Required:
Readonly:
    protected ArtifactRepository localRepository;

    
The current Maven project or the super pom.

Parameter:
expression="${project}"
Readonly:
Required:
    protected MavenProject project;

    
Remote repositories used for the project.

Parameter:
expression="${project.remoteArtifactRepositories}"
Readonly:
Required:
    private List remoteRepositories;

    
The system settings for Maven.

Parameter:
expression="${settings}"
Readonly:
Required:
    protected Settings settings;

    
The current Maven session.

Parameter:
expression="${session}"
Required:
Readonly:
    private MavenSession session;
    // ----------------------------------------------------------------------
    // Instance variables
    // ----------------------------------------------------------------------

    
lazy loading evaluator variable
lazy loading xstream variable
    private XStream xstream;
    // ----------------------------------------------------------------------
    // Public methods
    // ----------------------------------------------------------------------

    
    public void execute()
    {
        if (  == null && !.isInteractiveMode() )
        {
            StringBuffer msg = new StringBuffer();
            msg.append"Maven is configured to NOT interact with the user for input. " );
            msg.append"This Mojo requires that 'interactiveMode' in your settings file is flag to 'true'." );
            getLog().errormsg.toString() );
            return;
        }
        validateParameters();
        if ( StringUtils.isNotEmpty ) )
        {
            Artifact artifactObj = getArtifact );
            try
            {
                 = getMavenProjectartifactObj );
            }
            catch ( ProjectBuildingException e )
            {
                throw new MojoExecutionException"Unable to get the POM for the artifact '" + 
                    + "'. Verify the artifact parameter." );
            }
        }
        if (  == null )
        {
            while ( true )
            {
                getLog().info"Enter the Maven expression i.e. ${project.groupId} or 0 to exit?:" );
                try
                {
                    String userExpression = .readLine();
                    if ( userExpression == null || userExpression.toLowerCase. ).equals"0" ) )
                    {
                        break;
                    }
                    handleResponseuserExpression );
                }
                catch ( IOException e )
                {
                    throw new MojoExecutionException"Unable to read from standard input."e );
                }
            }
        }
        else
        {
            handleResponse"${" +  + "}" );
        }
    }
    // ----------------------------------------------------------------------
    // Private methods
    // ----------------------------------------------------------------------

    
Validate Mojo parameters.
    private void validateParameters()
    {
        if (  == null )
        {
            // using project if found or super-pom
            getLog().info"No artifact parameter specified, using '" + .getId() + "' as project." );
        }
    }

    

Parameters:
artifactString should respect the format groupId:artifactId[:version][:classifier]
Returns:
the Artifact object for the artifactString parameter.
Throws:
org.apache.maven.plugin.MojoExecutionException if the artifactString doesn't respect the format.
    private Artifact getArtifactString artifactString )
        throws MojoExecutionException
    {
        if ( StringUtils.isEmptyartifactString ) )
        {
            throw new IllegalArgumentException"artifact parameter could not be empty" );
        }
        String groupId = null// required
        String artifactId = null// required
        String version = null// optional
        String classifier = null// optional
        String[] artifactParts = artifactString.split":" );
        switch ( artifactParts.length )
        {
            case ( 2 ):
                groupId = artifactParts[0];
                artifactId = artifactParts[1];
                version = .;
                break;
            case ( 3 ):
                groupId = artifactParts[0];
                artifactId = artifactParts[1];
                version = artifactParts[2];
                break;
            case ( 4 ):
                groupId = artifactParts[0];
                artifactId = artifactParts[1];
                version = artifactParts[2];
                classifier = artifactParts[3];
                break;
            default:
                throw new MojoExecutionException"The artifact parameter '" + artifactString
                    + "' should be conform to: " + "'groupId:artifactId[:version][:classifier]'." );
        }
        if ( StringUtils.isNotEmptyclassifier ) )
        {
            return .createArtifactWithClassifiergroupIdartifactIdversion"jar"classifier );
        }
        return .createArtifactgroupIdartifactIdversion."jar" );
    }

    

Parameters:
artifactObj not null
Returns:
the POM for the given artifact.
Throws:
org.apache.maven.plugin.MojoExecutionException if the artifact has a system scope.
org.apache.maven.project.ProjectBuildingException when building pom.
    private MavenProject getMavenProjectArtifact artifactObj )
    {
        if ( ..equalsartifactObj.getScope() ) )
        {
            throw new MojoExecutionException"System artifact is not be handled." );
        }
        Artifact copyArtifact = ArtifactUtils.copyArtifactartifactObj );
        if ( !"pom".equalscopyArtifact.getType() ) )
        {
            copyArtifact =
                .createProjectArtifactcopyArtifact.getGroupId(), copyArtifact.getArtifactId(),
                                                       copyArtifact.getVersion(), copyArtifact.getScope() );
        }
        return .buildFromRepositorycopyArtifact );
    }

    
    {
        if (  == null )
        {
            MojoDescriptor mojoDescriptor =
                HelpUtil.getMojoDescriptor"help:evaluate""help:evaluate"truefalse );
            MojoExecution mojoExecution = new MojoExecutionmojoDescriptor );
             =
                new PluginParameterExpressionEvaluatormojoExecution,
                                                        .getLogger(), ,
                                                        .getExecutionProperties() );
        }
        return ;
    }

    

Parameters:
expression the user expression asked.
Throws:
org.apache.maven.plugin.MojoExecutionException if any
org.apache.maven.plugin.MojoFailureException if any reflection exceptions occur or missing components.
    private void handleResponseString expression )
    {
        StringBuffer response = new StringBuffer();
        Object obj;
        try
        {
            obj = getEvaluator().evaluateexpression );
        }
        catch ( ExpressionEvaluationException e )
        {
            throw new MojoExecutionException"Error when evaluating the Maven expression"e );
        }
        if ( obj != null && expression.equalsobj.toString() ) )
        {
            getLog().warn"The Maven expression was invalid. Please use a valid expression." );
            return;
        }
        // handle null
        if ( obj == null )
        {
            response.append"null object or invalid expression" );
        }
        // handle primitives objects
        else if ( obj instanceof String )
        {
            response.appendobj.toString() );
        }
        else if ( obj instanceof Boolean )
        {
            response.appendobj.toString() );
        }
        else if ( obj instanceof Byte )
        {
            response.appendobj.toString() );
        }
        else if ( obj instanceof Character )
        {
            response.appendobj.toString() );
        }
        else if ( obj instanceof Double )
        {
            response.appendobj.toString() );
        }
        else if ( obj instanceof Float )
        {
            response.appendobj.toString() );
        }
        else if ( obj instanceof Integer )
        {
            response.appendobj.toString() );
        }
        else if ( obj instanceof Long )
        {
            response.appendobj.toString() );
        }
        else if ( obj instanceof Short )
        {
            response.appendobj.toString() );
        }
        // handle specific objects
        else if ( obj instanceof File )
        {
            File f = (Fileobj;
            response.appendf.getAbsolutePath() );
        }
        // handle Maven pom object
        else if ( obj instanceof MavenProject )
        {
            MavenProject projectAsked = (MavenProjectobj;
            StringWriter sWriter = new StringWriter();
            MavenXpp3Writer pomWriter = new MavenXpp3Writer();
            try
            {
                pomWriter.writesWriterprojectAsked.getModel() );
            }
            catch ( IOException e )
            {
                throw new MojoExecutionException"Error when writing pom"e );
            }
            response.appendsWriter.toString() );
        }
        // handle Maven Settings object
        else if ( obj instanceof Settings )
        {
            Settings settingsAsked = (Settingsobj;
            StringWriter sWriter = new StringWriter();
            SettingsXpp3Writer settingsWriter = new SettingsXpp3Writer();
            try
            {
                settingsWriter.writesWritersettingsAsked );
            }
            catch ( IOException e )
            {
                throw new MojoExecutionException"Error when writing settings"e );
            }
            response.appendsWriter.toString() );
        }
        else
        {
            // others Maven objects
            response.appendtoXMLexpressionobj ) );
        }
        getLog().info"\n" + response.toString() );
    }

    

Parameters:
expression the user expression.
obj a not null.
Returns:
the XML for the given object.
    private String toXMLString expressionObject obj )
    {
        XStream currentXStream = getXStream();
        // beautify list
        if ( obj instanceof List )
        {
            List list = (Listobj;
            if ( list.size() > 0 )
            {
                Object elt = list.iterator().next();
                String name = StringUtils.lowercaseFirstLetter( ClassUtils.getShortClassNameelt.getClass() ) );
                currentXStream.aliaspluralizename ), List.class );
            }
            else
            {
                // try to detect the alias from question
                if ( expression.indexOf"." ) != -1 )
                {
                    String name = expression.substringexpression.indexOf"." ) + 1, expression.indexOf"}" ) );
                    currentXStream.aliasnameList.class );
                }
            }
        }
        return currentXStream.toXMLobj );
    }

    

Returns:
lazy loading xstream object.
    private XStream getXStream()
    {
        if (  == null )
        {
             = new XStream();
            addAlias );
            // handle Properties a la Maven
            .registerConverternew PropertiesConverter()
            {
                
                public boolean canConvertClass type )
                {
                    return Properties.class == type;
                }

                
                public void marshalObject sourceHierarchicalStreamWriter writerMarshallingContext context )
                {
                    Properties properties = (Propertiessource;
                    Map map = new TreeMapproperties ); // sort
                    for ( Iterator iterator = map.entrySet().iterator(); iterator.hasNext(); )
                    {
                        Map.Entry entry = (Map.Entryiterator.next();
                        writer.startNodeentry.getKey().toString() );
                        writer.setValueentry.getValue().toString() );
                        writer.endNode();
                    }
                }
            } );
        }
        return ;
    }

    

Parameters:
xstreamObject not null
    private void addAliasXStream xstreamObject )
    {
        try
        {
            addAliasxstreamObjectgetMavenModelJarFile(), "org.apache.maven.model" );
            addAliasxstreamObjectgetMavenSettingsJarFile(), "org.apache.maven.settings" );
        }
        catch ( MojoExecutionException e )
        {
            if ( getLog().isDebugEnabled() )
            {
                getLog().debug"MojoExecutionException: " + e.getMessage(), e );
            }
        }
        catch ( ArtifactResolutionException e )
        {
            if ( getLog().isDebugEnabled() )
            {
                getLog().debug"ArtifactResolutionException: " + e.getMessage(), e );
            }
        }
        catch ( ArtifactNotFoundException e )
        {
            if ( getLog().isDebugEnabled() )
            {
                getLog().debug"ArtifactNotFoundException: " + e.getMessage(), e );
            }
        }
        catch ( ProjectBuildingException e )
        {
            if ( getLog().isDebugEnabled() )
            {
                getLog().debug"ProjectBuildingException: " + e.getMessage(), e );
            }
        }
        // TODO need to handle specific Maven objects like DefaultArtifact?
    }

    

Parameters:
xstreamObject not null
jarFile not null
packageFilter a package name to filter.
    private void addAliasXStream xstreamObjectFile jarFileString packageFilter )
    {
        JarInputStream jarStream = null;
        try
        {
            jarStream = new JarInputStreamnew FileInputStreamjarFile ) );
            JarEntry jarEntry = jarStream.getNextJarEntry();
            while ( jarEntry != null )
            {
                if ( jarEntry == null )
                {
                    break;
                }
                if ( jarEntry.getName().toLowerCase. ).endsWith".class" ) )
                {
                    String name = jarEntry.getName().substring( 0, jarEntry.getName().indexOf"." ) );
                    name = name.replaceAll"/""\\." );
                    if ( name.indexOfpackageFilter ) != -1 )
                    {
                        try
                        {
                            Class clazz = ClassUtils.getClassname );
                            String alias = StringUtils.lowercaseFirstLetter( ClassUtils.getShortClassNameclazz ) );
                            xstreamObject.aliasaliasclazz );
                            if ( !clazz.equalsModel.class ) )
                            {
                                xstreamObject.omitFieldclazz"modelEncoding" ); // unnecessary field
                            }
                        }
                        catch ( ClassNotFoundException e )
                        {
                            e.printStackTrace();
                        }
                    }
                }
                jarStream.closeEntry();
                jarEntry = jarStream.getNextJarEntry();
            }
        }
        catch ( IOException e )
        {
            if ( getLog().isDebugEnabled() )
            {
                getLog().debug"IOException: " + e.getMessage(), e );
            }
        }
        finally
        {
            IOUtil.closejarStream );
        }
    }

    
    private File getMavenModelJarFile()
    {
        return getArtifactFiletrue );
    }

    
    private File getMavenSettingsJarFile()
    {
        return getArtifactFilefalse );
    }

    

Parameters:
isPom true to lookup the maven-model artifact jar, false to lookup the maven-settings artifact jar.
Returns:
the org.apache.maven:maven-model|maven-settings artifact jar file for this current HelpPlugin pom.
Throws:
org.apache.maven.plugin.MojoExecutionException if any
org.apache.maven.project.ProjectBuildingException if any
org.apache.maven.artifact.resolver.ArtifactResolutionException if any
org.apache.maven.artifact.resolver.ArtifactNotFoundException if any
    private File getArtifactFileboolean isPom )
    {
        for ( Iterator it = getHelpPluginPom().getDependencies().iterator(); it.hasNext(); )
        {
            Dependency depependency = (Dependencyit.next();
            if ( !( depependency.getGroupId().equals"org.apache.maven" ) ) )
            {
                continue;
            }
            if ( isPom )
            {
                if ( !( depependency.getArtifactId().equals"maven-model" ) ) )
                {
                    continue;
                }
            }
            else
            {
                if ( !( depependency.getArtifactId().equals"maven-settings" ) ) )
                {
                    continue;
                }
            }
            Artifact mavenArtifact =
                getArtifactdepependency.getGroupId() + ":" + depependency.getArtifactId() + ":"
                    + depependency.getVersion() );
            .resolveAlwaysmavenArtifact );
            return mavenArtifact.getFile();
        }
        throw new MojoExecutionException"Unable to find the 'org.apache.maven:"
            + ( isPom ? "maven-model" : "maven-settings" ) + "' artifact" );
    }

    

Returns:
the Maven POM for the current help plugin
Throws:
org.apache.maven.plugin.MojoExecutionException if any
org.apache.maven.project.ProjectBuildingException if any
    private MavenProject getHelpPluginPom()
    {
        String resource = "META-INF/maven/org.apache.maven.plugins/maven-help-plugin/pom.properties";
        InputStream resourceAsStream = EvaluateMojo.class.getClassLoader().getResourceAsStreamresource );
        Artifact helpPluginArtifact = null;
        if ( resourceAsStream != null )
        {
            Properties properties = new Properties();
            try
            {
                properties.loadresourceAsStream );
            }
            catch ( IOException e )
            {
                if ( getLog().isDebugEnabled() )
                {
                    getLog().debug"IOException: " + e.getMessage(), e );
                }
            }
            String artifactString =
                properties.getProperty"groupId""unknown" ) + ":"
                    + properties.getProperty"artifactId""unknown" ) + ":"
                    + properties.getProperty"version""unknown" );
            helpPluginArtifact = getArtifactartifactString );
        }
        if ( helpPluginArtifact == null )
        {
            throw new MojoExecutionException"The help plugin artifact was not found." );
        }
        return getMavenProjecthelpPluginArtifact );
    }

    

Parameters:
name not null
Returns:
the plural of the name
    private static String pluralizeString name )
    {
        if ( StringUtils.isEmptyname ) )
        {
            throw new IllegalArgumentException"name is required" );
        }
        if ( name.endsWith"y" ) )
        {
            return name.substring( 0, name.length() - 1 ) + "ies";
        }
        else if ( name.endsWith"s" ) )
        {
            return name;
        }
        else
        {
            return name + "s";
        }
    }
New to GrepCode? Check out our FAQ X