Pages

Showing posts with label plugin. Show all posts
Showing posts with label plugin. Show all posts

Wednesday, January 9, 2013

Versioning a webapp using SVN revision as build number with maven

Versioning a webapp is useful for keeping track of bugs fixed, upgrades, libraries versions modifications, etc.

In this article I will show how to use SVN revision number as part of the version number of a webapp using the buildnumber-maven-plugin. Using that number makes things a lot easier in case you have to downgrade your application, reproduce a bug in a particular previous version, etc.

Here I will use the version format Major.Minor.SVNRevision. Major is a number manually assigned, Minor is a sequential number that is incremented automatically after every build, and SVNRevision is the revision number obtained from the SVN repository, you can easily modify this format to suit your needs. The whole number is generated by maven in the build process, ie when you execute mvn install on your project.

For this to work first of all you have to configure the scm section in your pom.xml:


<scm>
    <connection>scm:svn:https://svnserver/projectname/trunk</connection>
    <developerConnection>scm:svn:https://svnserver/projectname/trunk</developerConnection>
    <tag>HEAD</tag>
    <url>https://svnserver/projectname/trunk</url>
</scm>


Then, you must add the buildnumber plugin to the plugins section inside <build> tag

<plugin>

<groupId>org.codehaus.mojo</groupId>
<artifactId>buildnumber-maven-plugin</artifactId>
<version>1.0</version>
<executions>
<execution>
<id>generate-buildnumber</id>
<phase>prepare-package</phase>
<goals>
<goal>create</goal>
</goals>
<configuration>
<doUpdate>true</doUpdate>
<providerImplementations>
<svn>javasvn</svn>
</providerImplementations> 
<useLastCommittedRevision>true</useLastCommittedRevision>
<buildNumberPropertyName>buildRevision</buildNumberPropertyName>
</configuration>
</execution>
<execution>
<id>generate-sequential</id>
<phase>prepare-package</phase>
<goals>
<goal>create</goal>
</goals>
<configuration>
<buildNumberPropertiesFileLocation>src/main/resources/buildNumber.properties</buildNumberPropertiesFileLocation>
<format>{0,number,1'.'00}</format>
<items>
   <item>buildNumber0</item>
</items>
<buildNumberPropertyName>buildSequential</buildNumberPropertyName>
</configuration>
</execution>
</executions>
</plugin>

The plugin has two executions configured.

The first one is responsible for getting the svn revision number from the repository, the 
create goal is executed upon the prepare-package phase, that phase is reached automatically when you issue a build command on maven (install, package, release); the <buildNumberPropertyName> tag value creates a variable name that hold the revision number, later we'll see how it is used.

The second execution creates the sequential part of the version number, it references the
buildNumber.properties file that hold the last number used, which is automatically incremented by 1 after every build. The item tag indicates the name of the variable inside the properties file. The format of the generated number is 1.XX, where XX is the number obtained from the properties file, the plugin uses java.text.MessageFormat to format the number using {0,number,1'.'00} format in this case. Note that we use <buildNumberPropertyName> again to store the sequential number in a new variable.


Using the generated version number

Now that we already have the pom.xml configured to generate the version number, it's time to use it. I'll show you here how to put it in your application's home page but you can reference it elsewhere.

First, I'll declare two variables in the pom.xml that references the two variables created by the buildnumber plugin:

<properties>
    ...
    <webapp.version>${buildSequential}</webapp.version>
    <webapp.revision>${buildRevision}</webapp.revision>
</properties>

Then I'll add another plugin to my pom, maven-war-plugin that is responsible for the packaging and generation of the web application archive.

<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<webResources>
<resource>
<directory>src/main/webapp</directory>
<filtering>true</filtering>
<includes>
<include>index.html</include>
</includes>
</resource>
</webResources>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
<manifestEntries>
<Implementation-Build>${buildRevision}</Implementation-Build>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>

In the configuration of the plugin I indicate to filter index.html in order to replace variables included there by values computed from this pom. You can find more information about filtering in the plugin's site. I also added a default MANIFEST.MF file indicating the generated revision number as Implementation-Build value. That file is included inside the META-INF folder of the webapp.

Then, inside the index.html you can reference the variables declared earlier in the pom:

<html>
  <head>
    <title>Webapp's Name ${webapp.version} (Revision: ${webapp.revision})</title>
    ...
  </head>
  ...
</html>

That's all, when your application is packaged and deployed, you'll see in your home page the title indicating the version number, for example: Webapp's Name 1.23 (Revision: 4567)

Hope it helps. Comment if you have any problem using this approach.

Monday, January 7, 2013

Use aspectj-maven-plugin to perform custom validation in JSF

You can use AspectJ to do many things, but its potential arise when you use it in order to apply the SoC paradigm.
In this post I will show you how to use it to perform custom validation in the presentation layer of a JSF webapp. Later I will show how to use spring to define more generic pointcuts in your application.

Note: I'll asume you already have basic knowledge of AOP in general and AspectJ in particular. I will not get into syntax and terminology details here. You can consult AspectJ site for documentation and resources. You can also find some terms definitions used here in Captain Debug's Blog.

It is very straightforward to configure AspectJ when you are using maven in your project. All you have to do is to add the aspectj-maven-plugin in the build section of your pom.xml:

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.2</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjtools</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
</plugin>

You have to add the aspectjrt and aspectjtools dependencies to the plugin in order to let maven find the necessary to compile the AspectJ source.


Then you can code the validation AspectJ advice BackingBeanValidatorAdvice.aj as a normal source file:

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
...

public aspect BackingBeanValidatorAdvice {

    pointcut doSaveChanges() : execution(* com.foo.beans.BackingBean.saveChanges(..));

    void around() : doSaveChanges() {
        FacesContext context = FacesContext.getCurrentInstance();
        BBean bbean = context.getApplication().evaluateExpressionGet(context, "#{bBean.selected}", BBean.class); 

        // perform custom validation

        // if validation fails
        if (..) {
         String sum = "...";
         String det = "...";
         context.addMessage("error", new FacesMessage(FacesMessage.SEVERITY_ERROR, sum, det);
         return;
        }
        proceed();
    }
}

Doing this, when your backing bean's saveChanges(..) method is invoked, the pointcut is reached and the advice performing the custom validation is executed. Then, back to the jsf page, you can show the error's custom message as usual using <h:messages ... />

As you can see, you can apply this mechanism also to perform logging, database audits, notifications, etc. That's precisely the potential of AspectJ used in conjunction with SoC design principle.


Automatic pointcut configuracion using Spring

In this article, you had to add the pointcut manually in your advice's source. If you are using springframework, you can configure the pointcuts in the application-context.xml. Here is an example of using AOP in spring to implement a database logging concern without modifying a single line of code in your existing application. In your application-context.xml file add the following:

...

<bean id="databaseAuditAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
  <property name="beanNames">
<list>
<value>*Dao</value>
</list>
  </property>
  <property name="interceptorNames">
<list>
<value>regexpAdvisor</value>
</list>
  </property>
</bean>

<bean id="regexpAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="advice">
<ref local="databaseLoggerAuditAdvisor"/>
</property>
<property name="pointcut">
   <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="patterns">
<value>.*read.*,.*load.*,.*get.*,.*save.*,.*Username.*</value>
</property>
<property name="excludedPatterns">
<value>.*find.*,.*History.*</value>
</property>
   </bean>
</property>
</bean>

<bean id="databaseLoggerAuditAdvisor" class="com.foo.aspects.DatabaseLoggerAuditAdvice">
<property name="auditService" ref="auditService"/>
</bean>
...

The databaseAuditAutoProxy automatically create proxies for the beans names that match beanNames attribute. The regexpAdvisor references the advisor implementation itself and defines a pointcut that uses regular expressions to define method names to intercept.

Then you have to code the DatabaseLoggerAuditAdvice.aj class:

public class DatabaseLoggerAuditAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {

    private AuditService auditService;

    public LoggerAuditAdvice() {
    }

    /**
     * @see org.springframework.aop.MethodBeforeAdvice#before(java.lang.reflect.Method,
     *      java.lang.Object[], java.lang.Object)
     */
    public void before(Method method, Object[] args, Object target) throws Throwable {

        log = LogFactory.getLog(target.getClass());
        if (log.isInfoEnabled()) {
            Audit audit = new Audit();
            audit.setUsername(SecurityHelper.getUserName());
            audit.setTime(new Date());
            audit.setMethodName(method.getName());
            audit.setMethodArgumentsValue(ArrayUtils.toString(args, "null"));
            log.info(" [[[BEFORE]]] " + audit);
        }
    }

    /**
     * @see org.springframework.aop.AfterReturningAdvice#afterReturning(java.lang.Object,
     *      java.lang.reflect.Method, java.lang.Object[], java.lang.Object)
     */
    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {

        log = LogFactory.getLog(target.getClass());
        if (log.isInfoEnabled()) {
            Audit audit = new Audit();
            audit.setUsername(SecurityHelper.getUserName());
            audit.setTime(new Date());
            audit.setMethodName(method.getName());
            audit.setMethodArgumentsValue(ArrayUtils.toString(args, "null"));
            audit.setTarget(target.getClass().getSimpleName());
            log.info(" [[[AFTER]]] " + audit);
            this.getAuditService().save(audit);
        }
    }

    public void afterThrowing(Method m, Object[] args, Object target, Throwable ex) {
        log = LogFactory.getLog(target.getClass());
        log.error("Exception in method: " + m.getName() + " Exception is: " + ex.getMessage() + " for user "
            + SecurityHelper.getUserName());
    }

    public AuditService getAuditService() {
        return auditService;
    }

    public void setAuditService(AuditService auditServiceToSet) {
        this.auditService = auditServiceToSet;
    }
}

Hope it helps, comment and give feedback.

PS: If you get errors in your project, you have to make sure you have added  *.aj as source files, and to make the project as a "AspectJ Project", ie, add the AspectJ runtime. The method may vary depending on the IDE you are using. In Eclipse, you have to configure the project as an AspectJ Project (right click on the project, Configure > Convert to AspectJ Project..) and add *.aj fileset mapping to the source code in the Java Build Path of your project.