Maven archetype + Velocity: how to show the date

I have a maven archetype project. When I use this archetype, I want some files to report the actual date. I tried with $ date, but Velocity will not recognize it. I found something called DateTools, but I don't know how to use it. This is the first time I use Velocity.

+4
source share
4 answers

Unfortunately, the Maven Archetype plugin is not bundled with Velocity tools. I added it by modifying the Maven Archetypes plugin. Complete the following steps, assuming you are using Maven 2.2.1:

svn co -q http://svn.apache.org/repos/asf/maven/archetype/tags/maven-archetype-2.2 cd maven-archetype-2.2 curl -k -O https://raw.github.com/gist/3404715/59c7fa1c20c60e2a165de4109c2acffb8026febd/velocity-tools.patch patch -p0 -i velocity-tools.patch mvn install 

The modified Maven Archetype plugin will now be installed locally.

$date usage in your templates should now display, for example.

 The date is $date 

... in:

 The date is Aug 20, 2012 4:40:22 PM 
+3
source

(Apologies for resurrecting the old question, but I just worked in such a way as to achieve this without having to pull out and fix the plugin).

For those who want to have a link to the date fields in their maven archetype templates, I managed to get it to work with the following set of definitions at the top of my pom.xml template

 #set( $str = "" ) #set( $dt = $str.getClass().forName("java.util.Date").newInstance() ) #set( $year = $dt.getYear() + 1900 ) 

If you already have the object-oriented variables available for your template where you insert these lines, you can scratch the $ str declaration and use one of your variables instead, since it doesn't really matter where you are get a link to the .forName () Class from.

NOTE. My attempts to get this working with Calendar.getInstance () were unsuccessful.

+3
source

I managed to trim the solution from @maaxiim to one line:

 #set( $year = $package.getClass().forName("java.util.Date").newInstance().getYear() + 1900 ) 

The $ package variable will always be available from the maven archetype plugin. Other built-in functions also work, but most of them are quite long, and $ artifactId.getClass () just looks ... wrong.

+1
source

In Java 8 with formatting:

 #set( $ldt = $package.getClass().forName("java.time.LocalDateTime").getMethod("now").invoke(null) ) #set( $dtf = $package.getClass().forName("java.time.format.DateTimeFormatter").getMethod("ofPattern", $package.getClass()).invoke(null, "yyyy/MM/dd HH:mm:ss") ) #set( $date = $ldt.format($dtf) ) 
+1
source

All Articles