Archive

Archive for July, 2009

Injecting JPA EntityManager in Google Guice through JBoss Seam

July 31st, 2009 Shrihari No comments

This cool tip describes a 3 step process to use JPA’s EntityManager initialized in JBoss Seam inside the Google Guice environment.

1). Define Seam’s components.xml with entity-manager-factory component as below

<components>
    <persistence:entity-manager-factory name="my_persistence_unit"/>
    <guice:init injector="#{myInjector}"/>
    <guice:injector name="myInjector">
        <guice:modules>
           <value>mypackage.MyEntityManagerModule</value>
        </guice:modules>
    </guice:injector>
</components>

where my_persistence_unit is the persistence unit name under META-INF/persistence.xml.

2). Define a Google Guice Module to wire-up Seam’s EnitiyManagerFactory by looking-up based on the expression-value and binding it to Guice context using a Provider

public class MyEntityManagerModule extends AbstractModule
{   public void configure()
    {   Expressions expressions = Expressions.instance();
        ValueExpression emfVE = expressions.createValueExpression("#{my_persistence_unit}");
        EntityManagerFactory emf = (EntityManagerFactory)emfVE.getValue();
        EntityManagerProvider.setEntityManagerFactory(emf);
        bind(EntityManager.class).toProvider(EntityManagerProvider.class).in(Scopes.SINGLETON);
     }
 }
 
class EntityManagerProvider implements Provider
    {   static EntityManagerFactory entityManagerFactory = null;
        public EntityManager get()
        {   return entityManagerFactory.createEntityManager();
        }
    }
 

3) One could use the EntityManager anywhere in the Seam-Guice hybrid component:

@Name("hybrid")
@Guice
public class HybridDAO
{  @Inject EntityManager entityManager;
   //other DAO methods.
}

This makes Guice components use EntityManager normally use Seam established EntityManagerFactory

Categories: jee-light Tags: , ,

Method entry-exit logging in Google Guice through AOP

July 30th, 2009 Shrihari 1 comment

This cool tip explains 2 step logic to log all methods entry and exit information with profiling in Guice with AOP (aop-alliance)

1) Define a Guice Module with a method level logging Interceptor binding at all class levels and method levels.

public class MyModule extends AbstractModule
{     public void configure()
      {      bindInterceptor(Matchers.any(), Matchers.any(), new LoggingMethodInterceptor());
      }
}

2) Define a method level logging interceptor to log entry and exit messages with profiled information.

public class LoggingMethodInterceptor implements MethodInterceptor
{   public Object invoke(MethodInvocation invocation) throws Throwable
    {    Object returnValue = null;
    	 long start = System.currentTimeInMillis();
         System.out.println("Method "+invocation.getMethod()+" entered from "+invocation.getThis()+" with arguments "+invocation.getArguments());
         returnValue = invocation.proceed();
         long end = System.currentTimeInMillis();
         System.out.println("Method "+invocation.getMethod()+" exited in "+((end-start)/1000L)+" seconds");
         return returnValue;
    }
}

One could use this logic to extend and introduce many cross-cutting concerns such as Transaction Management, secure access to method

Categories: jee-light Tags: ,

Cool Code Search Engines

July 29th, 2009 Shrihari No comments

Stumbled on some of the cool code search engines for instant source code reference. Here are few:

1) http://codesearch.google.com – Code hosted on Google Code

2) http://grepcode.com – Maven repository based code search.

3) http://koders.com – Multi programming lingual search.

4) http://www.krugle.org/kse/ – Another language based search

5) http://www.ucodit.com – Neat organization of categories of code retreived.

6) http://www.codase.com/ – Another language based search offering category specific retreival.

Categories: java-internals Tags:

Establishing a webservice unit test infrastructure using Unitils on Apache CXF and Hibernate

July 16th, 2009 Shrihari No comments

Unitils is most preferred Spring based unit testing framework for unit testing DAOs and persistence layers. However using the power of inherent Spring support it has, added with flexible flavors on JUnit or TestNG, it could be extended to implement Web-services testing infrastructure such as Apache CXF which has persistence layer access through DAO layer, that gets rid of loads of boilerplate code we got to ensure, before a proxy gets initialized.

This quick tip addresses how to put in place a unit testing infrastructure, so that unit testing Apache CXF web-services becomes a easy task. We assume we would use TestNG flavor of Unitils for our understanding, using JUnit is equivalently similar, and Maven based POM.

1) Include the Unitils dependency with TestNG in ${basedir}/pom.xml as given below.

<dependency>
 <groupId>org.unitils</groupId>
 <artifactId>unitils</artifactId>
 <version>2.3</version>
 </dependency>

 <dependency>
 <groupId>org.testng</groupId>
 <artifactId>testng</artifactId>
 <version>5.8</version>
 <classifier>jdk15</classifier>
 <scope>test</scope>
 </dependency>

2) Add a Spring configuration file under ${basedir}/src/test/resources, say as client-test-config.xml and add the JAXWSProxyFactoryBean wiring so as to obtain a proxy object of the service exposed on a specific WSDL url.

<beans>
   <bean id="propConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="systemPropertiesMode" value="2"/>
     <property name="location" value="classpath:mytest.properties"/>
   </bean>

   <bean id="wsclient"  class="mypackage.MyServiceInterface" factory-bean="wsFactory" factory-method="create"/>

   <bean id="wsFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
      <property name="serviceClass" value="mypackage.MyServiceInterface"/>
      <property name="address" value="${myservice.wsdl.url}"/>
   </bean>
</beans>

3) Define a unit test-case using the Spring configuration file, to inject the proxy service bean, and invoke/unit test methods on the exposed service.

public class MyServiceTest extends UnitilsTestNG
{   @SpringApplicationContext
    public ConfigurableApplicationContext createApplicationContext()
    {  return new ClassPathXmlApplicationContext("client-test-config.xml");
    }

    @SpringBean("wsclient")
     private MyServiceInterface myService;</span>
      //All your unit test methods annotated with @Test here</span>
}

Thats it!. Your webservice unit test infrastructure for Apache CXF on Unitils is ready for adding test cases.

Categories: jee-light Tags: ,

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: