Maven best practice for creating ad hoc zip artifact

chad picture chad · Oct 20, 2011 · Viewed 47.1k times · Source

Assume that I need to manage an artifact that consists of an aribtrary folder / file structure rolled up as a zip archive. It's not clear to me how to accomplish this in Maven in a way that best fits "the Maven way."

I know that there is no "zip" packaging type. Does this mean there is no generic lifecycle in Maven to simply take what I have in the resources folder, zip it up, and install/deploy it to my repositories?

I'm looking for options, with evaluations of how each option satisifies my requirement to follow the maven way, as I do not wish to incur the obvious penalities of straying from the golden path . . .

Answer

Alexander Pogrebnyak picture Alexander Pogrebnyak · Oct 20, 2011

Decide what classifier you will use for your zip file, for sake of argument let's say it would be sample.

In your project create file assembly/sample.xml

Fill in assembly/sample.xml with something like this:

<?xml version="1.0" encoding="UTF-8"?>
<assembly
  xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="
    http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2
      http://maven.apache.org/xsd/assembly-1.1.2.xsd"
>
  <id>sample</id>
  <formats>
    <format>zip</format>
  </formats>
  <fileSets>
    <fileSet>
      <outputDirectory>/</outputDirectory>
      <directory>some/directory/in/your/project</directory>
    </fileSet>
  </fileSets>
  <!-- use this section if you want to package dependencies -->
  <dependencySets>
    <dependencySet>
      <outputDirectory>lib</outputDirectory>
      <excludes>
        <exclude>*:pom</exclude>
      </excludes>
      <useStrictFiltering>true</useStrictFiltering>
      <useProjectArtifact>false</useProjectArtifact>
      <scope>runtime</scope>
    </dependencySet>
  </dependencySets>
</assembly>

Add this to your pom's build section

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <id>create-distribution</id>
            <phase>package</phase>
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <descriptors>
                <descriptor>assembly/sample.xml</descriptor>
              </descriptors>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

As a result it should create and install you-project-name-VERSION-sample.zip.

I suggest you read chapter on assemblies from Sonatype's maven book: https://books.sonatype.com/mvnref-book/reference/assemblies.html

Also, read assembly format specification: http://maven.apache.org/plugins/maven-assembly-plugin/assembly.html