Getting NetBeans 6.9 RC1 to insert the correct copyright text in maven projects

Netbeans has supported for quite some time the ability to set the license for a project so that when a new file is created, the template automatically inserts the correct one. The problem is that in the past this has not been that well supported when it comes to maven based projects.

Now in some of the recent releases this now works, with a little bit of configuration – I’ve tested this only with 6.9 RC1, but this should (in theory) work with 6.8 and possibly 6.5.

First you need to choose your license. Open the Tools menu and select Templates. This should then open the Template Manager. Once open, expand the Licenses entry to show the available licenses.

Netbeans 6.9 RC1 Template Manager

Now the ones that can be used in maven are the ones named: license-*.txt. If the one you want is there, then make a note if it’s name.

Creating a new License Template

If the license you want is not there then you’ll need to create a template for it. For example the above screenshot shows bsd and gpl3cp which are the two I use for my Open Source projects but they are not provided by Netbeans so I had to create them.

For the BSD template, create the following file in the root directory of your project (so others can reuse the same license), in this case license-bsd.txt:

<#if licenseFirst??>
${licenseFirst}
</#if>
${licensePrefix} Copyright (c) 1998-${date?date?string("yyyy")}, Peter T Mount
${licensePrefix} All rights reserved.
${licensePrefix}
${licensePrefix} Redistribution and use in source and binary forms, with or without
${licensePrefix} modification, are permitted provided that the following conditions
${licensePrefix} are met:
${licensePrefix}
${licensePrefix} * Redistributions of source code must retain the above copyright
${licensePrefix}   notice, this list of conditions and the following disclaimer.
${licensePrefix}
${licensePrefix} * Redistributions in binary form must reproduce the above copyright
${licensePrefix}   notice, this list of conditions and the following disclaimer in the
${licensePrefix}   documentation and/or other materials provided with the distribution.
${licensePrefix}
${licensePrefix} * Neither the name of the retep.org.uk nor the names of its contributors
${licensePrefix}   may be used to endorse or promote products derived from this software
${licensePrefix}   without specific prior written permission.
${licensePrefix}
${licensePrefix} THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
${licensePrefix} "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
${licensePrefix} LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
${licensePrefix} A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER
${licensePrefix} OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
${licensePrefix} EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
${licensePrefix} PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
${licensePrefix} PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
${licensePrefix} LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
${licensePrefix} NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
${licensePrefix} SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<#if licenseLast??>
${licenseLast}
</#if>

Next select the Licenses heading and press Add. Select your new file then add. The template’s now been added. Later if you need to tweek it you can now select it and press Open in editor.

Enabling the template for your Maven project

The next step is to tell Netbeans to use this template. To do this we need to add another file, profiles.xml, which goes into the same directory as your project’s root pom.

<profilesXml>
    <profiles>
        <profile>
            <id>netbeans-private</id>
            <activation>
                <property>
                    <name>netbeans.execution</name>
                    <value>true</value>
                </property>
            </activation>
            <properties>
                <netbeans.hint.license>bsd</netbeans.hint.license>
            </properties>
        </profile>
    </profiles>
</profilesXml>

You’ll notice the netbeans.hint.license property. It’s value is the middle part of your template’s name.

Once set, reload the project within netbeans and every time you create a new file who’s template includes the license it will include the correct one for the project.

Netbeans Template Tips

When creating your own templates, you can include the license at any time using the following snippet:

<#assign licenseFirst = "/*">
<#assign licensePrefix = " * ">
<#assign licenseLast = " */">
<#include "../Licenses/license-${project.license}.txt">

Here you’ll notice we have to assign three values then include the license – the above example is for .java files but you can change it to any values for any type of file.

The other useful tip is the following line from the license template above:

${licensePrefix} Copyright (c) 1998-${date?date?string("yyyy")}, Peter T Mount

Here the template will always insert the current year into the file, rather than having to remember to change the templates every year – although you’ll still have to amend existing files.

It’s been a busy couple of months

It’s been a couple of busy months with most of my time being taken up with my day job.

Most of my time has been spent with either tracking down issues with our live environment, or trying to finish off a couple major projects (both related to XMPP) interspersed with the usual major partner getting in the way.

Any how, over the last couple of weeks I’ve been finishing off some new features which cover most of my public projects and this post will hopefully cover some of the details.

Hopefully these will be released this weekend, time allowing.

The new features are:

RetepTools
* the builder api within retepTools has been updated
* the jaxb plugin library has been cleaned up with common generation code split out to enable reuse
* retepTools as a project is almost ready for deployment to maven central
* a new pligun has been added to jaxb which generates builders for jaxb objects

RetepMicroKernel
* spring has been updated to the latest version 3 (it was on 2.5)
* the core module has been broken up into individual & independent modules
* a new groovy module which enables groovy scripts to be run from the command line
* a major bug fix where exceptions thrown during application startup causes the process to hang has been fixed
* web applications can now be deployed as a war with either jetty or tomcat (they are both supported with their own modules)
* you can now embed Apache Derby within the environment

I’m leaving out the retepXMPP changes out of this list as they need their own article. Suffice it to say, I’ve got a lot waiting for release, just need the time.

Finally, this post is also a test of submitting a blog post from a BlackBerry using the WordPress app so the formatting may be off a tad – won’t know how it goes until I see it in a real browser.

Using groovy to generate java sources in maven

In this article I’ll briefly cover how to use Groovy to generate java sources as part of a maven build.

There are times when you need to generate Java source which is either repetitive, based on external data or both. Now there are tools out there for some tasks like this, but for most simple tasks running a groovy script is more than enough.

Now for the purposes of this article, I’m going to presume we need an enum which represents the cards in a Standard deck of cards, one entry per card.

First we need to create our groovy script. Now the best place to put this is in the src/main/script directory of your project. Here’s the script for this (writing groovy is not in scope for this article) which goes into the file src/main/script/CardDeckGen.groovy:

class CardDeckGen {

    public generate( project, String packageName, String className ) {

        // Where to write the classes
        File targetDirectory = new File( project.build.directory + '/generated-sources/groovy' )

        // The directory to write the source to
        File packageDir = new File( targetDirectory, packageName.replace( '.', '/' ) )

        // Now to create our enum
        def out = []
        out<<'package '+packageName+';\n'
        out<<'public enum '+className+' {\n'

        // We have four suits
        def suit = [ 'D', 'S', 'H', 'C']

        // Each suit has A, 2-9, T, J, Q & K
        def rank = [ 'A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K' ]

        // For each suit, write an entry for each card
        suit.eachWithIndex {
            s, i -> def indent = i==0 ? '    ' : ',\n    '
            rank.each {
                r -> out<< indent + s + r
                indent = ','
            }
        }

        // Mark the end of the enum list
        out<<';\n'

        // Finish the enum class
        out<<'}\n'

        // Convert the array into a string
        StringBuilder sb = new StringBuilder()
        out.each { sb.append(it) }

        // Now write the source, ensuring the directory exists first
        packageDir.mkdirs()
        new File( packageDir, className + ".java" ).write( sb.toString() );
    }

}

Next we need to get maven to run this script, so in pom.xml we first need to make sure we are using the correct version of the jdk – 1.5 or 1.6 would be enough:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
    </configuration>
</plugin>

Next groovy, here we add the gmaven-plugin which runs a small code snippet calling our class:

<plugin>
    <groupId>org.codehaus.groovy.maven</groupId>
    <artifactId>gmaven-plugin</artifactId>
    <executions>
        <execution>
            <phase>generate-resources</phase>
            <goals>
                <goal>execute</goal>
            </goals>
            <configuration>
                <scriptpath>
                    <element>${basedir}/src/main/script</element>
                </scriptpath>
                <source>
                    CardDeckGen cdg = new CardDeckGen()
                    cdg.generate( project, 'uk.org.retep.example', 'CardDeck' )
                </source>
            </configuration>
        </execution>
    </executions>
</plugin>

Now that’s enough to generate our enum, however maven doesn’t know about it so it wont compile. To do that we need to add it so the compiler picks it up:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>add-groovy-sources</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${project.build.directory}/generated-sources/groovy</source>
                </sources>
            </configuration>
        </execution>
    </executions>

Now you can run maven.mvn clean install
If all goes well you’ll get a maven artifact containing an enum:

package uk.org.retep.example;
public enum CardDeck {
    DA,D2,D3,D4,D5,D6,D7,D8,D9,DT,DJ,DQ,DK,
    SA,S2,S3,S4,S5,S6,S7,S8,S9,ST,SJ,SQ,SK,
    HA,H2,H3,H4,H5,H6,H7,H8,H9,HT,HJ,HQ,HK,
    CA,C2,C3,C4,C5,C6,C7,C8,C9,CT,CJ,CQ,CK;
}

This was a simple example but quite a powerful one. I’ve used this technique for generating more complex versions of Card’s to classes based on data contained within RFC’s (STRINGPREP etc).

For help on writing Groovy stripts take a look at the Groovy Getting Started Guide.