Tag Archives: Spring Framework

DIY Annotations

Since Java 5 there have been annotations in Java.  I wanted to make my own annotation just to see what it takes.  However, I found out that they were just interfaces.

There is the rub

Interfaces have no teeth behind them.  Some piece of code has to implement it.  I figured this is where the rubber hits the road and I really find a way to do this.

To start, I would need a purpose

I picked one recent hot topic, caching.  I didn’t want to implement JSR 109(JCache) but I didn’t want to do the typical “Hello World” either.  I picked implementing two annotations, one without any parameters and one with a parameter.  I also needed a caching provider.  Might as well bring a real caching library to the mix if I am going to do this.  It also follows my design philosophy to use products/libraries to reach  a goal instead of home spinning everything.  After careful consideration, I chose hazelcast to be my caching engine.  It is the fastest on the market and it is free.

More Decisions

After my purpose was chosen, I still needed to find out how to put teeth behind them.  After some digging around I found two methods:

Reflection

Almost every time I have used reflection, I have felt sorry for making such a clunky piece of code.  Plus, to do it the way I would like, I would have to create my own framework.  Sounds like a lot of work for two annotations.

Aspect Oriented Programming(AOP)

This was a perfect fit for what I wanted to do.  AOP deals in reducing boilerplate code into a single place.  This would be convenient and dovetails into caching because caching breaks down into the following steps:

  1. Check to see if this situation was done before.
  2. If so:
    1. retrieve the stored result
  3. if not:
    1. run the function
    2. store the result
  4. return the result

That maybe an oversimplification but in a nut shell it is true.  Like in all things, the devil is in the details.

Meanwhile, Back at the AOP Ranch

While I knew AOP was the place for me, I did not know much about it.  I found that Spring has an AOP library and that a well known library is AspectJ.  AspectJ is unfamiliar to me and needs a runtime engine to work.  I am much more familiar with Spring so I picked it.  As I dug into Spring’s AOP, I found that I had to delve into AspectJ’s annotations so I was stuck with AspectJ in some form or fashion anyway.

New Concepts, New Vocabulary

Writing aspects aren’t like writing objects.  They are objects but not really so, of course, a new set of terms are needed.  The ones I used are in the Spring AOP Documentation

I really needed to read the page a couple of times to grasp what is being said.  One is highly recommended to do the same or the rest of the post is going to sound like gibberish.

What Makes the Pointcut and How to Advise it

The pointcut design was easy since I was only interested in methods that had the annotation.  The advise it needed was the around advice because I needed to be able to circumvent calling the method if there was a matching call already done.

Finally the Code

Maven Pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.darylmathison</groupId>
    <artifactId>annotation-implementation</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <spring.version>4.2.4.RELEASE</spring.version>
    </properties>

    <description>
        This project is an example of how to implement an annotation via Spring AOP.
    </description>

    <scm>
        <url>https://github.com/darylmathison/annotation-implementation-example.git</url>
        <connection>scm:git:https://github.com/darylmathison/annotation-implementation-example.git</connection>
        <developerConnection>scm:git:git@github.com:darylmathison/annotation-implementation-example.git</developerConnection>
    </scm>

    <issueManagement>
        <system>GitHub</system>
        <url>https://github.com/darylmathison/annotation-implementation-example/issues</url>
    </issueManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.8</version>
        </dependency>

        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast</artifactId>
            <version>3.6</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <reporting>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-project-info-reports-plugin</artifactId>
                <version>2.7</version>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>dependencies</report>
                            <report>index</report>
                            <report>project-team</report>
                            <report>issue-tracking</report>
                            <report>scm</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-report-plugin</artifactId>
                <version>2.18.1</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-javadoc-plugin</artifactId>
                <version>2.10.3</version>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>javadoc</report>
                            <report>test-javadoc</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jxr-plugin</artifactId>
                <version>2.5</version>
                <configuration>
                    <linkJavadoc>true</linkJavadoc>
                </configuration>
                <reportSets>
                    <reportSet>
                        <reports>
                            <report>jxr</report>
                            <report>test-jxr</report>
                        </reports>
                    </reportSet>
                </reportSets>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-changelog-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <type>range</type>
                    <range>90</range>
                </configuration>
            </plugin>
        </plugins>
    </reporting>
</project>

The Annotations

CacheMe

Cute name for a caching annotation, right?

package com.darylmathison.ai.annotation;

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

/**
 * Created by Daryl on 2/19/2016.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface CacheMe {
}

CacheMeNow

package com.darylmathison.ai.annotation;

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

/**
 * Created by Daryl on 2/19/2016.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface CacheMeNow {
    String key();
}

Spring Configuration

I decided to use Java based configuration instead of XML like I normally use for a change of pace. The EnableAspectJAutoProxy annotation is key to getting Spring AOP to start working. I was beside myself until I read this about this little jewel. Sometimes it is the easiest thing that burns a day.

AppConfig

package com.darylmathison.ai.config;

import com.darylmathison.ai.cache.CacheAspect;
import com.darylmathison.ai.service.FibonacciService;
import com.darylmathison.ai.service.FibonacciServiceImpl;
import com.hazelcast.config.Config;
import com.hazelcast.config.EvictionPolicy;
import com.hazelcast.config.MapConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Daryl on 2/20/2016.
 */
@Configuration
@ComponentScan(basePackages = "com.darylmathison.ai")
@EnableAspectJAutoProxy
public class AppConfig {

    @Bean
    public Map<String, Object> cache() {
        Config config = new Config();
        MapConfig mapConfig = new MapConfig();
        mapConfig.setEvictionPercentage(50);
        mapConfig.setEvictionPolicy(EvictionPolicy.LFU);
        mapConfig.setTimeToLiveSeconds(300);
        Map<String, MapConfig> mapConfigMap = new HashMap<>();
        mapConfigMap.put("cache", mapConfig);
        config.setMapConfigs(mapConfigMap);

        HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
        return instance.getMap("cache");
    }

    @Bean
    public FibonacciService fibonacci() {
        return new FibonacciServiceImpl();
    }

    @Bean
    public CacheAspect cacheAspect() {
        return new CacheAspect();
    }
}

Service Code

Classic Spring based design needs a service right? Because Spring uses proxies to implement their AOP, it is highly advised to define an interface for the annotated class to implement.

FibonacciService

package com.darylmathison.ai.service;

/**
 * Created by Daryl on 2/20/2016.
 */
public interface FibonacciService {

    long calculate(int rounds);

    long calculateWithKey(int rounds);
}

FibonacciServiceImpl

package com.darylmathison.ai.service;


import com.darylmathison.ai.annotation.CacheMe;
import com.darylmathison.ai.annotation.CacheMeNow;

/**
 * Created by Daryl on 2/20/2016.
 */
public class FibonacciServiceImpl implements FibonacciService {

    @Override
    @CacheMe
    public long calculate(int rounds) {
        return sharedCalculate(rounds);
    }

    @Override
    @CacheMeNow(key = "now")
    public long calculateWithKey(int rounds) {
        return sharedCalculate(rounds);
    }

    private static long sharedCalculate(int rounds) {
        long[] lastTwo = new long[] {1, 1};

        for(int i = 0; i < rounds; i++) {
            long last = lastTwo[1];
            lastTwo[1] = lastTwo[0] + lastTwo[1];
            lastTwo[0] = last;
        }

        return lastTwo[1];
    }
}

AOP Stuff

This is heart of the annotation implementation. Everything else is support to do the source that follows.

SystemArch

According to Spring documentation, centralizing the pointcut definitions are a good idea.

package com.darylmathison.ai.cache;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * Created by Daryl on 2/20/2016.
 */
@Aspect
public class SystemArch {

    @Pointcut("@annotation(com.darylmathison.ai.annotation.CacheMe)")
    public void cacheMeCut() {

    }

    @Pointcut("@annotation(com.darylmathison.ai.annotation.CacheMeNow)")
    public void cacheMeNowCut() {

    }
}

CacheAspect

The Around annotations take the full method names of the pointcut class to define what to advise. The advice for the CacheMeNow annotation includes an extra condition so the annotation can be defined so the key parameter can be read. There is a design bug in CacheMeNow that is revealed in the test code.

package com.darylmathison.ai.cache;

import com.darylmathison.ai.annotation.CacheMeNow;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * Created by Daryl on 2/20/2016.
 */
@Aspect
public class CacheAspect {

    @Autowired
    private Map<String, Object> cache;

    @Around("com.darylmathison.ai.cache.SystemArch.cacheMeCut()")
    public Object simpleCache(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StringBuffer keyBuffer = new StringBuffer();
        for(Object o: proceedingJoinPoint.getArgs()) {
            keyBuffer.append(o.hashCode());
        }
        String key = keyBuffer.toString();
        Object ret = cache.get(key);
        if(ret == null) {
            ret = proceedingJoinPoint.proceed();
            cache.put(key, ret);
        }
        return ret;
    }

    @Around("com.darylmathison.ai.cache.SystemArch.cacheMeNowCut() && @annotation(cacheMeNow)")
    public Object simpleCacheWithParam(ProceedingJoinPoint proceedingJoinPoint, CacheMeNow cacheMeNow) throws Throwable {
        Object ret = cache.get(cacheMeNow.key());
        if(ret == null) {
            ret = proceedingJoinPoint.proceed();
            cache.put(cacheMeNow.key(), ret);
        }
        return ret;
    }
}

Test Code

Driver code to show that the annotations do cause caching.

FibonacciTest

package com.darylmathison.ai.service;

import com.darylmathison.ai.config.AppConfig;
import org.junit.Assert;
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;

/**
 * Created by Daryl on 2/20/2016.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class FibonacciTest {

    private static final int ROUNDS = 12;
    private static final long ANSWER = 377;

    @Autowired
    private FibonacciService fibonacci;

    @org.junit.Test
    public void testCalculate() throws Exception {
        long start = System.currentTimeMillis();
        Assert.assertEquals(ANSWER, fibonacci.calculate(ROUNDS));
        long middle = System.currentTimeMillis();
        Assert.assertEquals(ANSWER, fibonacci.calculate(ROUNDS));
        long end = System.currentTimeMillis();
        Assert.assertTrue((end - middle) < (middle - start));
    }

    @org.junit.Test
    public void testCalculateWithKey() throws Exception {
        Assert.assertEquals(ANSWER, fibonacci.calculateWithKey(ROUNDS));
        // This test should not pass
        Assert.assertEquals(ANSWER, fibonacci.calculateWithKey(13));
    }
}

Conclusion

Annotations do not have to be hard to implement. Using AOP programming, I was able to implement two annotations with little coding.  The code can be found here.

Advertisement

How to Configure a JPA Project Using Spring and Hibernate

Introduction

In most Java projects that involve a database, a ORM(Object Relational Mapping) layer is needed. This can be done by hand via JDBC. Spring does make the job easier however with a JdbcTemplate. The other way is to use one of the libraries that is popular is Hibernate. Another standard that is getting popular is JPA (Java Persistence API). The advantage of JPA is that it standardizes the API between ORM libraries and the DAO (Data Access Object) layer. This makes it easier to swap out different ORM libraries as requirements change. In this post I am going to show how to configure Hibernate with Spring using the JPA standard on a Java SE application.

Example

Maven pom.xml

Here is the pom.xml file used to pull the dependencies

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243;

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;

xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd&#8221; >

<modelVersion>4.0.0</modelVersion>

<groupId>org.mathison</groupId>

<artifactId>ForTheLittleGuy</artifactId>

<version>1.0-SNAPSHOT</version>

<packaging>jar</packaging>

<name>ForTheLittleGuy</name>

<url>http://maven.apache.org</url&gt;

<build>

<plugins>

<plugin>

<groupId>org.apache.maven.plugins</groupId>

<artifactId>maven-compiler-plugin</artifactId>

<version>2.3.2</version>

<configuration>

<source>1.7</source>

<target>1.7</target>

</configuration>

</plugin>

</plugins>

</build>

<repositories>

<repository>

<url>http://download.eclipse.org/rt/eclipselink/maven.repo/</url&gt;

<id>jpa20-persistence</id>

<layout>default</layout>

<name>Repository for library Persistence (JPA 2.1)</name>

</repository>

</repositories>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

</properties>

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>3.2.3.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>3.2.3.RELEASE</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-beans</artifactId>

<version>3.2.3.RELEASE</version>

</dependency>

<dependency>

<groupId>org.eclipse.persistence</groupId>

<artifactId>javax.persistence</artifactId>

<version>2.1.0-SNAPSHOT</version>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-entitymanager</artifactId>

<version>4.2.3.Final</version>

</dependency>

<dependency>

<groupId>org.hibernate.javax.persistence</groupId>

<artifactId>hibernate-jpa-2.0-api</artifactId>

<version>1.0.1.Final</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

<version>3.2.3.RELEASE</version>

</dependency>

<dependency>

<groupId>org.apache.derby</groupId>

<artifactId>derby</artifactId>

<version>10.10.1.1</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-orm</artifactId>

<version>3.2.3.RELEASE</version>

</dependency>

</dependencies>

</project>

Spring Files

main-config.xml

This is the main configuration file where the Spring framework configures Hibernate for its ORM layer. The context entries allow for annotations to be used to inject dependencies into classes.

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;

xmlns:context=”http://www.springframework.org/schema/context&#8221;

xmlns:tx=”http://www.springframework.org/schema/tx&#8221;

xmlns:jdbc=”http://www.springframework.org/schema/jdbc&#8221;

xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd

“>

<jdbc:embedded-database id=”dataSource” type=”DERBY”>

<jdbc:script location=”contact.sql”/>

<jdbc:script location=”InsertContacts.sql” />

</jdbc:embedded-database>

<tx:annotation-driven transaction-manager=”transactionManager”/>

<bean id=”transactionManager” class=”org.springframework.orm.jpa.JpaTransactionManager”>

<property name=”entityManagerFactory” ref=”emf”/>

<bean id=”emf” class=”org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean”>

<property name=”dataSource” ref=”dataSource”/>

<property name=”jpaVendorAdapter”>

<bean class=”org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter”/>

</property>

<property name=”packagesToScan” value=”org.mathison.fortlg.data”/>

<property name=”jpaProperties”>

<props>

<prop key=”hibernate.dialect”>

org.hibernate.dialect.DerbyTenSevenDialect

</prop>

<prop key=”hibernate.max_fetch_depth”>3</prop>

<prop key=”hibernate.jdbc.fetch_size”>50</prop>

<prop key=”hibernate.jdbc.batch_size”>10</prop>

<prop key=”hibernate.show_sql”>true</prop>

</props>

</property>

<context:annotation-config/>

<context:component-scan base-package=”org.mathison.fortlg”/>

</beans>

app-config.xml

This is a second configuration file that defines two profiles. Each profile defines a different implementation of a DAO.

<?xml version=”1.0″ encoding=”UTF-8″?>

<beans xmlns=”http://www.springframework.org/schema/beans&#8221;

xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;

xmlns:p=”http://www.springframework.org/schema/p&#8221;

xsi:schemaLocation=”http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd

http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd

http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd

“>

<beans profile=”criteria”>

<bean id=”contactDao” class=”org.mathison.fortlg.dao.ContactDaoCriteriaImpl”/>

</beans>

<beans profile=”jpql”>

<bean id=”contactDao” class=”org.mathison.fortlg.dao.ContactDaoJpqlImpl”/>

</beans>

</beans>

Conclusion

This is an example of how to define Hibernate as the JPA provider with the Spring Framework. These files plus the entire source code of the maven project can be found at http://fortlg.googlecode.com/svn/trunk/ForTheLittleGuy.

The JAXB Well Known Secret

Introduction

I rediscovered a library that Java offers to the masses. When I first read the specification, I was confused and thought I needed all these special tools to implement. I found recently that all was needed was some annotations and a POJO.

JAXB

JAXB stands for Java Architecture for XML Binding. This architecture allows a developer to turn the data from a class to be turned into a XML representation. This is called marshalling. The architecture also allows a developer to reverse the process turning a XML representation to be turned into a class. This is called unmarshalling. There are tools that can create Java classes from XML Schema files. The tool is called xjc. There is another tool that creates a xsd files by using schemagen.

Marshalling

Marshalling and unmarshalling happens several places in Java. The first I was exposed to this was RMI. Objects are sent over  being used as parameters for remote method calls, hence the name Remote Method Invocation (RMI). Another place it happens is writing objects to a stream. The streams that implement this are ObjectOutputStream and ObjectInputStream. Another place that it happens are ORM classes. Another way of course is writing a XML representation of an instance. Classes that want to be marshalled need to implement Serializable and all of its member attributes need to implement Serializable too with the exception of classes going through JAXB. Serializable is a marker interface. It has no methods to implement but it shows that a class can be serialized or marshalled. An object that has been marshalled has had its data put into some persistent fashion. Unmarshalled objects have had their data read from a persistent state and joined with a class. This makes classpaths very important. For a fun fact, a valid entry in a classpath is http://ip:port/path/to/jar. I imagine some organizations make use of this by centralizing their jar files and the latest version is just a download away.

Example

I used maven and spring to do this example. The reason was not to make it more complicated but to make the code cleaner to read and focus more on using the technology that I am showing. The dependencies in the pom.xml file are below:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0>

  <groupId>org.mathison>
  <artifactId>JAXBProject>
  <version>1.0-SNAPSHOT>
  <packaging>jar>

  <name>JAXBProject>
  <url>http://maven.apache.org>

  <properties>
    <project.build.sourceEncoding>UTF-8>
  >

  <dependencies>
    <dependency>
      <groupId>junit>
      <artifactId>junit>
      <version>4.11>
      <scope>test>
    >
    <dependency>
      <groupId>com.sun.xml.bind>
      <artifactId>jaxb-impl>
      <version>2.2.8-b01>
    >
    <dependency>
      <groupId>org.springframework>
      <artifactId>spring-core>
      <version>3.2.3.RELEASE>
    >
    <dependency>
      <groupId>org.springframework>
      <artifactId>spring-context>
      <version>3.2.3.RELEASE>
    >
    <dependency>
      <groupId>org.springframework>
      <artifactId>spring-beans>
      <version>3.2.3.RELEASE>
    >
  >
>

The wonderful thing about JAXB is that it uses POJOs. Contact.java is the central POJO class in the collection of three.

package org.mathison.jaxb.beans;

import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author Daryl Mathison
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Contact {
    private String lastName;
    private String firstName;
    private String middleName;
    private String jobTitle;
    
    @XmlElementWrapper(name = "addresses")
    @XmlElement(name = "address")
    private List<Address> addresses;
    
    @XmlElementWrapper(name = "phone-numbers")
    @XmlElement(name = "phone-number")
    private List<PhoneNumber> numbers;

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getJobTitle() {
        return jobTitle;
    }

    public void setJobTitle(String jobTitle) {
        this.jobTitle = jobTitle;
    }

    public List<Address> getAddresses() {
        return addresses;
    }

    public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
    }

    public List<PhoneNumber> getNumbers() {
        return numbers;
    }

    public void setNumbers(List<PhoneNumber> numbers) {
        this.numbers = numbers;
    }

    @Override
    public String toString() {
        return "Contact{" + "lastName=" + lastName + ", firstName=" + firstName + ", middleName=" + middleName + ", jobTitle=" + jobTitle + ", addresses=" + addresses + ", numbers=" + numbers + '}';
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 23 * hash + (this.lastName != null ? this.lastName.hashCode() : 0);
        hash = 23 * hash + (this.firstName != null ? this.firstName.hashCode() : 0);
        hash = 23 * hash + (this.middleName != null ? this.middleName.hashCode() : 0);
        hash = 23 * hash + (this.jobTitle != null ? this.jobTitle.hashCode() : 0);
        hash = 23 * hash + (this.addresses != null ? this.addresses.hashCode() : 0);
        hash = 23 * hash + (this.numbers != null ? this.numbers.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Contact other = (Contact) obj;
        if ((this.lastName == null) ? (other.lastName != null) : !this.lastName.equals(other.lastName)) {
            return false;
        }
        if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)) {
            return false;
        }
        if ((this.middleName == null) ? (other.middleName != null) : !this.middleName.equals(other.middleName)) {
            return false;
        }
        if ((this.jobTitle == null) ? (other.jobTitle != null) : !this.jobTitle.equals(other.jobTitle)) {
            return false;
        }
        
        if(!listEquals(this.addresses, other.addresses)) {
            return false;
        }
        
        if(!listEquals(this.numbers, other.numbers)) {
            return false;
        }
        return true;
    }
    
    private boolean listEquals(List first, List second) {
        for(Object o: first) {
            if(!second.contains(o)) {
                return false;
            }
        }
        return true;
    }
}

The main part to look at is the annotations. @XmlRootElement defines that this is the start of a class. @XmlAccessorType(XmlAccessType.FIELD) tells the architecture that the fields will be used to define the elements in the xml. The annotations can be put on the getters as well. If the annotation is not used, JAXB gets confused as to which to use. For instances where a list is present, @XmlElementWrapper is used to tell JAXB what the outer tag will be. For example, there are a list of addresses. The wrapper takes a parameter named “name” and it is filled with “addresses.” When the XML is rendered, there will be the tag “addresses” wrapped around the collection of addresses. The @XmlElement annotation is used when one wants to change the tag of a property. To come back to our address list, the annotation has redefined the addresses list to “address.” This will cause each address object to have a tag of “address” instead of “addresses” which is already taken up. The same pattern is used for numbers. The rest of the properties will be have tags that match the name of them. For example, lastName will be turned into the tag “lastName.” The other two POJOs, PhoneNumber.java and Address.java have public enum classes. Here is PhoneNumber.java:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mathison.jaxb.beans;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 * @author Daryl Mathison
 */
@XmlRootElement
public class PhoneNumber {
    @XmlType(name="phone-type")
    public enum Type {
        HOME,
        WORK,
        HOME_FAX,
        WORK_FAX;
    }
    
    private Type type;
    private String number;

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    @Override
    public String toString() {
        return "PhoneNumber{" + "type=" + type + ", number=" + number + '}';
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 37 * hash + (this.type != null ? this.type.hashCode() : 0);
        hash = 37 * hash + (this.number != null ? this.number.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final PhoneNumber other = (PhoneNumber) obj;
        if (this.type != other.type) {
            return false;
        }
        if ((this.number == null) ? (other.number != null) : !this.number.equals(other.number)) {
            return false;
        }
        return true;
    }
    
}

The annotation of note is @XmlType. This tells JAXB that a class of limited number of values. It takes a name parameter. The last POJO also uses @XmlType to define its public enum class. It can be found at Address.java.

Putting It All Together

With all of this annotation and class definition, it is time to pull it all together into one main class. Here is App.java, the main class:

package org.mathison.jaxb.app;

import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.mathison.jaxb.beans.Contact;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ApplicationContext cxt = new GenericXmlApplicationContext("jaxb.xml");
        Contact contact = cxt.getBean("contact", Contact.class);
        StringWriter writer = new StringWriter();
        try {
            JAXBContext context = JAXBContext.newInstance(Contact.class);

            //create xml from an instance from Contact
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            m.marshal(contact, writer);
            String xml = writer.getBuffer().toString();
            System.out.println(xml);
            
            //Take xml to Contact
            StringReader reader = new StringReader(xml);
            Unmarshaller u = context.createUnmarshaller();
            Contact fromXml = (Contact)u.unmarshal(reader);
            
            System.out.println("Are the instances equivalent: " + contact.equals(fromXml));
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

First, the instance of contact is retrieved from the ApplicationContext. Second, an instance of JAXBContext is created with the Contact class as the root class. The context will analyze the class structure and create a context that can marshall or unmarshall the Contact, Address and PhoneNumber classes. In the next section, a marshaller is created from the JAXBContext. The property, Marshaller.JAXB_FORMATTED_OUTPUT is set to true. This creates a XML output that is formatted. If the property was not set, the XML would come out as one line of text. The the marshaller is called to marshall contact and be written to a StringWriter. Then the XML is printed to System.out. The output should look like the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<contact>
    <lastName>Mathison>
    <firstName>Daryl>
    <middleName>Bob>
    <jobTitle>Developer>
    <addresses>
        <address>
            <addressLine>123 Willow View>
            <city>Cibolo>
            <state>TX>
            <type>HOME>
            <zipCode>78228>
        >
        <address>
            <addressLine>411 Grieg>
            <city>San Antonio>
            <state>TX>
            <type>WORK>
            <zipCode>78228>
        >
    >
    <phone-numbers>
        <phone-number>
            <number>210-123-4567>
            <type>WORK>
        >
        <phone-number>
            <number>210-345-1111>
            <type>HOME>
        >
    >
>

In the next section, the xml is unmarshalled back into an instance of Contact with its data. An Unmarshaller is created by the JAXBContext. Next, the unmarshaller is passed a StringReader with the just created XML as its contents. The Unmarshaller returns an Object that gets cast to a Contact. The original instance of Contact is tested against the new Contact instance to see if they are equivalent. The output should show:

Are the instances equivalent: true.

Summary

In this example, an instance of Contact was turned into XML and the resulting XML was turned back to a Contact instance with the help of JAXB. JAXB is an architecture that maps the state of an object into XML and maps XML back into an object.  The source code can be found here.

References

http://www.techrepublic.com/blog/programming-and-development/jaxb-20-offers-improved-xml-binding-in-java/498

http://www.vogella.com/articles/JAXB/article.html

http://en.wikipedia.org/wiki/JAXB

Solving a Puzzle with Spring

Introduction

Spring

Spring uses the Inversion of Control (IoC) pattern. There are many ways to do IoC. From what I can tell (please comment if I am entirely wrong) is that instead of creating the objects yourself, you have someone else do it for you. For example, EJB lookups with EJB 2.1 (You can still do this in EJB 3.1), the server gives you an instance of the object you want. Spring creates the objects for you through a BeanFactory or an ApplicationContext. The other pattern that gets thrown around in reference to Spring is Dependency Injection (DI). Many times IoC and DI can be interchangeable. The main thrust of DI is that to make objects as decoupled as possible. This happens by injecting the objects to an object rather than the object creating them. Spring uses a configuration file so it can know what beans it can inject. If a bean has a property with setters, the property can be set in the configuration. Here is an example of a property being set.

Randy

One can also populate a java collection like a java.util.List or java.util.Map. These are beyond the scope of this article. For now, one should know that a spring bean’s property can be set.

Puzzle

There are many puzzle books out there but the one I have is Dr. Ecco’s Cyberpuzzles by Dennis E. Shasha. I am up to puzzle number 2. The puzzles are given as stories with the puzzle changing throughout the story. There are many points in the story where the reader is challenged to solve the puzzle before going on. What is interesting from a software development perspective is that the requirements while changing are well defined. This makes it ideal for writing programs that can do the boring work for you while thinking about the solution.

The puzzle we are going to solve deals with Monopoles. In the story the person with the Jordan Tyler is talking to Dr. Ecco and his niece Liane. Jordan explains that they are going to ship monopoles into space for a mission. The company that makes the monopoles makes 52 kinds. Monopoles have interesting properties. They bind three kind at a time. Once bound, they are forever bound. If the conditions to bond do not exist, the monopoles neither attract nor repel each other. The formula for what monopoles will bind is x + y = z. For example, monopoles 1,2 and 3 will bond together as will 5, 3 and 8. For the purposes of the mission, bonded monopoles are worthless. They have discovered that a barrier of tungsten will block the attraction of monopoles that would normally bond together. The company launching the monopoles into space doesn’t want to fill their ship with a rare metal. The challenge is what is the smallest number of containers that can hold all 52 monopoles types without any of them bonding together.

Example

Model

Monopole types are going to be modeled as integers. I could create a monopole class and define a function that returns the type number but that would be an int. Monopoles will be held in Chambers. Chambers will know if a monopole can be added or not and will not allow a monopole that will bind to other monopoles to be added. Chambers will be inside Ships. Ships will know if a monopole can be held by querying its chambers. A ship can have chambers added if there is not enough to hold all 52 types.

Interfaces

In the interest of keeping dependencies low, I decided to make a couple of interfaces, one for Ship and one for Chamber.

Ship.java:
package ship;

import java.util.List;

import chamber.Chamber;

public interface Ship {

public void addMonopole(int monopole);

public boolean canAddMonopole(int monopole);

public void addChamber(Chamber chamber);

public List getChambers();

public int getNumChambers();

public void reset();

public String toString();

}
Noticed that I have addChamber() with a parameter of Chamber. This is so the dependency can be injected by the ApplicationContext. Normally, I would have the Ship create the Chamber internally. The reset method is to clear the chambers of their monopoles in preparation for another try.

Chamber’s interface is next:
package chamber;

import java.util.List;

public interface Chamber {

public void addMonopole(int monopole);

public boolean canAddMonopole(int monopole);

public int numMonopoles();

public List getMonopoles();

public void clear();

public boolean isEmpty();

public String toString();

}
This is a pretty simple interface. Basically, it is a list with a simpler interface. The canAddMonopole method is what prevents monopoles that would bond outside the chamber.

Chamber Implementation

Chambers do two things, hold monopoles and prevent monopoles from bonding. My solution to the problem is found below.

LinkedListChamber.java:
package chamber;

import java.util.Collections;

import java.util.HashSet;

import java.util.LinkedList;

import java.util.List;

import java.util.Set;

public class LinkedListChamber implements Chamber {

private List monopoles;

private Set monopoleTypeCache;

public LinkedListChamber() {

monopoles = new LinkedList();

monopoleTypeCache = new HashSet();

}

@Override

public void addMonopole(int monopole) {

if(monopole < 1 || monopole > 52) {

throw new IllegalArgumentException(“the range for monopole is 1 to 52”);

}

if(canAddMonopole(monopole)) {

addToCache(monopole);

monopoles.add(monopole);

}

}

@Override

public boolean canAddMonopole(int monopole) {

return !monopoleTypeCache.contains(new Integer(monopole));

}

@Override

public int numMonopoles() {

return monopoles.size();

}

@Override

public List getMonopoles() {

return Collections.unmodifiableList(monopoles);

}

@Override

public void clear() {

monopoles.clear();

monopoleTypeCache.clear();

}

@Override

public boolean isEmpty() {

return monopoles.isEmpty();

}

@Override

public String toString() {

return “LinkedListChamberImpl{” + “monopoles=” + monopoles + “}”;

}

private void addToCache(int monopole) {

List temp = new LinkedList();

for(int m: monopoles){

temp.add(m + monopole);

}

monopoleTypeCache.addAll(temp);

}

}
As one can see, there are two data structures keeping track of the monopoles. The first one is a java.util.List. This holds the monopoles. The other structure is a java.util.Set that holds the possible monopoles that would bond to two other monopoles held in the chamber if added. Entries are added before the monopole is entered.

Ship Implementation

A ship places the monopoles into chambers. The way that it does this affects how many chambers are needed to hold all 52 monopoles. I created three ways the chambers are filled. All but one method was common among them so I extracted an abstract class and extended it three times. Here is the AbstractShip class.

AbstractShip.java:
package ship;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import chamber.Chamber;

abstract class AbstractShip implements Ship {

protected List chambers = new ArrayList();

public void addChamber(Chamber chamber) {

if (chamber == null) {

throw new NullPointerException(“chamber is null”);

}

chambers.add(chamber);

}

@Override

public abstract void addMonopole(int monopole);

@Override

public boolean canAddMonopole(int monopole) {

boolean canAdd = false;

for (Chamber c : chambers) {

if (c.canAddMonopole(monopole)) {

canAdd = true;

break;

}

}

return canAdd;

}

@Override

public List getChambers() {

return Collections.unmodifiableList(chambers);

}

@Override

public int getNumChambers() {

return chambers.size();

}

@Override

public void reset() {

for (Chamber c : chambers) {

c.clear();

}

}

@Override

public String toString() {

return “Ship{” + “chambers=” + chambers + ‘}’;

}

}
As one can see, the abstract class just implements everything but one method, addMonopole(). Here is my first attempt at placing all of the monopoles, FirstChamberShip.

FirstChamberShip.java:
package ship;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import chamber.Chamber;

public class FirstChamberShip extends AbstractShip {

@Override

public void addMonopole(int monopole) {

if(canAddMonopole(monopole)) {

for(Chamber c: chambers) {

if(c.canAddMonopole(monopole)){

c.addMonopole(monopole);

break;

}

}

}

}

}
This ship just places the monopole in the first chamber that can hold the monopole. I did two more types of ships to see how low I could get the chamber count. The lowest I could get it to was four. The other two ship classes can be found at http://darylmathisonblog.googlecode.com/svn/trunk/Monopole/src/ship/MaxChamberShip.java and http://darylmathisonblog.googlecode.com/svn/trunk/Monopole/src/ship/MinChamberShip.java.

Factories

Whenever I use interfaces, I normally want to use a factory to hide the implementation. This involves making a singleton and defining a method that returns the instance of the class you want. Then if I want to have a more dynamic factory, I need to define a property that tells the factory what class to create. If this sounds like a pain, it is a pain. What would happen if one could create a factory in a line of xml? What if one could define a factory that could instantiate several different classes all by just setting a property in an XML file? Both of those factories are possible in Spring.

DI depends on factories. The dependency is injected in from an outside source. Spring implementing DI creates objects via its BeanFactory or its ApplicationContext. The basic line of code that uses a spring injection is like this:
chamber = cxt.getBean(“chamber”, Chamber.class);
The object is created by Spring, not by using new. By default, all beans are singletons. Imagine that, every time the above line is called the same object is returned. This can be used everywhere a singleton is needed. The line in the configuration file that creates the bean is:

There it is, a factory that creates a singleton. As long as one uses the same id or name, the same instance is returned. This would be a problem for adding chambers to a ship. There in effect would be only one chamber! The Spring framework has an attribute in the bean tag named “scope.” There are several types of scopes, the majority of them are used for web applications. The ones that I am interested in are singleton (default) and prototype. The prototype scope creates a different instance every time one injects the bean. This is ideal for adding new chambers into a ship. The configuration line is this:

The only change is adding the scope and setting it to prototype. This way does not depend on anything that is specific to Spring. This trick can be used in other IoC frameworks. There is a Spring factory interface. It is named org.springframework.beans.factory.FactoryBean. Requires the three methods to be implemented:
public <? > getObject() throws Exception;

public Class<?> getObjectType();

public boolean isSingleton();
There is another interface that I used and that is org.springframework.beans.factory.InitializingBean. This defines the method that is called after a property is set. The method is:
public void afterPropertiesSet() throws Exception;
To configure Spring to use a FactoryBean one uses the factory class at the class attribute. An example is below:

This line configures Spring to call the factory when the ApplicationContext is called to inject firstChamberShip. One can add properties to the factory to make it create different beans. As one can tell from the above example line, I used a factory bean to create the different types of ships. I created an enum class to choose which one is created. Here is the class:
package ship;

public enum ShipType {

FIRSTCOME,

LARGEST,

SMALLEST;

}
I created the property shipType and set in the configuration file. Here is the full factory bean class that I made to create the different ships.
package ship;

import org.springframework.beans.factory.FactoryBean;

import org.springframework.beans.factory.InitializingBean;

public class ShipFactory implements FactoryBean, InitializingBean{

private Ship ship;

private ShipType shipType = ShipType.FIRSTCOME;

@Override

public Ship getObject() throws Exception {

return ship;

}

@Override

public Class<?> getObjectType() {

return Ship.class;

}

@Override

public boolean isSingleton() {

return true;

}

@Override

public void afterPropertiesSet() throws Exception {

if(shipType == ShipType.FIRSTCOME){

ship = new FirstChamberShip();

} else if(shipType == ShipType.LARGEST){

ship = new MaxChamberShip();

} else if(shipType == ShipType.SMALLEST) {

ship = new MinChamberShip();

}

}

public void setShipType(ShipType shipType) {

this.shipType = shipType;

}

}
Notice that when after the properties are set, the member attribute ship is set. The FirstChamberShip is the default ship type for the factory.

Here is the full configuration file that defines the different beans used in the program.

LARGEST

SMALLEST

This is a simple configuration file. All it does is define four beans, one with a prototype scope and three using a FactoryBean.

Putting It All Together

This would not be a fair if I did not show how it all fits together in one place. To show how it all works, here is the main class, monopole.Monopole:
package monopole;

import chamber.Chamber;

import ship.Ship;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.GenericXmlApplicationContext;

public class Monopole {

public static void main(String[] args) {

ApplicationContext cxt =

new GenericXmlApplicationContext(“classpath:swing/monopole.xml”);

Ship maxShip = cxt.getBean(“maxChamberShip”, Ship.class);

Ship firstShip = cxt.getBean(“firstChamberShip”, Ship.class);

Ship minShip = cxt.getBean(“minChamberShip”, Ship.class);

run(firstShip, cxt);

run(maxShip, cxt);

run(minShip, cxt);

}

public static void run(Ship ship, ApplicationContext cxt) {

int numOfMono = 0;

Chamber chamber = cxt.getBean(“chamber”, Chamber.class);

ship.addChamber(chamber);

while (numOfMono < 52 && ship.getNumChambers() < 52){

for(int i = 1; i <= 52; i++) {

if (ship.canAddMonopole(i)){

numOfMono++;

ship.addMonopole(i);

} else {

numOfMono = 0;

chamber = cxt.getBean(“chamber”, Chamber.class);

ship.addChamber(chamber);

ship.reset();

break;

}

}

}

System.out.println(“largest num ” + numOfMono + ” with “

+ ship.getNumChambers() + ” chambers”);

System.out.println(ship);

}

}
The ships are defined then run is called to put them through their paces. Ships are given one chamber at first and seen if they can load all of the monopoles. If they cannot load all of the monopoles, they print out how many they could and how many chambers. If the number of chambers is greater than 52 then the number of chambers and what is in the chambers are printed out.

The source code project can be found at https://github.com/darylmathison/monopole-example. I used Netbeans 7.3 to develop the source code.

Conclusion

A puzzle was used to feature the different factory styles that can be done in the Spring Framework. One style is the standard bean definition. It can be customized to create different instances or a singleton. The other way is to create a FactoryBean. When using a FactoryBean, the class attribute of the bean definition is the FactoryBean. A property can be added to have different beans coming out of the same FactoryBean. Using both of these styles, I was able to test three different solutions to the monopole puzzle. I was able to only use four chambers to store all 52 monopoles.

References

  • Ho, Clarence and Harrop, Rob. Pro Spring 3. New York:Springer Science+Business Media, 2012. Print
  • Shasha, Dennis E. Doctor Ecco’s Cyberpuzzles. New York:W.W. Norton & Company, Inc. 2002. Print

Technologies I am Working on

I have been combining technologies for my For the Little Guy application described in the documents in the download section. Next post I am going to give a demonstration of how I combined Eclipse, Spring Framework and Maven. Currently work has been quite demanding so I have slipped on posts. Here are some links I have been using to make it all work.

Maven – http://maven.apache.com

Spring Framework – http://www.springsource.com/

Eclipse – http://www.eclipse.org

Maven Eclipse Tools – http://www.eclipse.org/m2e/