Wednesday, March 28, 2012

Avoid i18n runtime exception

Recently a colleague came up with a nice tip of how to avoid some runtime exceptions causes by empty i18n key.

Very short and informative - enjoy :

Wednesday, March 14, 2012

Resolve circular dependency in Spring Autowiring

I would consider this post as best practice for using Spring in enterprise application development.

When writing enterprise web application using Spring, the amount of services in the service layer, will probably grow.
Each service in the service layer will probably consume other services, which will be injected via @Autowire .
The problem: When services number start growing, a circular dependency might occur. It does not have to indicate on design problem... It's enough that a central service, which is autowired in many services, consuming one of the other services, the circular dependency will likely to occur.

The circular dependency will cause the Spring Application Context to fail and the symptom is an error which indicate clearly about the problem:

Bean with name ‘*********’ has been injected into other beans [******, **********, **********, **********] in its raw version as part of a circular reference,

but has eventually been wrapped (for example as part of auto-proxy creation). This means that said other beans do not use the final version of the bean. This is often the result of over-eager type matching – consider using ‘getBeanNamesOfType’ with the ‘allowEagerInit’ flag turned off, for example.


 The problem in modern spring application is that beans are defined via @nnotations (and not via XML) and the option of allowEagerInit flag, simply does not exist.
The alternative solution of annotating the classes with @Lazy, simply did not work for me.

The working solution was to add default-lazy-init="true" to the application config xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true" xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    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 >
    <context:component-scan base-package="com.package">
       
    </context:component-scan>
    <context:annotation-config/>
   ...
</beans>

Hope this helps.  Not sure why it is not a default configuration.
If you have suggestion why this configuration might be not ok, kindly share it with us all.

Update:
Following redesign I had, this mentioned solution simply did not do the trick.
So I designed more aggressive solution to resolve that problem in 5 steps.

Good luck!

Wednesday, February 1, 2012

JPA 2.0 Metamodel generation using Eclipse Maven build

Update:
Please see this updated post in that manner which simplifies the process a bit better.


In order to write JPA2.0 queries using the criteria API in a type safe manner, one can use the corresponding @Entity generated metamodel.

This post is for developers who are familiar with this concept, and feel their current metamodel files generation process need improvement.

Over the web there are some guidelines regarding the best way to generate these static metamodel classes.
However, maybe it's just me, but I could not run them in a proper way.
Some methods generated the metamodel classes in the target directory and some simply did not work.
When running the metamodel generation tool, I had to set the pom file with the proc parameter manually with the "only" value and revert it when I wanted to generate the other java files.
(Very tedious when rapid model changes  are needed)

I would like to suggest a way to create the static metamodel files in the source directory (right beside the @Entities they refer)  AND run the build without modifying the pom/maven file.

The process is set from two steps:
1) Configure the POM.xml
2) Configure eclipse to run the build

So, first thing first - lets configure the pom file:




            org.hibernate

            hibernate-jpamodelgen

            1.1.1.Final

        

    

    

        

            

                maven-clean-plugin

                2.4.1

                

                  

                       

                     ../your_project_name/src/main/java/com/your_path/model/                     

                      

                        **/*_.java                       

                                           

                      false

                    

                  

                

              

           

            

                org.apache.maven.plugins

                maven-compiler-plugin

                2.3.2

                

                    1.7

                    1.7                                           

                    

                        org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor

                    

                    

                        ../your_project_name/src/main/java/

                    

                

            

        

    


The artifact is needed for the @Entity classes analysis and static Metamodel generation.
The maven-clean section is to clean the previous metamodel files (pattern: *_.java ) before generation (useful since the metamodel generation raise an error if any previous file already exist).
The maven-compileer section refer to the class with the metamodel generation class and set the target directory as the source directory (not the target!).

Next step is to define the eclipse maven build.
You can follow the below screenshots (sample build for project called "management"):


Configure the metamodel build:
Configure the project build:

  • For every "regular" build simply run the project build.
  • For any change in the @Entity files, run the compile metamodel build.

That's it..

Important note:
If you know how to run the two builds automatically one after the other, kindly leave a comment.

Tuesday, January 24, 2012

RESTful standard resolved! - part I

Latly I'm trying to build a web application which will be exposed in a RESTfull manner.
There are some general guideline and hints about how to define it, but no explicit standard or accepted schema structure to use.

After reading some info on the web, I think I manage to crack the pattern :-)
I would like to share the rules and structure I formed and hopefully to get some feedback about it and improve it, so please don't hesitate to leave notes and point any pain point that structure has.

The high level pattern is:
http(s)://server.com/app-name/{version}/{domain}/{rest-convention}

Where {version} is the api version this interface work with and {domain} is an area you wish to define for any technical (e.g. security - allow certain users to access that domain) or business reason (e.g. gather functionality under same prefix).

The {rest-convention} denotes the set of REST API which is available under that domain.
It has the following convention:

  • singular-resourceX/
    • URL example: order/  (order is the singular resource X)
      • GET - will return a new order
      • POST - will create a new order. values are taken from the post content body.
  • singular-resourceX/{id} 
    • URL example: order/1 (order is the singular resource X)
      • GET - will return an order with the id 1
      • DELETE - will delete an order with the id 1
      • PUT - will update an order with the id 1.  Order values to update are taken from the post content body.

  • plural-resourceX/
    • URL example: orders/
      • GET - will return all orders
  • plural-resourceX/search
    • URL example: orders/search?name=123
      • GET - will return all orders that answer search criteria (QBE, no join) -order  name equal to 123
  • plural-resourceX/searchByXXX
    • URL example: orders/searchByItems?name=ipad
      • GET - will return all orders that answer the customized query - get all orders  that associated to items with name ipad
  • singular-resourceX/{id}/pluralY
    • URL example: order/1/items/ (order is the singular resource X, items is the plural resource Y)
      • GET - will return all items that associated to order #1
  •  singular-resourceX/{id}/singular-resourceY/
    • URL example: order/1/item/
      • GET - return a new item (transient) that is associated order #1
      • POST - create a new item and associate it to order  #1. Item values are taken from the post content body.
  •  singular-resourceX/{id}/singular-resourceY/{id}/singular-resourceZ/
    • URL example: order/1/item/2/package/
      • GET - return a new package (transient) that is associated to item 2 (i.e. how to pack the item) and is associated to order #1
      • POST - create a new package and associate it to item #2 & order #1. package values are taken from the post content body.

One basically can have further nesting as long as the above convention is maintained and no plural resource is defined after another plural resource.
There are further guidelines/notes to make things clear:
- When using plural resource, the returning instances will be those of the last plural resource used.
- When using singular resource the returning instance will be the last singular resource used.
- On search, the returning instances will be those of the last plural entity used.

Hopefully your insight will help me improve this structure and overcome issues which you might came across.

In next post, after this suggested structure will be improved, I will try to give technical examples how to implement it using Spring MVC 3.1


Friday, January 20, 2012

Advanced QBE pattern (common using generics)

On previous post I introduced the QBE pattern.

The pattern saves us a lot of tedious binding code.
However, one still need to implement the same method for each Entity.

To save us the redundant work of defining the same QBE method for each entity, where only the entity is changed, we could utilize Generics.

Using Generics we will implement only one method in a base class, and each concrete QBE (on certain @Entity) will inherit from that base class.


Lets see that in action.

First, we define the interface for the base class:

public interface BaseDAO {

   

    /**
     * Perform a query based on the values in the given object.
     * Each (String) attribute will be searched based on the Like comparison.
     * Comply the QueryByExample (QBE) pattern
     * @param modelEntity The Entity with values to search
     * @param propertiesToExclude Any property which the search will ignored.
     * @return Instances that answer the given parameters values (empty if none)
     */
    public List getByElementsLike(T modelEntity, List propertiesToExclude);   

    /**
     * Perform a query based on the values in the given object.
     * Each attribute will be searched based on the Equality comparison.
     * Comply the QueryByExample (QBE) pattern
     * @param modelEntity The Entity with values to search
     * @param propertiesToExclude Any property which the search will ignored
     * @return Instances that answer the given parameters values (empty if none)
     */
    public List getByElementsEqual(T modelEntity, List propertiesToExclude);

}



 Second step is to write the Base class implementation

public class BaseDaoImpl implements BaseDAO {
//Get DB session access using Spring 3.1 Entity Manger
     @PersistenceContext
    protected EntityManager em;
  
    protected Class entityClass;

   
     //Initialize the entity class
     @SuppressWarnings("unchecked")
    public BaseRepositoryImpl() {
            ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
            this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[0];
        }

    protected Class getEntityClass() {
        return entityClass;
    }   
  

    public List getByElementsLike(T modelEntity,List propertiesToExclude) {

        // get the native hibernate session
        Session session = (Session) em.getDelegate();

        // create an example from our model-entity, exclude all zero valued numeric properties
        Example example = Example.create(modelEntity).excludeZeroes().enableLike(MatchMode.ANYWHERE);

        for (String property : propertiesToExclude) {
            example.excludeProperty(property);
        }       

        // create criteria based on the customer example
        Criteria criteria = session.createCriteria(getEntityClass()).add(example);

        // perform the query       
        return criteria.list();

    }

    public List getByElementsEqual(T modelEntity,List propertiesToExclude) {

        // get the native hibernate session
        Session session = (Session) em.getDelegate();

        // create an example from our customer, exclude all zero valued numeric properties
        Example example = Example.create(modelEntity).excludeZeroes();

        for (String property : propertiesToExclude) {
            example.excludeProperty(property);
        }   

        // create criteria based on the customer example
        Criteria criteria = session.createCriteria(getEntityClass()).add(example);

        // perform the query       
        return criteria.list();
    }

}


Third step is to extend the base class:
@Entity

public class Order{
..
}

 

@Entity
public class Item{
..
}

 
public class OrderDaoImpl extends BaseDaoImpl implements
        BaseDao{

//No need to implement the QBE again here

}

public class ItemDaoImpl extends BaseDaoImpl implements
        BaseDao{

//No need to implement the QBE again here

}


Kindly let me know for any further improvements.

QBE pattern

When writing an enterprise system, there is a common pattern of a user who fill in a search form and get a corresponding result based on the given search parameters.

Handling this request manually in the backend is a bit tedious since for every search parameter, the developer need to check if the user insert a value and if so, concatenate the corresponding string into the WHERE clause in the SQL.

The Query By Example (QBE) pattern is a pattern that helps deal with the mentioned task.

It is implemented by ORM frameworks (such as Hibernate) and also avlaiable as part of possible to implement utilizing the the spec in JPA 2.0 (as seen in OpenJPA project)

The QBE implementation expect the model instance (the object which is annotated with @Entity).
That instance should have the form search values in it.
Than the implementation  framework does all the SQL wiring magic and save us the tedious work.
So at the end we just return the query result.

Lets discuss a case where a user want to query the Order object.

The Order class need to be annotated with @Entity


@Entity
public class Order{
..
}

Using a Hibernate implementation :
public List findByOrderElements(Order order) {

 Session session = getSession();

//Hibernate assembles the query with the given entity to query
 Example example = Example.create(order) //create Example object given the instance to query
     .enableLike(MatchMode.ANYWHERE) //optional parameters
     .excludeZeroes()
     .ignoreCase();

//Get the query result
 List result = session.createCriteria(Order.class)
     .add(example)
     .list();
        
 return result;
}


That's it...

Important note:
  • QBE will only work on one object (won't help in case the form input has properties of other related fields, i.e.  requires join)
  • Version properties, identifiers and associations are ignored (if QBE would consider the id than it would match only one instance...)

For even more advanced stuff regarding QBE pattern, please follow my next post.

Thursday, December 29, 2011

Unit Test on Spring via Maven - configuration tips



 This post is for newbies who set their project to run Spring powered Unit Tests via Maven.

There are many blogs who mention how to do it.
I would recommend to install STS IDE and create new Spring Template project.
It usually comes with built in Test package. The test package can be executed via JUnit.

The tricky part comes when you want to run the tests via Maven and set the Spring configuration xml file in your custom folder.

Using default setting, Maven might raise an exception complaining the Spring xml configuration file could not be found or Tests could not be found.

So, my two cents are:
cent 1: Make sure your test classes ends with Test (and not ending with Tests, for example, as it comes with the Spring default project)
cent 2: configuration can be resolved while defining the spring configuration path.
 The trick is to use the relative location as it is in the source folder, and not in the target compilation folder. Also note to use backslash as folder separation and not dots.

Configuration using classpath relative path:

@ContextConfiguration (value = "classpath:/com/company/app/OrderPersistenceTests-context.xml")

 @RunWith(SpringJUnit4ClassRunner.class)

public class OrderPersistenceTest {

...

}

or

Configuration using project relative path:

@ContextConfiguration (value = "file:src/test/resources/com/company/app/OrderPersistenceTests-context.xml ") 
@RunWith(SpringJUnit4ClassRunner.class)
public class OrderPersistenceTest {



...

} 


Run tests using maven:
If pom.xml has the skipTest tag with true as value, e.g.:

       

            

                org.apache.maven.plugins

                maven-surefire-plugin

                2.6

                 

                1.5

                1.7

               true

            

            

...


...

Then no test will be executed, even when explicitly executing maven with test goal


Good luck !