maven-assembly-plugin中的檔案合併處理
阿新 • • 發佈:2020-08-13
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>