Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maven - Replace a file in a Jar

I want to replace a file in an existing jar/zip file while doing a Maven build. What is the easiest way to achieve this?

like image 637
M99 Avatar asked Jun 10 '11 13:06

M99


People also ask

How do I replace a .JAR file?

You don't need to extract the jar file to make this work. Just open the jar with one of those apps, go to de directory where is the class file to be replaced, drag-and-drop the new file to replace the old one and save.

How do I open and update a JAR file?

The Jar tool provides a u option which you can use to update the contents of an existing JAR file by modifying its manifest or by adding files. In this command: The u option indicates that you want to update an existing JAR file. The f option indicates that the JAR file to update is specified on the command line.


2 Answers

My favorite for this sort of tasks is maven-antrun-plugin which brings you complete ant functionality.

You can use it like this:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.6</version>
    <executions>
      <execution>
        <id>repack</id>
        <phase>compile</phase>
        <goals>
          <goal>run</goal>
        </goals>
        <configuration>
          <target>
            <!-- note that here we reference previously declared dependency -->
            <unzip src="${org.apache:common-util:jar}" dest="${project.build.directory}/tmp"/>
            <!-- now do what you need to any of unpacked files under target/tmp/ -->
            <zip basedir="${project.build.directory}/tmp" destfile="${project.build.directory}/common-util-modified.jar"/>
            <!-- now the modified jar is available  -->
          </target>
        </configuration>
      </execution>
    </executions>
  </plugin>

But remember - never modify any files in your local repository - in this example pointed to by ${org.apache:common-util:jar}. Doing so would affect your further builds of all your projects on the same computer (= against the same local repo).

Such builds are also irreproducible (or hard to reproduce) on other machines.

like image 106
Petr Kozelka Avatar answered Sep 16 '22 15:09

Petr Kozelka


I don't think there is a dedicated plugin to do this but I would imagine you can use the exec plugin and information from Updating .class file in jar to accomplish this.

like image 30
mark-cs Avatar answered Sep 20 '22 15:09

mark-cs