6
votes

I have a project (here called my-artifact) which needs to generate sources from a model file. I've created a maven-plugin (my-code-generator) which is used as described in the pom.xml excerpt below. It loads and processes the model.xml from my-artifact's resources and generates code using some predefined templates stored within the plugin. The question is how my-code-generator could access these templates as they are not in the project resources but within its own resources.

Thanks in advance

<plugin>
  <groupId>my-group</groupId>
        <artifactId>my-code-generator</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <configuration>
                <modelfile>
                        src/main/resources/model.xml
                </modelDir>
        </configuration>
        <executions>
                <execution>
                        <phase>generate-sources</phase>
                        <goals>
                                <goal>generate-model</goal>
                        </goals>
                </execution>
        </executions>
</plugin>
<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <executions>
                <execution>
                        <id>add-source</id>
                        <phase>generate-sources</phase>
                        <goals>
                                <goal>add-source</goal>
                                <sources>
                                        <source>target/generated-sources</source>
                                </sources>
                        </configuration>
                </execution>
        </executions>
</plugin>

2
@anonymous, so the template(s) are within your own created Maven plug-in?Verhagen

2 Answers

5
votes

Just use the ClassLoader, to get resources from the MyCodeGenerator Maven plugin.

Add something like this to your MyCodeGeneratorMojo

    URL getTemplate(String fileName) {
        return this.getClass().getResource(fileName);
    }

Within the MyCodeGenerator Maven plugin, add the template(s) to the src/main/resources directory (don't forget to use the correct package entry (directories) within that directory).

3
votes

By including them in the jar file for the plugin and referencing them via classpath, via ClassLoader.getResourceAsStream.

By packaging them as another artifact, declaring them as a dependency, and calling the dependency-resolution API, which is a lot more work.