ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

maven-assembly-plugin中的文件合并处理

2020-08-13 09:33:41  阅读:308  来源: 互联网

标签:assembly plugin org writer maven new import logger final



SimpleMergeFileDescriptorHandler.java


package org.apache.maven.plugins.assembly.filter;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
import org.codehaus.plexus.archiver.ArchiveEntry;
import org.apache.maven.plugins.assembly.filter.ContainerDescriptorHandler;
import org.apache.maven.plugins.assembly.utils.AssemblyFileUtils;
import org.codehaus.plexus.archiver.Archiver;
import org.codehaus.plexus.archiver.ArchiverException;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.components.io.fileselectors.FileInfo;
import org.codehaus.plexus.logging.LogEnabled;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.logging.console.ConsoleLogger;
import org.codehaus.plexus.util.IOUtil;
import org.apache.maven.plugins.annotations.InstantiationStrategy;
import javax.annotation.Nonnull;
import java.util.UUID;

@Component( role = ContainerDescriptorHandler.class, hint = "file-merge", instantiationStrategy = "per-lookup" )
public class SimpleMergeFileDescriptorHandler implements  ContainerDescriptorHandler, LogEnabled
{
    // component configuration.

    @SuppressWarnings( "FieldCanBeLocal" )
    private final String commentChars = "#";

    private final StringWriter aggregateWriter = new StringWriter();

    private final List<String> filenames = new ArrayList<>();

    // calculated, temporary values.

    private String filePattern;

    private String outputPath;

    private boolean overrideFilterAction;

    // injected by the container.

    private Logger logger;

    private Archiver archiver;

    private File temp;

    @Override
    public void finalizeArchiveCreation( final Archiver archiver )
    {
        checkConfig();

        if ( outputPath.endsWith( "/" ) )
        {
            throw new ArchiverException( "Cannot write aggregated properties to a directory. "
                    + "You must specify a file name in the outputPath configuration for this"
                    + " handler. (handler: " + getClass().getName() );
        }

        if ( outputPath.startsWith( "/" ) )
        {
            outputPath = outputPath.substring( 1 );
        }

        this.temp = writePropertiesFile();

        overrideFilterAction = true;

        archiver.addFile( temp, outputPath );
        this.archiver = archiver;
        overrideFilterAction = false;
    }

    private File writePropertiesFile()
    {
        File f;

        Writer writer = null;
        try
        {
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            f = File.createTempFile( "maven-assembly-plugin-" + uuid, "tmp" );
            f.deleteOnExit();

            writer = AssemblyFileUtils.isPropertyFile( f )
                    ? new OutputStreamWriter( new FileOutputStream( f , true), StandardCharsets.ISO_8859_1 )
                    : new OutputStreamWriter( new FileOutputStream( f , true) ); // Still platform encoding

            writer.write( commentChars + " Aggregated on " + new Date() + " from: " );

            for ( final String filename : filenames )
            {
                writer.write( "\n" + commentChars + " " + filename );
                //System.out.println("---------------------------------------------: >   " + filename);
                //logger.info("---------------------------------------------: >   " + filename);
            }

            writer.write( "\n\n" );
            //System.out.println(aggregateWriter.toString());
            //logger.info("---------------------------------------------: >   aggregateWriter: ");
            //logger.info(aggregateWriter.toString());
            writer.write( aggregateWriter.toString() );

            writer.close();
            writer = null;
        }
        catch ( final IOException e )
        {
            throw new ArchiverException(
                    "Error adding aggregated properties to finalize archive creation. Reason: " + e.getMessage(), e );
        }
        finally
        {
            IOUtil.close( writer );
        }

        return f;
    }

    private void writeFile(String content)
    {
      Writer writer = null;
        try
        {
            writer = AssemblyFileUtils.isPropertyFile( this.temp )
                    ? new OutputStreamWriter( new FileOutputStream( this.temp , true), StandardCharsets.ISO_8859_1 )
                    : new OutputStreamWriter( new FileOutputStream( this.temp, true ) );
            writer.write( content);
            writer.write( "\n");
            writer.close();
            writer = null;
        }
        catch ( final IOException e )
        {
            throw new ArchiverException(
                    "Error adding aggregated properties to finalize archive creation. Reason: " + e.getMessage(), e );
        }
        finally
        {
            IOUtil.close( writer );
        }

    }


    @Override
    public void finalizeArchiveExtraction( final UnArchiver unarchiver )
    {
      //logger.info("UnArchiver------------------------------------------------------>:  " + unarchiver.getDestFile().getAbsolutePath());
    }

    @Override
    public List<String> getVirtualFiles()
    {
        checkConfig();

        return Collections.singletonList( outputPath );
    }

    private List<Integer> writeFile = new LinkedList<Integer>();

    @Override
    public boolean isSelected( @Nonnull final FileInfo fileInfo )
            throws IOException
    {
        checkConfig();

        if ( overrideFilterAction )
        {
            return true;
        }

        String name = AssemblyFileUtils.normalizeFileInfo( fileInfo );

        if ( fileInfo.isFile() && name.matches( filePattern ) )
        {
            String content = readProperties( fileInfo );            
            filenames.add( name );
            //logger.info("---------------------------------------------: >   readfile: " + name);
            if(!writeFile.contains(content.hashCode())){
              writeFile(content);
              writeFile.add(content.hashCode());
              //logger.info(content);
              //logger.info("-------------------------: >   write this file : " + name);
            }            
            //logger.info("aggregateWriter Length:  " + content.length());
            return false;
        }
        return true;
    }

    private void checkConfig()
    {
        if ( filePattern == null || outputPath == null )
        {
            throw new IllegalStateException(
                    "You must configure filePattern and outputPath in your containerDescriptorHandler declaration." );
        }
    }

    private String readProperties( final FileInfo fileInfo )
            throws IOException
    {
        try ( StringWriter writer = new StringWriter();
              Reader reader = AssemblyFileUtils.isPropertyFile( fileInfo.getName() )
                      ? new InputStreamReader( fileInfo.getContents(), StandardCharsets.ISO_8859_1 )
                      : new InputStreamReader( fileInfo.getContents() ) ) // platform encoding
        {
            IOUtil.copy( reader, writer );
            final String content = writer.toString();
            //System.out.println(content);
            aggregateWriter.write( "\n" );
            //logger.info(content);
            aggregateWriter.write( content );
            return content;
        }
    }

    protected final Logger getLogger()
    {
        if ( logger == null )
        {
            logger = new ConsoleLogger( Logger.LEVEL_INFO, "" );
        }

        return logger;
    }

    @Override
    public void enableLogging( final Logger logger )
    {
        this.logger = logger;
    }

    @SuppressWarnings( "UnusedDeclaration" )
    public String getFilePattern()
    {
        return filePattern;
    }

    @SuppressWarnings( "UnusedDeclaration" )
    public void setFilePattern( final String filePattern )
    {
        this.filePattern = filePattern;
    }

    @SuppressWarnings( "UnusedDeclaration" )
    public String getOutputPath()
    {
        return outputPath;
    }

    @SuppressWarnings( "UnusedDeclaration" )
    public void setOutputPath( final String outputPath )
    {
        this.outputPath = outputPath;
    }

}


pom.xml

<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>3.2.0</version>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>GeoPublish</mainClass>
                        </manifest>
                    </archive>
                    <!--                    <descriptorRefs>-->
                    <!--                        <descriptorRef>jar-with-dependencies</descriptorRef>-->
                    <!--                    </descriptorRefs>-->
                    <descriptors>
                        <descriptor>src/assembly/assembly.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>


assembly.xml

<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd">
    <id>jar-with-all-dependencies</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <containerDescriptorHandlers>
        <containerDescriptorHandler>
            <handlerName>file-merge</handlerName>
            <configuration>
                <filePattern>.*reference.conf</filePattern>
                <outputPath>reference.conf</outputPath>
            </configuration>
        </containerDescriptorHandler>
<!--        <containerDescriptorHandler>-->
<!--            <handlerName>file-merge</handlerName>-->
<!--            <configuration>-->
<!--                <filePattern>.*application.conf</filePattern>-->
<!--                <outputPath>application.conf</outputPath>-->
<!--            </configuration>-->
<!--        </containerDescriptorHandler>-->
    </containerDescriptorHandlers>
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <useProjectArtifact>true</useProjectArtifact>
            <unpack>true</unpack>
            <scope>runtime</scope>
            <includes>
                <include>*:jar:*</include>
            </includes>
            <excludes>
                <exclude>*:sources</exclude>
                <exclude>*:javadoc</exclude>
            </excludes>
        </dependencySet>
    </dependencySets>
</assembly>

标签:assembly,plugin,org,writer,maven,new,import,logger,final
来源: https://www.cnblogs.com/gispathfinder/p/13494523.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有