Enabling plain clustering on JBoss in 3 steps

July 13th, 2009 Shrihari No comments

This quick tip tells about enabling clustering on a existing non-all JBoss realm($JBOSS_HOME/server/all), say default realm ($JBOSS_HOME/server/default) (by default clustering with farming (hot-deployment) in enabled for ‘all’ realm).

1) Synchronize(copy) the lib/*.jar from all to the custom realm (eg. default)
2) Copy the cluster-service.xml  from ‘all’ to your custom realm and retain the mbean with code org.jboss.ha.framework.server.ClusterPartition, removing the other beans, as they are need for advanced configuration.Be-default, the discovery of the other nodes in the partition is identified by UDP configuration specified by PartitionConfig tag.
3) Copy the farm-service.xml from all/deploy.last to your custom realm directory.

Repeat these steps on all cluster instances.

Run the JBoss cluster server instances using

run -c [realm_id] -b 0.0.0.0

Note: If your cluster instance binds to localhost/127.0.0.1, you could bind to your actual IP

run -c [realm_id] -b x.x.x.x

You could read more at JBoss Clustering chapter

Categories: java-internals Tags:

Custom injection example in Google Guice

July 10th, 2009 Shrihari No comments

Google Guice supports custom injections using 2 endpoints: type listener and injection listener and registeration of end-points. You may read the whole theory behind here, where a Logging Injection using Log4J is explained.

Lets try to implement that and see what more is required. In order to test the whole exercise, we could embrace TestNG to write a sample unit test-case using a dummy class have a method.   Lets write a simple class which uses the Log4J Logger instance, injected using InjectLogger.

public class LoggingUsage  
{   @InjectLogger org.apache.log4j.Logger log;
     public int doAddition(int a,int b)
     {      int c = a+b;
           log.info("Added result: "+c);
           return c;
     }
}

Lets us now a write a TestNG testcase to try and test the same.
public class CustomLoggerInjectionTest
{ LoggingUsage logUsage;
@BeforeMethod
public void initLogUsage()
{ logUsage = Guice.createInjector(new LoggerModule(),new MyLoggerModule()).getInstance(LoggingUsage.class);
}

@Test
public void testLogUsage()
{ int value = logUsage.doAddition(20, 15);
assertEquals(value,35);
}

static class MyLoggerModule extends AbstractModule
{ @Override
protected void configure()
{ bind(LoggingUsage.class);
}
}
}
[/sourcecode]
Lets examine this testcase. Just before test execution, we register the LoggerModule, which binds the LOG4J specific listeners (type/injections) and custom module to bind our custom class which needs Logger injection we wrote above, and instantiate the class that uses this Logger instance. When the test executes, the usage-class would already have a injected Logger and would execute without issues.

Categories: Uncategorized Tags:

Using enums in DWR to populate select or multi-select

July 6th, 2009 Shrihari No comments

In case we need to population enumeration data in combo  box or multi-select widgets, in DWR (integrated on Spring), following is the approach:

1) In the spring’s applicationContext.
a) Add the method which returns the enum entity to <dwr:remote>
b) Add a dwr:convert tag of type ‘enum’ (as below)

<dwr:remote javascript="myoperations">
   <dwr:include method="getDataAsEnum"/>
   <dwr:convert type="enum"/>
</dwr:remote>

2) In the view (jsp) file, you could invoke the following javascript function

<body onload="loadEnumeration();">
function loadEnumeration()
{ myOperations.getDataAsEnum(callbackFunctionHandle);
};
var callbackFunctionHandle = function(data)
{   dwr.util.removeAllOptions('enum_select');
     dwr.util.addOptions('enum_select',['--Select--']);
     dwr.util.addOptions('enum_select', data);
}
Categories: Uncategorized Tags: ,

Resolving conflicts on DWR with jQuery

July 4th, 2009 Shrihari 1 comment

Since DWR’s util.js uses $ as an alias to ‘dwr.util.byId’ function, it may not have a smooth integration with jQuery as $ is also used by the latter as a function alias. In order to resolve this conflict, one could follow snippet:

<script type='text/javascript' src='/mycontext/js/jquery-1.3.2.min.js'></script>
<script type="text/javascript">
    var jq = jQuery.noConflict();
</script>
<script type='text/javascript' src='/mycontext/dwr/engine.js'></script>
<script type='text/javascript' src='/mycontext/dwr/util.js'></script>
<script type="text/javascript">
   jq(document).ready(function()
   {  //other function calls
   });
</script>

‘jq’ variable defined in place of $ to invoke the rest of other jQuery functions.

dwr/util.jsfor
Categories: Uncategorized Tags:

Integrating PrimeFaces with GuiceyFruit on JPA

July 1st, 2009 Shrihari No comments

Following suggestions from James Stratchan and Catagay Civici, I set my foot to integrate GuiceyFruit with JPA for the PrimeFaces tutorial I wrote.  You could download the example hosted there and try it. Here are the steps I followed on that Book-Store example and ended up with a cool working code.

1) Add the following repository to pom.xml

<repository>
 <id>guiceyfruit.release</id>
 <name>GuiceyFruit Release Repository</name>
 <url>http://guiceyfruit.googlecode.com/svn/repo/releases/</url>
 <snapshots>
 <enabled>false</enabled>
 </snapshots>
 <releases>
 <enabled>true</enabled>
 </releases>
 </repository>

2) Add the following dependencies

<dependency>
 <groupId>org.guiceyfruit</groupId>
 <artifactId>guiceyfruit-jpa</artifactId>
 <version>2.0-beta-7</version>
 </dependency>

3)  Comment/remove the following dependency

<!--dependency>
 <groupId>com.google.code.guice</groupId>
 <artifactId>guice</artifactId>
 <version>1.0</version>
 </dependency>

 <dependency>
 <groupId>aopalliance</groupId>
 <artifactId>aopalliance</artifactId>
 <version>1.0</version>
 </dependency-->

4) Open the dataservice bould concrete implementation (e.g. BookStoreImpl in the example) and replace @Inject with @javax.persistence.PeristenceContext.

public class BookStoreImpl implements BookStore
{  @PersistenceContext()
   private EntityManager em;
}

5)  Open the WEB-INF/web.xml and modify the context-param ‘optimus.CONFIG_MODULES’  like this

<context-param>
 <param-name>optimus.CONFIG_MODULES</param-name>
 <param-value>com.ts.pfaces.core.BookStoreModule
 ,org.primefaces.optimus.persistence.JPAModule
 ,org.guiceyfruit.jpa.JpaModule
 </param-value>
 </context-param>

And voila it works!

Categories: Uncategorized Tags:

Implementing a Unitils DAO testing infrastructure for Spring and JPA on TestNG

June 29th, 2009 Shrihari No comments

Unitils provides an excellant infrastructure for unit testing DAO (and data-service) layers  for Spring as IoC Framework on all the component unit testing frameworks such as JUnit 3, JUnit4 and TestNG, without any boilerplate code or coniguration hassles. We will look at establishing a testing infrastructure for Spring with JPA on TestNG frmaework.

Suppose the custom DAO and its implementation definition are like this (with regard to semantics of Spring JPA integration)

package mypackage;
public CustomDAO
{    public List findAll();
     public void save(Entity eo);
}
package mypackage;
public CustomDAOImpl implements CustommmDAO
{   @PersistenceContext
    private EntityManager em;
    //all other method implementations..
      ....
}

In order to setup a Unitils test infrastructure on TestNG, the following is the class-template:

public class CustomDAOTestCase extends UnitilsTestNG
{   /**
     * Injects a test specific application context configuration
     */
    @SpringApplicationContext
    public ConfigurableApplicationContext createApplicationContext()
    {  return new ClassPathXmlApplicationContext("applicationContext-test.xml");
    }
     @SpringBean("customDAO")
     private CustomDAO customDAO;
     //all @Test annotated methods..
      @Override
      protected void unitilsAfterTestTearDown(java.lang.reflect.Method method)
      {}
}

for which the following would be the test specific Spring’s application context confguration (applicationContext-test.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://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="entityManagerFactory" >
 <property name="persistenceXmlLocation" value="persistence-test.xml"/>
 <property name="persistenceUnitName" value="customservice-test"/>
 </bean>

 <bean id="transactionManager">
 <property name="entityManagerFactory" ref="entityManagerFactory" />
 </bean>

 <tx:annotation-driven />

 <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

 <bean id="customDAO" class="mypackage.CustomDAOImpl"/>
</beans>

Look specifically at entityManagerFactory bean definition, org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean allows us to load test specific persistence.xml which could allow us to maintain more than onne persistence context for a sample application.
These two definitions extend the Spring’s JPA capabilities for unit testing DAO on Unitils infrastructure!

Categories: Uncategorized Tags: , ,

Overcoming pitfalls with Query cache in Hibernate

June 27th, 2009 Shrihari No comments

Query caching in Hibernate used to cache query state and results, has  multiple shortcomings if, not used judiciously. Some of the common pitfalls include:

(i) Query Cache structural representation is a QueryKey mapped to Object[][] (2-dimensional)  and holds majority of persistent object references. QueryKey represents query specific data such as the SQL Query text with parameters (positional/named). QueryKey representation would get deteriorated if parameters represent entity object or a deep rooted object hierarchy.

(ii) If multiple equivalents of load() is invoked,  there could potentially create multiple parameter versions of QueryKey containing equivalent duplicate entity objects exist in the cache.

Following are the patterns and practices that could be followed to fix these shortcomings:

1) Decorate org.hibernate.cache.StandardQueryCache and override the put() method to check if a canonical equivalent of a query results object already exist in the Object[][], and assign the same QueryKey if it exists. One needs to implement org.hibernate.cache.QueryCacheFactory also to plug into the Hibernate config.

2) Refactor the code to set entity’s keys as query parameters, rather than setting the entire entity object. Critreia representations should also use identifiers as parameters.

3) Write HQL queries to use identifiers in any substitutable parameters such as WHERE clause, IN clause etc.

4) Use positional parameters over named parameters as it could prevent using string pools.

5) If you are in a single JVM using in memory cache only, use hibernate.cache.use_structured_entries=false in your hibernate configuration.

Categories: Uncategorized Tags: ,

Hibernate Session's get() annd load() comparison

June 27th, 2009 Shrihari No comments

These are the differences I could readily understand when I was comparing the runtime behaviour of Hibernate Session’s get and load methods.

a)    get() does a database hit as soon as the method is called, load() makes a database hit, only if one of the field in the entity is called.

b)    load() should be used when the entity is assured that it exists in the database, else get() should be called. If an non-existent primary key is passed, get() returns a null directly. However passing a non-existing primary key to load() returns you a non-null entity object, but would throw this exception when a field of that entity is referenced: org.hibernate.ObjectNotFoundException: No row with the given identifier exists.

c)    calling a field in the entity in load() method after getTransaction().commit(), would throw a LazyInitializationException (could not initialize proxy – no Session).


Categories: Uncategorized Tags:

Dependency Injection's equivalent Java reflection invocations

June 24th, 2009 Shrihari No comments

As we know that there are 3 types of injections supported by any IoC framework, following are the equivalent function points in the reflection package (java.lang.reflect):

1) Constructor Injection -  <T> Constructor.newInstance(Object... initargs)
2) Method Injection    -     Object Method.invoke(Object obj, Object... args)
3) Field Injection -  void Field.set(Object obj, Object value)

Interestingly all these reflection classes are subclasses of java.lang.reflect.AccessibleObject and are final.  Also the complete mechanics of Injection semantics hinges on the accessible flag defined in java.lang.reflect.AccessibleObject. Please see javadocs for effective explanation.

Categories: Uncategorized Tags:

Using Google Guice to inject JPA EntityManager

June 23rd, 2009 Shrihari 5 comments

I am working on an persistence example using PrimeFaces, Google Guice and Hibernate. Following are the four steps to inject a JPA EntityManager into the Manager  (Appfuse parlance) / DAO Layer:

1) Define META-INF/persistence.xml containing JPA Configuration (similar to hibernate.cfg.xml)

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
 version="1.0">

 <persistence-unit name="persdb" transaction-type="RESOURCE_LOCAL">
 <provider>org.hibernate.ejb.HibernatePersistence</provider>
 <properties>
 ...
 </properties>
 </persistence-unit>

</persistence>

2) Create a startup controller Guice bean

@Controller(name="startupBean", startup=true)
public class StartupBean
{    public StartupBean()
      {}
}

3) Create a Google Guice Module

public class MyModule implements Module
{       public void configure(Binder binder)
          {   AnnotatedBindingBuilder bindingBuilder = binder.bind(MyDataService.class);
              ScopedBindingBuilder scopedBuilder = bindingBuilder.to(MyDataServiceImpl.class);
              scopedBuilder.in(SINGLETON);
          }
}

and create a context parameter in WEB-INF/web.xml

<context-param>
 <param-name>optimus.CONFIG_MODULES</param-name>
 <param-value>mypackage.MyModule,org.primefaces.optimus.persistence.JPAModule
 </param-value>
 </context-param>

Note: org.primefaces.optimus.persistence.JPAModule actually injects the EntityManager reading the META-INF/persistence.xml

4) Create the DaraService implementation containing the injected EntityManager

public class MyDataServiceImpl implements MyDataService
{        @Inject
            private EntityManager em;
           //all methods using JPA entityManager here

}

No other configuration xmls to be changed. Ain’t it cool!

Categories: Uncategorized Tags: