Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package org.codehaus.mojo.rpm;
  
  /*
   * 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;
 import java.util.Set;
 
Utility to interact with files (source, dependencies, artifacts, etc.).

Author(s):
Brett Okken
Since:
2.0
 
 final class FileHelper
 {
     private static final List<StringEMPTY_STRING_LIST = new ArrayList<String>();

    
Message for exception indicating that a Source has a destination, but refers to a directory.
 
     private static final String DESTINATION_DIRECTORY_ERROR_MSG =
         "Source has a destination [{0}], but the location [{1}] does not refer to a file.";

    
Pattern to identify macros.

Since:
2.1-alpha-1
 
     private static final Pattern MACRO_PATTERN = Pattern.compile"%\\{([^}]*)\\}" );

    
A Plexus component to copy files and directories. Using our own custom version of the DirectoryArchiver to allow filtering of files.
 
     private final FilteringDirectoryArchiver copier;
 
     private final AbstractRPMMojo mojo;

    

Parameters:
mojo
copier
 
     public FileHelperAbstractRPMMojo mojoFilteringDirectoryArchiver copier )
     {
         super();
         this. = mojo;
         this. = copier;
     }

    
Copy the files from the various mapping sources into the build root.

 
     public void installFiles()
     {
         final File workarea = .getWorkarea();
         final File buildroot = .getBuildroot();
 
         final File icon = .getIcon();
         // Copy icon, if specified
         if ( icon != null )
        {
            File icondest = new Fileworkarea"SOURCES" );
            copySourceiconnullicondestnullnullfalsefalse );
        }
        final Log log = .getLog();
        // Process each mapping
        for ( Mapping map : .getMappings() )
        {
            final String destinationString = map.getDestination();
            final String macroEvaluatedDestination = evaluateMacrosdestinationString );
            File dest = new FilebuildrootmacroEvaluatedDestination );
            map.setAbsoluteDestinationdest );
            if ( map.isDirOnly() )
            {
                // Build the output directory if it doesn't exist
                if ( !dest.exists() )
                {
                    log.info"Creating empty directory " + dest.getAbsolutePath() );
                    if ( !dest.mkdirs() )
                    {
                        throw new MojoExecutionException"Unable to create " + dest.getAbsolutePath() );
                    }
                }
            }
            else
            {
                processSourcesmapdest );
                ArtifactMap art = map.getArtifact();
                if ( art != null )
                {
                    List<Artifactartlist = selectArtifactsart );
                    for ( Artifact artifactInstance : artlist )
                    {
                        copyArtifactartifactInstancedestfalse );
                        map.addCopiedFileNameRelativeToDestinationartifactInstance.getFile().getName() );
                    }
                }
                Dependency dep = map.getDependency();
                if ( dep != null )
                {
                    List<Artifactdeplist = selectDependenciesdep );
                    for ( Artifact artifactInstance : deplist )
                    {
                        // pass in dependency stripVersion parameter
                        String outputFileName = copyArtifactartifactInstancedestdep.getStripVersion() );
                        map.addCopiedFileNameRelativeToDestinationoutputFileName );
                    }
                }
                if ( map.getCopiedFileNamesRelativeToDestination().isEmpty() )
                {
                    log.info"Mapping empty with destination: " + dest.getName() );
                    // Build the output directory if it doesn't exist
                    if ( !dest.exists() )
                    {
                        log.info"Creating empty directory " + dest.getAbsolutePath() );
                        if ( !dest.mkdirs() )
                        {
                            throw new MojoExecutionException"Unable to create " + dest.getAbsolutePath() );
                        }
                    }
                }
            }
        }
    }

    
Copy a set of files.

Parameters:
src The file or directory to start copying from
srcName The src file name to be used in the copy, only used if the src is not a directory.
dest The destination directory
incl The list of inclusions
excl The list of exclusions
filter Indicates if the file(s) being copied should be filtered.
Returns:
List of file names, relative to dest, copied to dest.
Throws:
org.apache.maven.plugin.MojoExecutionException if a problem occurs
    private List<StringcopySourceFile srcString srcNameFile destList<StringinclList<Stringexcl,
                                     boolean filterboolean dontUseDefaultExcludes )
        throws MojoExecutionException
    {
        try
        {
            // Set the destination
            .setDestFiledest );
            // Set the source
            if ( src.isDirectory() )
            {
                String[] ia = null;
                if ( incl != null )
                {
                    ia = incl.toArraynew String[0] );
                }
                String[] ea = null;
                if ( excl != null )
                {
                    ea = excl.toArraynew String[0] );
                }
                // same as copier.addDirectory( src, "", ia, ea ) with dontUseDefaultExcludes
                DefaultFileSet fileset = new DefaultFileSetsrc );
                fileset.setPrefix"" );
                fileset.setIncludesia );
                fileset.setExcludesea );
                fileset.setIncludingEmptyDirectories.getIncludeEmptyDirs() );
                fileset.setUsingDefaultExcludes( !dontUseDefaultExcludes );
                .addFileSetfileset );
            }
            else
            {
                // set srcName to default if null
                srcName = srcName != null ? srcName : src.getName();
                .addFilesrcsrcName );
            }
            .setFilterfilter );
            .setFilterWrappers.getFilterWrappers() );
            Map<StringArchiveEntrycopiedFilesMap = .getFiles();
            // Perform the copy
            .createArchive();
            List<StringcopiedFiles = new ArrayList<String>( copiedFilesMap.size() );
            for ( String key : copiedFilesMap.keySet() )
            {
                if ( key != null && key.length() > 0 )
                {
                    copiedFiles.addkey );
                }
            }
            // Clear the list for the next mapping
            .resetArchiver();
            return copiedFiles;
        }
        catch ( Throwable t )
        {
            throw new MojoExecutionException"Unable to copy files for packaging: " + t.getMessage(), t );
        }
    }
    public static DefaultFileSet fileSetFile directory )
    {
        final DefaultFileSet defaultFileSet = new DefaultFileSetdirectory );
        return defaultFileSet;
    }

    
Copy an artifact.

Parameters:
art The artifact to copy
dest The destination directory
stripVersion Whether or not to strip the artifact version from the filename
Returns:
Artifact file name
Throws:
org.apache.maven.plugin.MojoExecutionException if a problem occurs
    private String copyArtifactArtifact artFile destboolean stripVersion )
        throws MojoExecutionException
    {
        if ( art.getFile() == null )
        {
            final Log log = .getLog();
            log.warn"Artifact " + art + " requested in configuration." );
            log.warn"Plugin must be run in Maven's build lifecycle for this to work." );
            throw new MojoExecutionException"Unable to resolve artifact." );
        }
        String outputFileName;
        if ( stripVersion )
        {
            final String classifier = art.getClassifier();
            // strip the version from the file name
            outputFileName = art.getArtifactId();
            if ( classifier != null )
            {
                outputFileName += '-';
                outputFileName += classifier;
            }
            outputFileName += '.';
            outputFileName += art.getType();
        }
        else
        {
            outputFileName = art.getFile().getName();
        }
        copySourceart.getFile(), outputFileNamedestnullnullfalsefalse );
        return outputFileName;
    }

    
Make a list of the artifacts to package in this mapping.

Parameters:
am The artifact mapping information
Returns:
The list of artifacts to package
    private List<ArtifactselectArtifactsArtifactMap am )
    {
        final List<Artifactretval = new ArrayList<Artifact>();
        final List<Stringclist = am.getClassifiers();
        final Artifact artifact = .getArtifact();
        final List<ArtifactattachedArtifacts = .getAttachedArtifacts();
        if ( clist == null )
        {
            retval.addartifact );
            retval.addAllattachedArtifacts );
        }
        else
        {
            if ( clist.containsnull ) )
            {
                retval.addartifact );
            }
            for ( Artifact aa : attachedArtifacts )
            {
                if ( ( aa.hasClassifier() ) && ( clist.containsaa.getClassifier() ) ) )
                {
                    retval.addaa );
                }
            }
        }
        return retval;
    }

    
Make a list of the dependencies to package in this mapping.

Parameters:
d The artifact mapping information
Returns:
The list of artifacts to package
    private List<ArtifactselectDependenciesDependency d )
    {
        List<Artifactretval = new ArrayList<Artifact>();
        List<Artifactinc = d.getIncludes();
        List<Artifactexc = d.getExcludes();
        @SuppressWarnings"unchecked" )
        Set<Artifactdeps = ..getArtifacts();
        if ( deps == null || deps.isEmpty() )
        {
            return retval;
        }
        final Log log = .getLog();
        for ( Artifact pdep : deps )
        {
            log.debug"Dependency is " + pdep + " at " + pdep.getFile() );
            if ( !depMatcherpdepexc ) )
            {
                log.debug"--> not excluded" );
                if ( ( inc == null ) || ( depMatcherpdepinc ) ) )
                {
                    log.debug"--> included" );
                    retval.addpdep );
                }
            }
        }
        return retval;
    }

    
Installs the sources to dest

Parameters:
map The Mapping to process the sources for.
dest The destination directory for the sources.
Throws:
org.apache.maven.plugin.MojoExecutionException
org.apache.maven.plugin.MojoFailureException
    private void processSourcesMapping mapFile dest )
    {
        if ( !dest.exists() )
        {
            if ( !dest.mkdirs() )
            {
                throw new MojoExecutionException"unable to create directory: " + dest.getAbsolutePath() );
            }
        }
        String relativeDestination = map.getDestination();
        if ( !relativeDestination.endsWith. ) )
        {
            relativeDestination += .;
        }
        List<Sourcesrcs = map.getSources();
        if ( srcs != null )
        {
            // for passivity, we will always use lowercase representation of architecture
            // for comparison purposes.
            final String targetArchComparison = .getTargetArch().toLowerCase. );
            final String targetOS = .getTargetOS();
            final Map<StringList<SoftlinkSource>> linkTargetToSources = .getLinkTargetToSources();
            // it is important that for each Source we set the files that are "installed".
            for ( Source src : srcs )
            {
                if ( !src.matchesArchitecturetargetArchComparison ) )
                {
                    .getLog().debug"Source does not match target architecture: " + src.toString() );
                    continue;
                }
                if ( !src.matchesOSNametargetOS ) )
                {
                    .getLog().debug"Source does not match target os name: " + src.toString() );
                    continue;
                }
                final File macroEvaluatedLocation = new FileevaluateMacrossrc.getLocation() ) );
                src.setMacroEvaluatedLocationmacroEvaluatedLocation.getPath() );
                final File locationFile =
                    macroEvaluatedLocation.isAbsolute() ? macroEvaluatedLocation
                                    : new File..getBasedir(), macroEvaluatedLocation.getPath() );
                // better with just macroEvaluatedLocation.getAbsoluteFile(), but not tested yet
                // it is important that we check if softlink source first as the "location" may
                // exist in the filesystem of the build machine
                if ( src instanceof SoftlinkSource )
                {
                    SoftlinkSource softlinkSource = (SoftlinkSourcesrc;
                    List<SoftlinkSourcesources = linkTargetToSources.getrelativeDestination );
                    if ( sources == null )
                    {
                        sources = new LinkedList<SoftlinkSource>();
                        linkTargetToSources.putrelativeDestinationsources );
                    }
                    sources.addsoftlinkSource );
                    softlinkSource.setSourceMappingmap );
                    map.setHasSoftLinkstrue );
                }
                else if ( locationFile.exists() )
                {
                    final String destination = src.getDestination();
                    if ( destination == null )
                    {
                        map.addCopiedFileNamesRelativeToDestinationcopySourcelocationFilenulldest,
                                                                                 src.getIncludes(), src.getExcludes(),
                                                                                 src.isFilter(),
                                                                                 src.getNoDefaultExcludes() ) );
                    }
                    else
                    {
                        if ( !locationFile.isFile() )
                        {
                            throw new MojoExecutionException( MessageFormat.format,
                                                                                    new Object[] { destination,
                                                                                        macroEvaluatedLocation } ) );
                        }
                        copySourcelocationFiledestinationdest,
                                    src.isFilter(), src.getNoDefaultExcludes() );
                        map.addCopiedFileNameRelativeToDestinationdestination );
                    }
                }
                else if ( !src.getFailIfLocationNotExists() )
                {
                    .getLog().warn"Source location " + macroEvaluatedLocation
                                            + " does not exist, but failIfLocationNotExist was set to false" );
                }
                else
                {
                    throw new MojoExecutionException"Source location " + macroEvaluatedLocation + " does not exist" );
                }
            }
        }
    }

    
Determine if there are any macros in the value and replace any/all occurrences with the evaluated value.

Parameters:
value String to replace macros in.
Returns:
Result of evaluating all macros in value.
Throws:
org.apache.maven.plugin.MojoExecutionException
Since:
2.1-alpha-1
    private String evaluateMacrosString value )
        throws MojoExecutionException
    {
        final Matcher matcher = .matchervalue );
        final StringBuffer newValue = new StringBuffervalue.length() );
        while ( matcher.find() )
        {
            final String macro = matcher.group( 1 );
            final String evaluatedValue = .evaluateMacromacro );
            matcher.appendReplacementnewValueevaluatedValue.replaceAll"\\\\""\\\\\\\\" ) );
        }
        matcher.appendTailnewValue );
        return newValue.toString();
    }

    
Determine if the dependency matches an include or exclude list.

Parameters:
dep The dependency to check
list The list to check against
Returns:
true if the dependency was found on the list
    private boolean depMatcherArtifact depList<Artifactlist )
    {
        if ( list == null )
        {
            // No list, not possible to match
            return false;
        }
        final Log log = .getLog();
        for ( Artifact item : list )
        {
            log.debug"Compare " + dep + " to " + item );
            final String groupId = item.getGroupId();
            if ( StringUtils.isEmptygroupId ) || "*".equalsgroupId ) || groupId.equalsdep.getGroupId() ) )
            {
                log.debug"... Group matches" );
                final String artifactId = item.getArtifactId();
                if ( StringUtils.isEmptyartifactId ) || "*".equalsartifactId )
                    || artifactId.equalsdep.getArtifactId() ) )
                {
                    log.debug"... Artifact matches" );
                    // ArtifactVersion av = item.getVersionRange().matchVersion( dep.getAvailableVersions() );
                    try
                    {
                        if ( item.getVersionRange().containsVersiondep.getSelectedVersion() ) )
                        {
                            log.debug"... Version matches" );
                            return true;
                        }
                    }
                    catch ( OverConstrainedVersionException ocve )
                    {
                        log.debug"... caught OverConstrainedVersionException" );
                    }
                }
            }
        }
        // Not found
        return false;
    }
    //
    // Convenient utils to convert to cygwin if needed
    //
    public static final String UNIX_FILE_SEPARATOR = "/";
    public static String toUnixPathFile path )
    {
        return toUnixPathpath.getAbsolutePath() );
    }
    public static String toUnixPathString path )
    {
        path = StringUtils.replacepath"\\""/" );
        String[] tokens = StringUtils.splitpath":" );
        if ( tokens.length == 2 && tokens[0].length() == 1 )
        {
            StringBuilder buffer = new StringBuilder();
            buffer.append"/cygdrive/" ).appendtokens[0] ).appendtokens[1] );
            path = buffer.toString();
        }
        return path;
    }
New to GrepCode? Check out our FAQ X