5

I have a file with a list of tokens:

tokens.txt

foo
bar
baz

and a template file:

template.txt

public class @token@MyInterface implements MyInterface {
     public void doStuff() {
        // First line of generated code
        // Second line of generated code
     }
}

I want to generate the following source code files to target/generated-sources/my/package:

  • FooMyInterface.java
  • BarMyInterface.java
  • BazMyInterface.java

One of the generated source files look like this:

FooMyInterface.java

public class FooMyInterface implements MyInterface {
     public void doStuff() {
        // First line of generated code
        // Second line of generated code
     }
}

How can I do this with Maven ?

Stephan
  • 41,764
  • 65
  • 238
  • 329

1 Answers1

1

What you're looking to do is called filtering. You can read more about it here. As you can see, you'll have to change the way you're doing some things. The variables are defined differently. You'll want to rename the file to a .java.

But then you've got another problem: This will take a source file and replace the variables with literals, but it wont compile the .java file for you when you build your project. Assuming you want to do that, here's a tutorial on how. I'm going to inline some of that tutorial just in case it disappears some day:

Example source file:

public static final String DOMAIN = "${pom.groupId}";
public static final String WCB_ID = "${pom.artifactId}";

The filtering:

<project...>
  ...
  <build>
    ...
    <!-- Configure the source files as resources to be filtered
      into a custom target directory -->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <filtering>true</filtering>
        <targetPath>../filtered-sources/java</targetPath>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
  ...
  </build>
...
</project>

Now change the directory in which maven finds the source files to compile:

<project...>
  ...
  <build>
    ...
      <!-- Overrule the default pom source directory to match
            our generated sources so the compiler will pick them up -->
      <sourceDirectory>target/filtered-sources/java</sourceDirectory>
  ...
  </build>
...
</project>
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356
  • Does this will generate only one file ? – Stephan May 10 '13 at 07:39
  • Yeah, I forgot about that requirement when I wrote this. To do that part, it looks like this SO answer will help: http://stackoverflow.com/questions/3308368/maven-how-to-filter-the-same-resource-multiple-times-with-different-property-va – Daniel Kaplan May 10 '13 at 07:44