//
you're reading...
General, Java/Cloud, SMART/Lean development, Tips&Tricks

Creating maven archetype using create-from-project

Maven archetypes are a great way to create templates for standardized projects. The advantage of creating a maven archetype is that it can easily integrate with any IDE that supports maven compilation such as Eclipse. In SMART we provide maven archetypes to get started on developing SMART flows easily. In this blog I want to share our learning when creating these archetypes.

Sample Archetype

We will write an archetype called simple-archetype that generates the following structure:

    pom.xml
    src
     |--main
        |-- java
        |   |-- package (org.smart.demo)
        |       |-- TestMessage.java
        |-- resources
            |-- TestMessageFlow.soa
            |-- package (org.smart.demo)
                |-- TestMessage.soa

when the below command is run:

 mvn archetype:generate \
-DarchetypeGroupId=org.smart.archetypes \
-DarchetypeArtifactId=simple-archetype \  
-DarchetypeVersion=1.0-SNAPSHOT \  
-DgroupId=org.smart.demo \  
-DartifactId=testmessage \  
-Dclassname=TestMessage

Creating the skeleton archetype project

Maven archetypes can be created easily using the create-from-project maven command. To create an archetype from a project run the command from the directory where the template project is present.

mvn archetype:create-from-project

We will use the sample template project from here to create the archetype. This creates an archetype from the current project into the directory target/generated-sources/archetype. When we look at the generated project for the archetype we find that Message.java is hardcoded. Hence using this archetype will always only generate back the same fields and java classes as present in the template project.

archetype properties

How to vary the generated class? By default maven has a set of standard variables defined that can be varied when the project is created. The most common ones that are used:

  • groupId
  • artifactId
  • version
  • package

These are defaulted to the values in the project from which the artefact is created. More variables can be added to this as required for the archetype. For eg., in our project we want to vary the name of Message.java, to do this we will introduce a new variable called “data” that can be specified when the maven project is created.

The maven create-from-project takes in a archetype properties file that define these variables. To use this we define a generate.properties file with content as below (Ensure this file is present outside the directory of your template project):

package=org.smart.flows.message
groupId=org.smart.flows
artifactId=message
version=1.0-SNAPSHOT
data=Message

The values should be the values that are present in the template project. In our example, we have the data class in the package org.smart.flows.message and it is called Message.java. Hence we have defined the “data” variable as Message. This is important because the create-from-project will automatically replace the values with the variables. Now you can run the command as

mvn -Darchetype.properties=../generate.properties archetype:create-from-project

The Message.java that is generated will be as below:

#set( $symbol_pound = '#' )
#set( $symbol_dollar = '$' )
#set( $symbol_escape = '\' )
package ${groupId}.${artifactId};

public class ${data} implements java.io.Serializable
{
    private String ${artifactId};

    public ${data}()
    {
    }

    public String get${data}() { return ${artifactId}; }
}

Now the content of the java file will vary based on the “data” and “artifactId” variables set. The generated project has a few things that has to be fixed.

  • The name of the java file is still hardcoded to Message.java.
  • The files in resources directory is still hardcoded with Message

Changing the name of the generated file

The files that will be used to generate the project is present under the directory “src/main/resources/archetype-resources/”. The java file is under “src/main/java”. Move the Message.java file to  __data__.java. This will ensure that the generated file is the same name as the variable passed to the maven command. The package variable is not correct, since the artifactId and groupId reflect the package name. Hence we change the package from ${groupId}.${artifactId} to ${package}. This sets up the java class correctly.

The test classes also need to follow the same pattern, except the file has to have a “Test” post fixed to the name. Hence we rename the test file as __data__Test.java. Any variations in the java classes can be done manually. Any ${…} inside the file is substituted with the variable value and __…__ in the file name is substituted with the variable value.

Changing the resources directory

While the java classes are by default created with substitution variables, the resources are not. These files need to be modified manually. In our case we have two files to be generated. Flow.soa that describes our jar.The .soa describes our data class and has to be present in the same package as the java class. Modification for substitution is simple. The soa file is changed as below:

##set( $symbol_pound = '#' )
##set( $symbol_dollar = '$' )
##set( $symbol_escape = '\' )
name:   ${data}Flow
defaultEnable: all
primeData:
    - ${package}.${data}
events:
    - ${package}.${event}
transitions:
    - ${package}.${transition}
features:
    - name: all
      artefacts:
        - ${package}.${data}
        - ${package}.${event}
        - ${package}.${transition}

We need to add the first three lines in all files. This has to be equal to a comment, hence we use “##”. We replace all places where substitution has to occur with the proper variables. This generates the file with the correct substitutions. But changing the name of the file to “__data__Flow.soa” does not change the file name based on the variable.

To do this we need to change the archetype metadata. This is present under the directory “src/main/resources/META-INF/maven/” in the file archetype-metadata.xml. The fileset command in this file defines how the files are created:

  

    <fileSet filtered="true" packaged="true" encoding="UTF-8">
      src/main/java

        **/*.java

    <fileSet encoding="UTF-8">
      src/main/resources

        **/*.soa

    
    <fileSet filtered="true" packaged="true" encoding="UTF-8">
      src/test/java

        **/*.java

From the above we see that the resources directory is a direct copy. To change this we need two variables defined, filtered and packaged. So we redefine this as below:

    <fileSet encoding="UTF-8" packaged="true" filtered="true">
      src/main/resources

        **/__*__.soa

    filtered="true">
      src/main/resources

        **/*Flow.soa
        **/*.js

We need the Flow.soa directly under the parent directory while the .soa file needs to be present in the packaged directory. Hence we split this into two filesets. Now we rename the files appropriately i.e., MessageFlow.soa is named as __data__Flow.soa and Message.soa is directly under the resources directory and named as __data__.soa file. This ensures that we get the correct project generated when the maven command is run.The generated maven archetype can be checked out here.

Advertisements

Discussion

One thought on “Creating maven archetype using create-from-project

  1. Thanks for a wonderful tutorial. I have a question. Can we create dynamic files with maven archetype which does more than variable substitution and #if #else constructs. e.g.
    Can I add a custom object to the velocity context, which contains other properties provided by the user including collections of other objects which are iterated over in the templates.
    Use case : I want to build a dynamic java class whose fields names are provided by user. I dont know the number of fields or names of those fields. But is there a way I can get that information in form of a java object and populate the dynamic class. I know that it uses Velocity Template but I find documentation lacking to answer these questions.
    A similar question on stackoverflow :
    http://stackoverflow.com/questions/12360904/can-i-add-custom-objects-to-velocity-context-with-maven-archetype-plugin?rq=1

    Posted by sanchit | June 27, 2014, 11:31 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: