42

I have some java source files that use a package prefix (they are emulating some JDK classes). I use these files with the prefix to run against some unit tests. If the tests pass I want to produce a jar that contains the source files but with the package prefix removed from all the java files.

I am using maven for builds. Does any one know of a way to do this? Essentially what I want is something like the resources plugin filtering feature, but that does proper search and replace (like: s/my.package.prefix.//g), rather than filtering on ${vars}.

Dean Povey
  • 9,256
  • 1
  • 41
  • 52

2 Answers2

52

You can also use

http://code.google.com/p/maven-replacer-plugin/

100% maven and doing exactly what you want and more

cedric.walter
  • 731
  • 6
  • 7
37

This can be solved with the antrun plugin. Firstly the sources need to be copied to the target directory, with:

<build>
  ...
  <resources>
    <resource>
      <directory>src/main/java</directory>
      <includes>
        <include>**/*.java</include>
      </includes>
    </resource>
  </resources>
  ...
</build>

Secondly you use the replace task of the antrun plugin to replace the files using the prepare package phase

<build>
    ...
  <plugin>
    <artifactId>maven-antrun-plugin</artifactId>
    <executions>
      <execution>
        <phase>prepare-package</phase>
        <configuration>
          <tasks>
            <replace token= "my.package.prefix." value="" dir="target/classes">                                 
              <include name="**/*.java"/>
            </replace>
          </tasks>
        </configuration>
        <goals>
          <goal>run</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
  ...
</build>

This will copy the source files to target/classes in the process-resources phase, do a search and replace on the files inplace in the target/classes directory in the prepare-package phase and finally they will jarred up in the package phase.

Dean Povey
  • 9,256
  • 1
  • 41
  • 52
  • I prefer this way as this enable more execution phases to occur, and allows to work on different files separately. – JayZee Apr 29 '14 at 10:31
  • 5
    The replace is done correctly but the replaced .java is not compiled and not included in the generated package. It is because you apply the replace plugin in the prepare-package phase, when source files only has collected and them has been yet compiled. You must apply this solution in the compile phase, and it works!!! – AntuanSoft Aug 24 '16 at 18:30
  • For doing something in Java files I can recommend [templating-maven-plugin](http://www.mojohaus.org/templating-maven-plugin/) – khmarbaise Jan 13 '17 at 13:36
  • 1
    is there a way to remove whole line that starts with some character, say '#' in properties file? – being_ethereal Dec 22 '18 at 13:22