Thursday, November 22, 2012

Apache Camel with Spring, routing with enrichment service



Sorry for not having posted anything in some time but I had plenty of work. Anyway today I will continue the example with JMS that I've shown you some time ago.

The idea of the previous example was to simplify the work that we had to do in a manual way - we've sed JmsTemplate and Spring listener containers. The routing as such unfortunately was still done by us. In order to facilitate this process we can use Apache Camel.

The following example bases on the one that we've seen in this post Spring JMS, message automatic conversion, JMS template but with slight modifications:

CamelRouter.java

package pl.grzejszczak.marcin.camel;

import org.apache.camel.spring.Main;

public class CamelRouter {

 /**
  * @param args
  * @throws Exception
  */
 public static void main(String[] args) throws Exception {
  Main main = new Main();
  main.setApplicationContextUri("/camel/camelContext.xml");
  main.run(args);
 }

}


What we can see here is the usage of the Camel's Main class which you can reuse to more easily boot up Camel and keep it running until the JVM terminate.

Then we have a new file camelContext.xml in which we have the Camel context in the Spring configuration file.

camelContext.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">
 
 <import resource="classpath:/camel/jmsApplicationContext.xml" />
 
 <camel:camelContext id="camel" xmlns:camel="http://camel.apache.org/schema/spring">
  <camel:dataFormats>
   <camel:jaxb id="jaxb" prettyPrint="true" contextPath="pl.grzejszczak.marcin.camel.jaxb.generated" />
  </camel:dataFormats>

  <camel:route>
   <camel:from uri="activemq:topic:Initial.Topic" />
   <camel:unmarshal ref="jaxb" />
   <camel:bean ref="enrichingService" />
   <camel:marshal ref="jaxb" />
   <camel:to uri="activemq:topic:Routed.Topic" />
  </camel:route>

 </camel:camelContext>
</beans>

We are defining in this file in order to create a Camel Route - from the activemq topic called Initial.Topic to the one called Routed.Topic. In the meantime we are doing some unmarshalling and marshalling by means of Jaxb.

In the jmsApplicationContext we no longer define the sender to the final topic: Routed.Topic.

jmsApplicationContext.java

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jms="http://www.springframework.org/schema/jms" xmlns:oxm="http://www.springframework.org/schema/oxm"
 xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

 <!-- Spring configuration based on annotations -->
 <context:annotation-config />
 <!-- Show Spring where to search for the beans (in which packages) -->
 <context:component-scan base-package="pl.grzejszczak.marcin.camel" />
 
 <!-- Show Spring where to search for the properties files -->
 <context:property-placeholder location="classpath:/camel/jms.properties" />

 <!-- The ActiveMQ connection factory with specification of the server URL -->
 <bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
  <property name="brokerURL" value="tcp://localhost:61616" />
 </bean>

 <!-- Spring's jms connection factory -->
 <bean id="cachingConnectionFactory"
  class="org.springframework.jms.connection.CachingConnectionFactory">
  <property name="targetConnectionFactory" ref="activeMQConnectionFactory" />
  <property name="sessionCacheSize" value="10" />
 </bean>

 <!-- The name of the queue from which we will take the messages -->
 <bean id="origin" class="org.apache.activemq.command.ActiveMQTopic">
  <constructor-arg value="${jms.origin}" />
 </bean>
 <!-- The name of the queue to which we will route the messages -->
 <bean id="destination" class="org.apache.activemq.command.ActiveMQTopic">
  <constructor-arg value="${jms.destination}" />
 </bean>

 <!-- Configuration of the JmsTemplate together with the connection factory and the message converter -->
 <bean id="producerTemplate" class="org.springframework.jms.core.JmsTemplate">
  <property name="connectionFactory" ref="cachingConnectionFactory" />
  <property name="messageConverter" ref="oxmMessageConverter" />
 </bean>

 <!-- Custom message sender sending messages to the initial queue -->
 <bean id="originPlayerSender" class="pl.grzejszczak.marcin.camel.manual.jms.PlayerDetailsSenderImpl">
  <property name="destination" ref="origin" />
 </bean>

 <!-- Custom message listener - listens to the destination queue  -->
 <bean id="destinationListenerImpl" class="pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl"/>

 
 <!-- Spring's jms message listener container - specified the connection factory, the queue to be listened to and the component that listens to the queue -->
 <bean id="jmsDestinationContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
  <property name="connectionFactory" ref="cachingConnectionFactory" />
  <property name="destination" ref="destination" />
  <property name="messageListener" ref="destinationListenerImpl" />
 </bean>
 
 <!-- Message converter - automatically marshalls and unmarshalls messages using the provided marshaller / unmarshaller-->
 <bean id="oxmMessageConverter" class="org.springframework.jms.support.converter.MarshallingMessageConverter">
          <property name="marshaller" ref="marshaller" />
          <property name="unmarshaller" ref="marshaller" />
     </bean>

 <bean id="enrichingService" class="pl.grzejszczak.marcin.camel.service.EnrichingServiceImpl"/>

 <!-- Spring's JAXB implementation of marshaller - provided a class the JAXB generated class -->
     <oxm:jaxb2-marshaller id="marshaller">
          <oxm:class-to-be-bound name="pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails" />
     </oxm:jaxb2-marshaller>

</beans>

Once we have already initialized our camel context, what we need to do is to send a message to the Initial.Topic. We are doing it by means of our modified ActiveMQRouter class.

ActiveMQRouter.java


package pl.grzejszczak.marcin.camel.manual;

import java.io.File;
import java.util.Scanner;

import javax.jms.JMSException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import pl.grzejszczak.marcin.camel.jaxb.PlayerDetailsConverter;
import pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails;
import pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl;
import pl.grzejszczak.marcin.camel.manual.jms.Sender;

public class ActiveMQRouter {

 /**
  * @param args
  * @throws JMSException
  */
 public static void main(String[] args) throws Exception {
  ApplicationContext context = new ClassPathXmlApplicationContext("/camel/jmsApplicationContext.xml");
  @SuppressWarnings("unchecked")
  Sender<PlayerDetails> sender = (Sender<PlayerDetails>) context.getBean("originPlayerSender");

  Resource resource = new ClassPathResource("/camel/RobertLewandowski.xml");

  Scanner scanner = new Scanner(new File(resource.getURI())).useDelimiter("\\Z");
  String contents = scanner.next();

  PlayerDetailsConverter converter = context.getBean(PlayerDetailsConverter.class);

  FinalListenerImpl listener = (FinalListenerImpl) context.getBean("finalListenerImpl");

  sender.sendMessage(converter.unmarshal(contents));
 }
}

The class is reading the file and sending it to the initial topic. We also initialize a FinalListenerImpl - a class that will listen to the messages coming to the final topic - to prove that everything is working correctly.

That's it! Now let's check out the logs. Logs of CamelRouter:


2012-11-22 22:51:39,429 INFO  [main] org.apache.camel.main.MainSupport:300 Apache Camel 2.9.2 starting
2012-11-22 22:51:40,028 INFO  [main] org.springframework.context.support.ClassPathXmlApplicationContext:495 Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@4c5e176f: startup date [Thu Nov 22 22:51:40 CET 2012]; root of context hierarchy
2012-11-22 22:51:40,213 INFO  [main] org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [camel/camelContext.xml]
2012-11-22 22:51:40,746 INFO  [main] org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [camel/jmsApplicationContext.xml]
2012-11-22 22:51:41,120 INFO  [main] org.springframework.context.annotation.ClassPathBeanDefinitionScanner:210 JSR-330 'javax.inject.Named' annotation found and supported for component scanning
2012-11-22 22:51:43,219 INFO  [main] org.springframework.beans.factory.config.PropertyPlaceholderConfigurer:177 Loading properties file from class path resource [camel/jms.properties]
2012-11-22 22:51:43,233 INFO  [main] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor:139 JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2012-11-22 22:51:43,274 INFO  [main] org.springframework.beans.factory.support.DefaultListableBeanFactory:557 Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@19d03a4e: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,AgeEnricher,ClubEnricher,PlayerDetailsConverter,finalListenerImpl,playerDetailsSenderImpl,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,activeMQConnectionFactory,cachingConnectionFactory,origin,destination,producerTemplate,originPlayerSender,destinationListenerImpl,jmsDestinationContainer,oxmMessageConverter,enrichingService,marshaller,template,consumerTemplate,camel:beanPostProcessor,camel,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
2012-11-22 22:51:43,424 INFO  [main] org.springframework.oxm.jaxb.Jaxb2Marshaller:436 Creating JAXBContext with classes to be bound [class pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails]
2012-11-22 22:51:44,521 INFO  [main] org.springframework.context.support.DefaultLifecycleProcessor:334 Starting beans in phase 2147483647
2012-11-22 22:51:45,061 INFO  [main] org.springframework.jms.connection.CachingConnectionFactory:291 Established shared JMS Connection: ActiveMQConnection {id=ID:marcin-SR700-47684-1353621104666-1:1,clientId=null,started=false}
2012-11-22 22:51:45,608 INFO  [main] org.apache.camel.spring.SpringCamelContext:1374 Apache Camel 2.9.2 (CamelContext: camel) is starting
2012-11-22 22:51:45,611 INFO  [main] org.apache.camel.management.ManagementStrategyFactory:38 JMX enabled. Using ManagedManagementStrategy.
2012-11-22 22:51:45,850 INFO  [main] org.apache.camel.management.DefaultManagementLifecycleStrategy:790 StatisticsLevel at All so enabling load performance statistics
2012-11-22 22:51:45,961 INFO  [main] org.apache.camel.impl.converter.AnnotationTypeConverterLoader:119 Found 3 packages with 15 @Converter classes to load
2012-11-22 22:51:45,995 INFO  [main] org.apache.camel.impl.converter.DefaultTypeConverter:405 Loaded 170 core type converters (total 170 type converters)
2012-11-22 22:51:46,002 INFO  [main] org.apache.camel.impl.converter.AnnotationTypeConverterLoader:109 Loaded 2 @Converter classes
2012-11-22 22:51:46,023 INFO  [main] org.apache.camel.impl.converter.AnnotationTypeConverterLoader:119 Found 1 packages with 1 @Converter classes to load
2012-11-22 22:51:46,024 WARN  [main] org.apache.camel.impl.converter.DefaultTypeConverter:257 Overriding type converter from: StaticMethodTypeConverter: public static org.apache.activemq.command.ActiveMQDestination org.apache.camel.component.activemq.ActiveMQConverter.toDestination(java.lang.String) to: StaticMethodTypeConverter: public static org.apache.activemq.command.ActiveMQDestination org.apache.activemq.camel.converter.ActiveMQConverter.toDestination(java.lang.String)
2012-11-22 22:51:46,043 INFO  [main] org.apache.camel.impl.converter.DefaultTypeConverter:431 Loaded additional 3 type converters (total 173 type converters) in 0.041 seconds
2012-11-22 22:51:46,360 INFO  [main] org.apache.camel.converter.jaxb.JaxbDataFormat:277 Creating JAXBContext with contextPath: pl.grzejszczak.marcin.camel.jaxb.generated and ApplicationContextClassLoader: sun.misc.Launcher$AppClassLoader@35a16869
2012-11-22 22:51:46,500 INFO  [main] org.apache.camel.spring.SpringCamelContext:1980 Route: route1 started and consuming from: Endpoint[activemq://topic:Initial.Topic]
2012-11-22 22:51:46,509 INFO  [main] org.apache.camel.spring.SpringCamelContext:1409 Total 1 routes, of which 1 is started.
2012-11-22 22:51:46,510 INFO  [main] org.apache.camel.spring.SpringCamelContext:1410 Apache Camel 2.9.2 (CamelContext: camel) started in 0.901 seconds
2012-11-22 22:51:46,519 INFO  [main] org.springframework.context.support.DefaultLifecycleProcessor:334 Starting beans in phase 2147483647
2012-11-22 22:52:08,375 DEBUG [Camel (camel) thread #1 - JmsConsumer[Initial.Topic]] pl.grzejszczak.marcin.camel.service.EnrichingServiceImpl:21 Enriching player details
2012-11-22 22:52:08,377 DEBUG [Camel (camel) thread #1 - JmsConsumer[Initial.Topic]] pl.grzejszczak.marcin.camel.enricher.AgeEnricher:17 Enriching player [Lewandowski] with age data
2012-11-22 22:52:10,379 DEBUG [Camel (camel) thread #1 - JmsConsumer[Initial.Topic]] pl.grzejszczak.marcin.camel.enricher.ClubEnricher:16 Enriching player [Lewandowski] with club data
2012-11-22 22:52:12,462 DEBUG [jmsDestinationContainer-1] pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl:35 Message already enriched! Shutting down the system

We can see that the Camel Context has been initialized and then the bean that we have created in the jmsApplicationContext.xml that is listening to the final destination is acknowledging that the message has been enriched properly.

What about the ActiveMQRouter.java logs?


2012-11-22 22:52:06,077 INFO  [main] org.springframework.context.support.ClassPathXmlApplicationContext:495 Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@43462851: startup date [Thu Nov 22 22:52:06 CET 2012]; root of context hierarchy
2012-11-22 22:52:06,153 INFO  [main] org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [camel/jmsApplicationContext.xml]
2012-11-22 22:52:06,417 INFO  [main] org.springframework.context.annotation.ClassPathBeanDefinitionScanner:210 JSR-330 'javax.inject.Named' annotation found and supported for component scanning
2012-11-22 22:52:06,721 INFO  [main] org.springframework.beans.factory.config.PropertyPlaceholderConfigurer:177 Loading properties file from class path resource [camel/jms.properties]
2012-11-22 22:52:06,733 INFO  [main] org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor:139 JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2012-11-22 22:52:06,758 INFO  [main] org.springframework.beans.factory.support.DefaultListableBeanFactory:557 Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@362f0d54: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,AgeEnricher,ClubEnricher,PlayerDetailsConverter,finalListenerImpl,playerDetailsSenderImpl,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,activeMQConnectionFactory,cachingConnectionFactory,origin,destination,producerTemplate,originPlayerSender,destinationListenerImpl,jmsDestinationContainer,oxmMessageConverter,enrichingService,marshaller,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
2012-11-22 22:52:07,224 INFO  [main] org.springframework.oxm.jaxb.Jaxb2Marshaller:436 Creating JAXBContext with classes to be bound [class pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails]
2012-11-22 22:52:07,628 INFO  [main] org.springframework.context.support.DefaultLifecycleProcessor:334 Starting beans in phase 2147483647
2012-11-22 22:52:07,883 INFO  [main] org.springframework.jms.connection.CachingConnectionFactory:291 Established shared JMS Connection: ActiveMQConnection {id=ID:marcin-SR700-53586-1353621127755-1:1,clientId=null,started=false}
2012-11-22 22:52:08,093 DEBUG [main] pl.grzejszczak.marcin.camel.manual.jms.PlayerDetailsSenderImpl:26 Sending [pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails@3ea86d12] to topic [topic://Initial.Topic]
2012-11-22 22:52:12,463 DEBUG [jmsDestinationContainer-1] pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl:35 Message already enriched! Shutting down the system

First we see that our spring Context has been initialized and then we see that a message has been sent to the Initial.Topic. At the end of the processing we can see that the listener is confirming that the message has been properly enriched - so all the Camel work has been done in a proper way.

This example is showing how easy and simple it can be to create a routing / enriching service by means of Spring and Camel (integrated with Spring).

The sources are available at Too Much Coding's repository at bitbucket.

Tuesday, November 6, 2012

Sources to blog posts

I am happy to announce that I managed to find some time in order to create a repository for the code that I've been presenting here (at least for the most of it). You can find the Too Much Coding sources by clicking here or type in the address https://bitbucket.org/gregorin1987/too-much-coding.

Enjoy :)

Sunday, November 4, 2012

Spring JMS, message automatic conversion, JMS template



Hi!

In one of my projects I was supposed to create a message router that like all routers was supposed to take the JMS messages from one topic and put it into another one. The message itself was a JMS text message that in fact contained an XML message. What is more after having received it I was supposed to enrich the message with some additional data.

We were not allowed to use neither Spring nor JAXB nor any other useful library so I decided to check how easy it would be to do it using them. Initially I wanted to use only Spring and JAXB but in the next post I will try to repeat the same scenario by using Apache Camel (that's why you will find the word "camel" in the package name). The JMS communication was present thanks to the ActiveMQ messaging server.

Anyway coming back to the code.

I used maven to resolve dependencies and these are the dependencies that were mandatory i n terms of JMS and JAXB and message conversion:

pom.xml

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-jms</artifactId>
   <version>3.1.1.RELEASE</version>
  </dependency>
  <dependency>
   <groupId>com.sun.xml.bind</groupId>
   <artifactId>jaxb-impl</artifactId>
   <version>2.2.6</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-oxm</artifactId>
   <version>3.1.1.RELEASE</version>
  </dependency>


This is how I divided the project (the camel part of the package will make more sense in the next article).



In order to have my message converted to objects via JAXB I needed a schema:

Player.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

 <xsd:element name="PlayerDetails">
  <xsd:complexType>
   <xsd:sequence>
    <xsd:element name="Name" type="xsd:string" />
    <xsd:element name="Surname" type="xsd:string" />
    <xsd:element name="Position" type="PositionType" />
    <xsd:element name="Age" type="xsd:int" />
    <xsd:element name="TeamName" type="xsd:string" />
   </xsd:sequence>
  </xsd:complexType>
 </xsd:element>


 <xsd:simpleType name="PositionType">
  <xsd:restriction base="xsd:string">
   <xsd:enumeration value="GK" />
   <xsd:enumeration value="DEF" />
   <xsd:enumeration value="MID" />
   <xsd:enumeration value="ATT" />
  </xsd:restriction>
 </xsd:simpleType>

</xsd:schema>

I had to download JAXB binaries and executed the following command to have my objects created:

./xjc.sh -p pl.grzejszczak.marcin.camel.jaxb.generated ~/PATH/TO/THE/SCHEMA/FILE/Player.xsd

Note: The same you can achieve by using maven. This approach is not in the blog's repository but believe me - it does work :D

Add dependency to pom

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.1</version>
</dependency>


Use the plugin (mind that the schema file needs to be specified or by default is searched for at src/main/xsd/ folder)


<build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.5.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>jaxb2-maven-plugin</artifactId>
                <version>1.5</version>
                <executions>
                    <execution>
                        <id>xjc</id>
                        <goals>
                            <goal>xjc</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <packageName>pl.grzejszczak.marcin.camel.jaxb.generated</packageName>
                </configuration>
            </plugin>
        </plugins>
    </build>

An example of the outcome of this command or maven plugin is the following:

PlayerDetails.java

//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 
// See http://java.sun.com/xml/jaxb 
// Any modifications to this file will be lost upon recompilation of the source schema. 
// Generated on: 2012.11.05 at 09:23:22 PM CET 
//


package pl.grzejszczak.marcin.camel.jaxb.generated;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;


/**
 * Java class for anonymous complex type.
 * 
 * 

The following schema fragment specifies the expected content contained within this class.
 * 
 * 

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="Surname" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="Position" type="{}PositionType"/>
 *         <element name="Age" type="{http://www.w3.org/2001/XMLSchema}int"/>
 *         <element name="TeamName" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 * 
* * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "name", "surname", "position", "age", "teamName" }) @XmlRootElement(name = "PlayerDetails") public class PlayerDetails { @XmlElement(name = "Name", required = true) protected String name; @XmlElement(name = "Surname", required = true) protected String surname; @XmlElement(name = "Position", required = true) protected PositionType position; @XmlElement(name = "Age") protected int age; @XmlElement(name = "TeamName", required = true) protected String teamName; /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } /** * Gets the value of the surname property. * * @return * possible object is * {@link String } * */ public String getSurname() { return surname; } /** * Sets the value of the surname property. * * @param value * allowed object is * {@link String } * */ public void setSurname(String value) { this.surname = value; } /** * Gets the value of the position property. * * @return * possible object is * {@link PositionType } * */ public PositionType getPosition() { return position; } /** * Sets the value of the position property. * * @param value * allowed object is * {@link PositionType } * */ public void setPosition(PositionType value) { this.position = value; } /** * Gets the value of the age property. * */ public int getAge() { return age; } /** * Sets the value of the age property. * */ public void setAge(int value) { this.age = value; } /** * Gets the value of the teamName property. * * @return * possible object is * {@link String } * */ public String getTeamName() { return teamName; } /** * Sets the value of the teamName property. * * @param value * allowed object is * {@link String } * */ public void setTeamName(String value) { this.teamName = value; } }
The @XmlRootElement(name = "PlayerDetails") means that this class will output a Root node in the XML file. The @XmlAccessorType(XmlAccessType.FIELD) as the JavaDoc says means that "Every non static, non transient field in a JAXB-bound class will be automatically bound to XML, unless annotated by XmlTransient." In other words, if you have a field annotated by the XmlTransient annotation it won't get serialized. Then we have the @XmlType(name = "", propOrder = { "name", "surname", "position", "age", "teamName" })which as JavaDoc sates "Maps a class or an enum type to a XML Schema type" . In other words our class is mapped to the PlayerDetails element in the schema. Finally we have the @XmlElement(name = "Name", required = true) annotation which is a mapping of the XML node (element) to a field in the class.

This is my message to be sent, received, enriched and routed:

RobertLewandowski.xml

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerDetails>
    <Name>Robert</Name>
    <Surname>Lewandowski</Surname>
    <Position>ATT</Position>
</PlayerDetails>

Now off to my JMS configuration - I have configured the Queues of origin and destination

jms.properties

jms.origin=Initial.Queue
jms.destination=Routed.Queue

This is my Spring configuration (I added comments inside the config that explain the origin of those components):

jmsApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jms="http://www.springframework.org/schema/jms" xmlns:oxm="http://www.springframework.org/schema/oxm"
 xsi:schemaLocation="http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

 <!-- Spring configuration based on annotations -->
 <context:annotation-config />
 <!-- Show Spring where to search for the beans (in which packages) -->
 <context:component-scan base-package="pl.grzejszczak.marcin.camel" />
 
 <!-- Show Spring where to search for the properties files -->
 <context:property-placeholder location="classpath:/camel/jms.properties" />

 <!-- The ActiveMQ connection factory with specification of the server URL -->
 <bean id="activeMQConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
  <property name="brokerURL" value="tcp://localhost:61616" />
 </bean>

 <!-- Spring's jms connection factory -->
 <bean id="cachingConnectionFactory"
  class="org.springframework.jms.connection.CachingConnectionFactory">
  <property name="targetConnectionFactory" ref="activeMQConnectionFactory" />
  <property name="sessionCacheSize" value="10" />
 </bean>

 <!-- The name of the queue from which we will take the messages -->
 <bean id="origin" class="org.apache.activemq.command.ActiveMQQueue">
  <constructor-arg value="${jms.origin}" />
 </bean>
 <!-- The name of the queue to which we will route the messages -->
 <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
  <constructor-arg value="${jms.destination}" />
 </bean>

 <!-- Configuration of the JmsTemplate together with the connection factory and the message converter -->
 <bean id="producerTemplate" class="org.springframework.jms.core.JmsTemplate">
  <property name="connectionFactory" ref="cachingConnectionFactory" />
  <property name="messageConverter" ref="oxmMessageConverter" />
 </bean>

 <!-- Custom message sender sending messages to the initial queue -->
 <bean id="originPlayerSender" class="pl.grzejszczak.marcin.camel.manual.jms.PlayerDetailsSenderImpl">
  <property name="destination" ref="origin" />
 </bean>
 <!-- Custom message sender sending messages to the destination queue -->
 <bean id="destinationPlayerSender" class="pl.grzejszczak.marcin.camel.manual.jms.PlayerDetailsSenderImpl">
  <property name="destination" ref="destination" />
 </bean>

 <!-- Custom message listener - listens to the initial queue  -->
 <bean id="originListenerImpl" class="pl.grzejszczak.marcin.camel.manual.jms.ListenerImpl"/>
 <!-- Custom message listener - listens to the destination queue  -->
 <bean id="destinationListenerImpl" class="pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl"/>

 <!-- Spring's jms message listener container - specified the connection factory, the queue to be listened to and the component that listens to the queue -->
 <bean id="jmsOriginContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
  <property name="connectionFactory" ref="cachingConnectionFactory" />
  <property name="destination" ref="origin" />
  <property name="messageListener" ref="originListenerImpl" />
 </bean>
 
 <!-- Spring's jms message listener container - specified the connection factory, the queue to be listened to and the component that listens to the queue -->
 <bean id="jmsDestinationContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
  <property name="connectionFactory" ref="cachingConnectionFactory" />
  <property name="destination" ref="destination" />
  <property name="messageListener" ref="destinationListenerImpl" />
 </bean>
 
 <!-- Message converter - automatically marshalls and unmarshalls messages using the provided marshaller / unmarshaller-->
 <bean id="oxmMessageConverter" class="org.springframework.jms.support.converter.MarshallingMessageConverter">
          <property name="marshaller" ref="marshaller" />
          <property name="unmarshaller" ref="marshaller" />
     </bean>

 <!-- Spring's JAXB implementation of marshaller - provided a class the JAXB generated class -->
     <oxm:jaxb2-marshaller id="marshaller">
          <oxm:class-to-be-bound name="pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails" />
     </oxm:jaxb2-marshaller>

</beans>

Now let's take a look at the Java code - let's start with the class that has the main function

ActiveMQRouter.java

package pl.grzejszczak.marcin.camel.manual;

import java.io.File;
import java.util.Scanner;

import javax.jms.JMSException;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import pl.grzejszczak.marcin.camel.jaxb.PlayerDetailsConverter;
import pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails;
import pl.grzejszczak.marcin.camel.manual.jms.Sender;

public class ActiveMQRouter {

 /**
  * @param args
  * @throws JMSException
  */
 public static void main(String[] args) throws Exception {
  ApplicationContext context = new ClassPathXmlApplicationContext("/camel/jmsApplicationContext.xml");
  @SuppressWarnings("unchecked")
  Sender<PlayerDetails> sender = (Sender<PlayerDetails>) context.getBean("originPlayerSender");

  Resource resource = new ClassPathResource("/camel/RobertLewandowski.xml");

  Scanner scanner = new Scanner(new File(resource.getURI())).useDelimiter("\\Z");
  String contents = scanner.next();

  PlayerDetailsConverter converter = context.getBean(PlayerDetailsConverter.class);

  sender.sendMessage(converter.unmarshal(contents));
 }
}

What we can see here is that we initialize the Spring context from the classpath and retrieve the bean named originPlayerSender. This component is used for sending a message to the initial queue. In order to have a message to send we are retrieving a file RobertLewandowski.xml from the classpath and read it to a String variable through the Scanner class. Next we use our custom PlayerDetailsConverter class to unmarshall the String contents into a PlayerDetails object, which in effect is sent by the originPlayerSender to the origin queue.

Now let's take a look at the sender logic:

PlayerDetailsSenderImpl.java
package pl.grzejszczak.marcin.camel.manual.jms;

import javax.jms.Destination;
import javax.jms.JMSException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails;

@Component
public class PlayerDetailsSenderImpl implements Sender<PlayerDetails> {

 private static final Logger LOGGER = LoggerFactory.getLogger(PlayerDetailsSenderImpl.class);

 private Destination destination;

 @Autowired
 private JmsTemplate jmsTemplate;

 @Override
 public void sendMessage(final PlayerDetails object) throws JMSException {
  LOGGER.debug("Sending [{}] to topic [{}]", new Object[] { object, destination });
  jmsTemplate.convertAndSend(destination, object);
 }

 public Destination getDestination() {
  return destination;
 }

 public void setDestination(Destination destination) {
  this.destination = destination;
 }

}

This class is implementing my Sender interface that provides the sendMessage function. We are using the JmsTemplate object to convert and send the message to the given destination that is injected via Spring.

Ok, now that we've sent the message someone has to retrieve it:

ListenerImpl.java
package pl.grzejszczak.marcin.camel.manual.jms;

import java.util.List;

import javax.jms.BytesMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import pl.grzejszczak.marcin.camel.enricher.Enrichable;
import pl.grzejszczak.marcin.camel.jaxb.Convertable;
import pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails;

@Component
public class ListenerImpl implements MessageListener {

 private static final Logger LOG = LoggerFactory.getLogger(ListenerImpl.class);

 @Autowired
 private Convertable<PlayerDetails> playerDetailsConverter;

 @Autowired
 private List<Enrichable<PlayerDetails>> listOfEnrichers;

 @Autowired
 private MessageConverter messageConverter;

 @Autowired
 @Qualifier("destinationPlayerSender")
 private Sender<PlayerDetails> sender;

 @Override
 public void onMessage(Message message) {
  if (!(message instanceof BytesMessage)) {
   LOG.error("Wrong msg!");
   return;
  }

  PlayerDetails playerDetails = null;
  try {
   playerDetails = (PlayerDetails) messageConverter.fromMessage(message);

   LOG.debug("Enriching the input message");
   for (Enrichable<PlayerDetails> enrichable : listOfEnrichers) {
    enrichable.enrich(playerDetails);
   }
   LOG.debug("Enriched text message: [{}]", new Object[] { playerDetailsConverter.marshal(playerDetails) });
   sender.sendMessage(playerDetails);
  } catch (Exception e) {
   LOG.error("Exception occured", e);
  }

 }

}

This class has the list of all the classes implementing the Enrichable interface thanks to which it will provide the enrichment of the message without the necessity of knowing the amount of enrichers in the system. There is also the PlayerDetailsConverter class that helps with marshalling and unmarshalling PlayerDetails. Once the message is enriched it is sent to the destination queue through the bean that implements the Sender interface and has the id of destinationPlayerSender. It is important to remember that what we receive from the queue is a BytesMessage thus that's why we are doing the initial check.

Let's take a look at one of the enrichers (the other one is a setting another field in the PlayerDetails object)

ClubEnricher.java
package pl.grzejszczak.marcin.camel.enricher;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails;

@Component("ClubEnricher")
public class ClubEnricher implements Enrichable<PlayerDetails> {

 private static final Logger LOGGER = LoggerFactory.getLogger(ClubEnricher.class);

 @Override
 public void enrich(PlayerDetails inputObject) {
  LOGGER.debug("Enriching player [{}] with club data", new Object[] { inputObject.getSurname() });
  // Simulating accessing DB or some other service
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   LOGGER.error("Exception while sleeping occured", e);
  }
  inputObject.setTeamName("Borussia Dortmund");
 }

}

As you can see the class is just simulating some access to the DB or any other service and afterwards is setting the team name in the input PlayerDetails object.

Let's now take a look a the conversion mechanism:

PlayerDetailsConverter.java
package pl.grzejszczak.marcin.camel.jaxb;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.apache.activemq.util.ByteArrayInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails;

@Component("PlayerDetailsConverter")
public class PlayerDetailsConverter implements Convertable<PlayerDetails> {
 private static final Logger LOGGER = LoggerFactory.getLogger(PlayerDetailsConverter.class);

 private final JAXBContext jaxbContext;
 private final Marshaller jaxbMarshaller;
 private final Unmarshaller jaxbUnmarshaller;

 public PlayerDetailsConverter() throws JAXBException {
  jaxbContext = JAXBContext.newInstance(PlayerDetails.class);
  jaxbMarshaller = jaxbContext.createMarshaller();
  jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  jaxbUnmarshaller = jaxbContext.createUnmarshaller();
 }

 @Override
 public String marshal(PlayerDetails object) {
  OutputStream stream = new ByteArrayOutputStream();
  try {
   jaxbMarshaller.marshal(object, stream);
  } catch (JAXBException e) {
   LOGGER.error("Exception occured while marshalling", e);
  }
  return stream.toString();
 }

 @Override
 public PlayerDetails unmarshal(String objectAsString) {
  try {
   return (PlayerDetails) jaxbUnmarshaller.unmarshal(new ByteArrayInputStream(objectAsString.getBytes()));
  } catch (JAXBException e) {
   LOGGER.error("Exception occured while marshalling", e);
  }
  return null;
 }

}

In the constructor we are setting some JAXB components - the JAXBContext, JAXB Marshaller and JAXB Unmarshaller that have the necessary marshal and unmarshal methods.

Last but not least is the FinalListenerImpl that is listening to the inbound message from the destination queue and shuts the application.

FinalListenerImpl.java
package pl.grzejszczak.marcin.camel.manual.jms;

import javax.jms.BytesMessage;
import javax.jms.Message;
import javax.jms.MessageListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.stereotype.Component;

import pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails;

@Component
public class FinalListenerImpl implements MessageListener {

 private static final Logger LOG = LoggerFactory.getLogger(FinalListenerImpl.class);

 @Autowired
 private MessageConverter messageConverter;

 @Override
 public void onMessage(Message message) {
  if (!(message instanceof BytesMessage)) {
   LOG.error("Wrong msg!");
   return;
  }

  PlayerDetails playerDetails = null;
  try {
   playerDetails = (PlayerDetails) messageConverter.fromMessage(message);

   if (playerDetails.getTeamName() != null) {
    LOG.debug("Message already enriched! Shutting down the system");
    System.exit(0);
   } else {
    LOG.debug("The message should have been enriched but wasn't");
    System.exit(1);
   }

  } catch (Exception e) {
   LOG.error("Exception occured", e);
  }

 }

}

By using the MessageConverter, after having verified if the message is of proper type, we check if the team name has already been filled in - if that is the case we are terminating the application.

And the logs are as follows:

2012-11-05 [main] org.springframework.context.support.ClassPathXmlApplicationContext:495 Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@34fbb7cb: startup date [Mon Nov 05 21:47:00 CET 2012]; root of context hierarchy
2012-11-05 [main] org.springframework.beans.factory.xml.XmlBeanDefinitionReader:315 Loading XML bean definitions from class path resource [camel/jmsApplicationContext.xml]
2012-11-05 [main] org.springframework.beans.factory.config.PropertyPlaceholderConfigurer:177 Loading properties file from class path resource [camel/jms.properties]
2012-11-05 [main] org.springframework.beans.factory.support.DefaultListableBeanFactory:557 Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@3313beb5: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,myRoute,AgeEnricher,ClubEnricher,PlayerDetailsConverter,finalListenerImpl,listenerImpl,playerDetailsSenderImpl,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,activeMQConnectionFactory,cachingConnectionFactory,origin,destination,producerTemplate,originPlayerSender,destinationPlayerSender,originListenerImpl,destinationListenerImpl,jmsOriginContainer,jmsDestinationContainer,oxmMessageConverter,marshaller,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
2012-11-05 [main] org.springframework.oxm.jaxb.Jaxb2Marshaller:436 Creating JAXBContext with classes to be bound [class pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails]
2012-11-05 [main] org.springframework.context.support.DefaultLifecycleProcessor:334 Starting beans in phase 2147483647
2012-11-05 [main] org.springframework.jms.connection.CachingConnectionFactory:291 Established shared JMS Connection: ActiveMQConnection {id=ID:marcin-SR700-38535-1352148424687-1:1,clientId=null,started=false}
2012-11-05 [main] pl.grzejszczak.marcin.camel.manual.jms.PlayerDetailsSenderImpl:26 Sending [pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails@6ae2d0b2] to topic [queue://Initial.Queue]
2012-11-05 [jmsOriginContainer-1] pl.grzejszczak.marcin.camel.manual.jms.ListenerImpl:49 Enriching the input message
2012-11-05 [jmsOriginContainer-1] pl.grzejszczak.marcin.camel.enricher.AgeEnricher:17 Enriching player [Lewandowski] with age data
2012-11-05 [jmsOriginContainer-1] pl.grzejszczak.marcin.camel.enricher.ClubEnricher:16 Enriching player [Lewandowski] with club data
2012-11-05 [jmsOriginContainer-1] pl.grzejszczak.marcin.camel.manual.jms.ListenerImpl:53 Enriched text message: [<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<PlayerDetails>
    <Name>Robert</Name>
    <Surname>Lewandowski</Surname>
    <Position>ATT</Position>
    <Age>19</Age>
    <TeamName>Borussia Dortmund</TeamName>
</PlayerDetails>
]
2012-11-05 [jmsOriginContainer-1] pl.grzejszczak.marcin.camel.manual.jms.PlayerDetailsSenderImpl:26 Sending [pl.grzejszczak.marcin.camel.jaxb.generated.PlayerDetails@3dca1588] to topic [queue://Routed.Queue]
2012-11-05 [jmsDestinationContainer-1] pl.grzejszczak.marcin.camel.manual.jms.FinalListenerImpl:35 Message already enriched! Shutting down the system



This is how thanks to the Spring JMS module and the JAXB library you can easilly create JMS listeners, senders and message convertors for the XML messages.

Saturday, October 27, 2012

Spring AOP in security - controlling creation of UI components via aspects



The following post will show how in one of the projects that I took part in we used Spring's AOP to introduce some security related functionalities. The concept was such that in order for the user to see some UI components he needed to have a certain level of security privillages. If that requirement was not met then the UIComponent was not presented. Let's take a look at the project structure:


Then there were also the aopApplicationContext.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

 <aop:aspectj-autoproxy />
 <context:annotation-config />
 <context:component-scan base-package="pl.grzejszczak.marcin.aop">
  <context:exclude-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
 </context:component-scan>
 <bean class="pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor" factory-method="aspectOf"/> 

</beans>

Now let's take a look at the most interesting lines of the Spring's application context.

First we have all the required schemas - I don't think that this needs to be explained in more depth.
Then we have:
<aop:aspectj-autoproxy/>


which enables the @AspectJ support.

Next there is the

<context:annotation-config />
<context:component-scan base-package="pl.grzejszczak.marcin.aop">
    <context:exclude-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan>

first we are turning on Spring configuration via annotations. Then deliberatly we exclude aspects from being initialized as beans by Spring itself. Why? Because...

<bean class="pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor" factory-method="aspectOf"/>

we want to create the aspect by ourselves and provide the factory-method="aspectOf" . By doing so our aspect will be included in the autowiring process of our beans - thus all the fields annotated with the @Autowired annotation will get the beans injected.

Now let's move on to the code:

UserServiceImpl.java

package pl.grzejszczak.marcin.aop.service;

import org.springframework.stereotype.Service;

import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.user.UserHolder;

@Service
public class UserServiceImpl implements UserService {
 private UserHolder userHolder;

 @Override
 public UserHolder getCurrentUser() {
  return userHolder;
 }

 @Override
 public void setCurrentUser(UserHolder userHolder) {
  this.userHolder = userHolder;
 }

 @Override
 public Role getUserRole() {
  if (userHolder == null) {
   return null;
  }
  return userHolder.getUserRole();
 }
}

The class UserServiceImpl is immitating a service that would get the current user information from the db or from the current application context.

UserHolder.java

package pl.grzejszczak.marcin.aop.user;

import pl.grzejszczak.marcin.aop.type.Role;

public class UserHolder {
 private Role userRole;

 public UserHolder(Role userRole) {
  this.userRole = userRole;
 }

 public Role getUserRole() {
  return userRole;
 }

 public void setUserRole(Role userRole) {
  this.userRole = userRole;
 }
}


This is a simple holder class that holds information about current user Role.

Role.java

package pl.grzejszczak.marcin.aop.type;


public enum Role {
 ADMIN("ADM"), WRITER("WRT"), GUEST("GST");

 private String name;

 private Role(String name) {
  this.name = name;
 }

 public static Role getRoleByName(String name) {

  for (Role role : Role.values()) {

   if (role.name.equals(name)) {
    return role;
   }
  }

  throw new IllegalArgumentException("No such role exists [" + name + "]");
 }

 public String getName() {
  return this.name;
 }

 @Override
 public String toString() {
  return name;
 }
}

Role is an enum that defines a role for a person being an Admin, Writer or a Guest.

UIComponent.java

package pl.grzejszczak.marcin.aop.ui;

public abstract class UIComponent {
 protected String componentName;

 protected String getComponentName() {
  return componentName;
 }

}

An abstraction over concrete implementations of some UI components.

SomeComponentForAdminAndGuest.java

package pl.grzejszczak.marcin.aop.ui;

import pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation;
import pl.grzejszczak.marcin.aop.type.Role;

@SecurityAnnotation(allowedRole = { Role.ADMIN, Role.GUEST })
public class SomeComponentForAdminAndGuest extends UIComponent {

 public SomeComponentForAdminAndGuest() {
  this.componentName = "SomeComponentForAdmin";
 }

 public static UIComponent getComponent() {
  return new SomeComponentForAdminAndGuest();
 }
}

This component is an example of a UI component extention that can be seen only by users who have roles of Admin or Guest.

SecurityAnnotation.java

package pl.grzejszczak.marcin.aop.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

import pl.grzejszczak.marcin.aop.type.Role;

@Retention(RetentionPolicy.RUNTIME)
public @interface SecurityAnnotation {
 Role[] allowedRole();
}


Annotation that defines a roles that can have this component created.

UIFactoryImpl.java

package pl.grzejszczak.marcin.aop.ui;

import org.apache.commons.lang.NullArgumentException;
import org.springframework.stereotype.Component;

@Component
public class UIFactoryImpl implements UIFactory {

 @Override
 public UIComponent createComponent(Class<? extends UIComponent> componentClass) throws Exception {
  if (componentClass == null) {
   throw new NullArgumentException("Provide class for the component");
  }
  return (UIComponent) Class.forName(componentClass.getName()).newInstance();
 }
}


A factory class that given the class of an object that extends UIComponent returns a new instance of the given UIComponent.

SecurityInterceptor.java


package pl.grzejszczak.marcin.aop.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.util.Arrays;
import java.util.List;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation;
import pl.grzejszczak.marcin.aop.service.UserService;
import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.ui.UIComponent;

@Aspect
public class SecurityInterceptor {
 private static final Logger LOGGER = LoggerFactory.getLogger(SecurityInterceptor.class);

 public SecurityInterceptor() {
  LOGGER.debug("Security Interceptor created");
 }

 @Autowired
 private UserService userService;

 @Pointcut("execution(pl.grzejszczak.marcin.aop.ui.UIComponent pl.grzejszczak.marcin.aop.ui.UIFactory.createComponent(..))")
 private void getComponent(ProceedingJoinPoint thisJoinPoint) {
 }

 @Around("getComponent(thisJoinPoint)")
 public UIComponent checkSecurity(ProceedingJoinPoint thisJoinPoint) throws Throwable {
  LOGGER.info("Intercepting creation of a component");

  Object[] arguments = thisJoinPoint.getArgs();
  if (arguments.length == 0) {
   return null;
  }

  Annotation annotation = checkTheAnnotation(arguments);
  boolean securityAnnotationPresent = (annotation != null);

  if (securityAnnotationPresent) {
   boolean userHasRole = verifyRole(annotation);
   if (!userHasRole) {
    LOGGER.info("Current user doesn't have permission to have this component created");
    return null;
   }
  }
  LOGGER.info("Current user has required permissions for creating a component");
  return (UIComponent) thisJoinPoint.proceed();
 }

 /**
  * Basing on the method's argument check if the class is annotataed with
  * {@link SecurityAnnotation}
  * 
  * @param arguments
  * @return
  */
 private Annotation checkTheAnnotation(Object[] arguments) {
  Object concreteClass = arguments[0];
  LOGGER.info("Argument's class - [{}]", new Object[] { arguments });
  AnnotatedElement annotatedElement = (AnnotatedElement) concreteClass;
  Annotation annotation = annotatedElement.getAnnotation(SecurityAnnotation.class);
  LOGGER.info("Annotation present - [{}]", new Object[] { annotation });
  return annotation;
 }

 /**
  * The function verifies if the current user has sufficient privilages to
  * have the component built
  * 
  * @param annotation
  * @return
  */
 private boolean verifyRole(Annotation annotation) {
  LOGGER.info("Security annotation is present so checking if the user can use it");
  SecurityAnnotation annotationRule = (SecurityAnnotation) annotation;
  List<Role> requiredRolesList = Arrays.asList(annotationRule.allowedRole());
  Role userRole = userService.getUserRole();
  return requiredRolesList.contains(userRole);
 }
}


This is the aspect defined at the pointcut of executing a function createComponent of the UIFactory interface. Inside the Around advice there is the logic that first checks what kind of an argument has been passed to the method createComponent (for example SomeComponentForAdminAndGuest.class). Next it is checking if this class is annotated with SecurityAnnotation and if that is the case it checks what kind of Roles are required to have the component created. Afterwards it checks if the current user (from UserService to UserHolder's Roles) has the required role to present the component. If that is the case thisJoinPoint.proceed() is called which in effect returns the object of the class that extends UIComponent.

Now let's test it - here comes the SpringJUnit4ClassRunner

AopTest.java

package pl.grzejszczak.marcin.aop;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import pl.grzejszczak.marcin.aop.service.UserService;
import pl.grzejszczak.marcin.aop.type.Role;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForAdmin;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForAdminAndGuest;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForGuest;
import pl.grzejszczak.marcin.aop.ui.SomeComponentForWriter;
import pl.grzejszczak.marcin.aop.ui.UIFactory;
import pl.grzejszczak.marcin.aop.user.UserHolder;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:aopApplicationContext.xml" })
public class AopTest {

 @Autowired
 private UIFactory uiFactory;

 @Autowired
 private UserService userService;

 @Test
 public void adminTest() throws Exception {
  userService.setCurrentUser(new UserHolder(Role.ADMIN));
  Assert.assertNotNull(uiFactory.createComponent(SomeComponentForAdmin.class));
  Assert.assertNotNull(uiFactory.createComponent(SomeComponentForAdminAndGuest.class));
  Assert.assertNull(uiFactory.createComponent(SomeComponentForGuest.class));
  Assert.assertNull(uiFactory.createComponent(SomeComponentForWriter.class));
 }
}


And the logs:

pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:26 Security Interceptor created
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForAdmin]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[ADM])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:70 Current user has required permissions for creating a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForAdminAndGuest]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[ADM, GST])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:70 Current user has required permissions for creating a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForGuest]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[GST])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:66 Current user doesn't have permission to have this component created
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:38 Intercepting creation of a component
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:48 Argument's class - [[class pl.grzejszczak.marcin.aop.ui.SomeComponentForWriter]]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:54 Annotation present - [@pl.grzejszczak.marcin.aop.annotation.SecurityAnnotation(allowedRole=[WRT])]
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:57 Security annotation is present so checking if the user can use it
pl.grzejszczak.marcin.aop.interceptor.SecurityInterceptor:66 Current user doesn't have permission to have this component created

The unit test shows that for given Admin role only first two components get created whereas for the two others nulls are returned (due to the fact that user doesn't have proper rights).

That is how in our project we used Spring's AOP to create a simple framework that would check if the user can have the given component created or not. Thanks to this after having programmed the aspects one doesn't have to remember about writing any security related code since it will be done for him.

If you have any suggestions related to this post please feel free to comment it :)

Wednesday, October 24, 2012

Mockito InvocationOnMock - checking an argument



Hi!

In one of my projects we had a very interesting situation in terms of testing. We couldn't mock an invocation of a static method due to the fact that PowerMock was not allowed to be used so there were plenty of objects and dependencies being initialized. What is more we were using a custom made dependency injection system that had a possibility of injecting a mock.

The problem was such that during a test we wanted to assert whether one of the objects was in a very precise state. This object was created using the new operator so we couldn't mock it (again no PowerMock allowed). Fortunately this object got passed to a method of an object that we could mock...

As presented below timeConsumingExternalService is an object that we could mock via the custom dependency injection system whereas the SomePojo class is an object whose state we would like to verify.

timeConsumingExternalService.processSomeObject(new SomePojo("name", "surname", 1, 1.0));

So what we did was that in our mock to which the object got passed we created a new Answer (the same Answer that I spoke of here). Due to which we could access the InvocationOnMock and the arguments passed to the method as such.

Mockito.doAnswer(new Answer<Object>() {
   public Object answer(InvocationOnMock invocation) throws Throwable {
    Object[] object = invocation.getArguments();

      if (object.length > 0) {
          SomePojo somePojo = (SomePojo) object[0];

          Assert.assertEquals("name", somePojo.getName());
          LOGGER.debug("Names are equal");
          Assert.assertEquals("surname", somePojo.getSurname());
          LOGGER.debug("Surnames are equal");
          Assert.assertTrue(1 == somePojo.getIntValue());
          LOGGER.debug("Ints are equal");
          Assert.assertTrue(1.0 == somePojo.getDoubleValue());
          LOGGER.debug("Doubles are equal");

          LOGGER.debug("Object being an argument of the function [" + String.valueOf(somePojo) + "]");
  }
    return null;
   }
  }).when(timeConsumingExternalServiceMock).processSomeObject(Mockito.any(SomePojo.class));

Of course the logs regarding the equalities are unnecessary since if they wouldn't be equal we would have an assertion exception - I left them for the purpose of this post.

And in the logs we can find:

pl.grzejszczak.marcin.ServiceIntegrationTest:48 Names are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:50 Surnames are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:52 Ints are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:54 Doubles are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:56 Object being an argument of the function [SomePojo [name=name, surname=surname, intValue=1, doubleValue=1.0]]

So in this way something that seems impossible to be verified can get verified :)

Update!

Thanks to Holger's suggestion I took a look at the ArgumentCaptor object and that is true that it is an elegant solution to retrieve information about the arguments executed on a method. Where InvocationOnMock can give you much more information and possibilities (for instance regarding the method being executed or just execute the real method) for this particular case a much more elegant, easier and faster way of dealing with the issue would be:


  //service that executes the external service
  executorService.execute(someTask);

  final ArgumentCaptor<SomePojo> argumentCaptor = ArgumentCaptor.forClass(SomePojo.class);
  Mockito.verify(timeConsumingExternalServiceMock).processSomeObject(argumentCaptor.capture());
  SomePojo somePojo = argumentCaptor.getValue();
  Assert.assertEquals("name", somePojo.getName());
  LOGGER.debug("Names are equal");
  Assert.assertEquals("surname", somePojo.getSurname());
  LOGGER.debug("Surnames are equal");
  Assert.assertTrue(1 == somePojo.getIntValue());
  LOGGER.debug("Ints are equal");
  Assert.assertTrue(1.0 == somePojo.getDoubleValue());
  LOGGER.debug("Doubles are equal");

The logs:
pl.grzejszczak.marcin.junit.SomeTask:26 Before processing an object
pl.grzejszczak.marcin.junit.SomeTask:28 After processing an object
pl.grzejszczak.marcin.ServiceIntegrationTest:75 Names are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:77 Surnames are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:79 Ints are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:81 Doubles are equal

Thanks again Holger!

More interesting articles

Next portion of interesting articles from dZone

Understanding JVM internals
How to analyze Java thread dumps
Practicing Code, Java, and Databases
10 Things I Never Want to See a Java Developer Do Again
jQuery Kwicks - Sexy Sliding Panels And Navigational Interaction
Why Do Bad Things Happen to Good Code?

and sth about Apache Camel

Tuesday, October 23, 2012

Hibernate inheritance table per subclass with different foreign key names



In one of the projects we were supposed to implement an inheritance in the db. The project based on Spring and Hibernate so we could pick one of the three inheritance methods. We decided to pick the inheritance of table for subclass. The problem as been discussed in many ways but it is not common that the names of the foreign keys are not equal to the name of the primary key.


This is a diagram of a database that will be used in our example. As far as logic goes - we have an abstraction called ABSENCE that can be either a recursive absence (REC_ABSENCE) or a month recursive absence (MONTH_REC_ABSENCE).

The recursive absence and the month recursive absence are differing from the absence in terms of data being held more than in terms of the behavior.

Of course from the logical point of view, this example can have little sense but it is just an example so don't focus on the business side.

Absence.java

package pl.grzejszczak.marcin.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;

/**
 * Absence generated by hbm2java
 */
@Entity
@Table(name = "ABSENCE")
@Inheritance(strategy = InheritanceType.JOINED)
public class Absence implements java.io.Serializable {
 /**
  * 
  */
 private static final long serialVersionUID = -4572952141587410338L;
 private int id;
 private int version;
 private Date startDate;
 private Date endDate;

 public Absence() {
 }

 @Id
 @Column(name = "ID", unique = true, nullable = false)
 @GeneratedValue(strategy = GenerationType.IDENTITY)
 public int getId() {
  return this.id;
 }

 public void setId(int id) {
  this.id = id;
 }

 @Version
 @Column(name = "VERSION", nullable = false)
 public int getVersion() {
  return this.version;
 }

 public void setVersion(int version) {
  this.version = version;
 }

 @Temporal(TemporalType.TIMESTAMP)
 @Column(name = "START_DATE", nullable = false, length = 23)
 public Date getStartDate() {
  return this.startDate;
 }

 public void setStartDate(Date startDate) {
  this.startDate = startDate;
 }

 @Temporal(TemporalType.TIMESTAMP)
 @Column(name = "END_DATE", length = 23)
 public Date getEndDate() {
  return this.endDate;
 }

 public void setEndDate(Date endDate) {
  this.endDate = endDate;
 }
}

RecursiveAbsence.java

Note that you do not have to explicitly create an id field. You define it by means of an annotation @PrimaryKeyJoinColumn with providing the name of the id column for the given entity (REC_ABSENCE_ID) and the name of the column for the id it is referencing (ID in the ABSENCE table).

package pl.grzejszczak.marcin.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

/**
 * 
 * Hibernate mapping strategy: Inheritance mapping: joined subclasses (table per
 * subclass)
 * 
 */
@Entity
@Table(name = "REC_ABSENCE")
@PrimaryKeyJoinColumn(name = "REC_ABSENCE_ID", referencedColumnName = "ID")
public class RecursiveAbsence extends Absence implements java.io.Serializable {

 /**
  * 
  */
 private static final long serialVersionUID = 1L;
 private boolean isMonthly;
 private boolean isWeekly;

 public RecursiveAbsence() {
 }

 @Column(name = "isMONTHLY", nullable = false, precision = 1, scale = 0)
 public boolean getIsMonthly() {
  return this.isMonthly;
 }

 public void setIsMonthly(boolean isMonthly) {
  this.isMonthly = isMonthly;
 }

 @Column(name = "isWEEKLY", nullable = false, precision = 1, scale = 0)
 public boolean getIsWeekly() {
  return this.isWeekly;
 }

 public void setIsWeekly(boolean isWeekly) {
  this.isWeekly = isWeekly;
 }
}

MonthRecursiveAbsence.java

Issue with the referencing of the column name as in the previous example.

package pl.grzejszczak.marcin.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name = "MONTH_REC_ABSENCE")
@PrimaryKeyJoinColumn(name = "MONTH_ABSENCE_ID", referencedColumnName = "ID")
public class MonthRecursiveAbsence extends Absence implements java.io.Serializable {

 /**
  * 
  */
 private static final long serialVersionUID = 7844275381822579686L;

 private Integer monthId;

 public MonthRecursiveAbsence() {
 }

 @Transient
 public MonthDefinitionEnum getMonth() {
  return MonthDefinitionEnum.getByKey(monthId);
 }

 @Column(name = "MONTH_ID")
 public Integer getMonthId() {
  return monthId;
 }

 public void setMonthId(Integer monthId) {
  this.monthId = monthId;
 }
}