Archive

Posts Tagged ‘google-guice’

Integrating Hibernate Search on PrimeFaces using Google Guice and JBoss Seam

November 14th, 2009 Shrihari No comments

Recently I have been working on an application involving PrimeFaces and required search capabilities directly on the persisted data. Though I can use Hibernate search for implementing search services, the Google Guice, the underlying IoC framework, which PrimeFaces provide does not provide me the out-of-the-box integration. I am extending from my previous blog post which talked about using Google Guice to inject JPA EntityManager. This post builds on the previous post and explores the option of search. Here are the following sequence of steps I followed to ensure PrimeFaces widgets are Hibernate Search compliant:

1)  Follow the steps mentioned to get an EntityManager instance fro m JBoss Seam’s component xml and register in the Google Guice injector using a Provider  implementation. Make a little change where the Provider’s getter method is made static.  Following is the EntityManagerProvider code snippet to do that:

class EntityManagerProvider implements Provider
{       static EntityManagerFactory entityManagerFactory = null;
        public static EntityManager get()
        {   return entityManagerFactory.createEntityManager();
        }
}

2) Implement Guice injection Provider for constructing a FullTextEntityManager from EntityManager

public class FullTextEntityManagerProvider implements Provider
{    static FullTextEntityManager fullTextManager = null;
     private static EntityManager entityManager;

     public static void setEntityManager(EntityManager em)
     {   entityManager = em;
     }

      public FullTextEntityManager get()
      {   if(fullTextManager==null)
             fullTextManager = Search.getFullTextEntityManager(entityManager);
           return fullTextManager;
      }
}

3) Modify the custom module (now refactored as MySearchEntityManagerModule) to construct the FullTextEntityManager using EntityManager instance as shown below.

public class MySearchEntityManagerModule extends AbstractModule
{      public void configure()
       {   Expressions expressions = Expressions.instance();
           ValueExpression emfVE = expressions.createValueExpression("#{my_persistence_unit}");
           EntityManagerFactory emf = (EntityManagerFactory)emfVE.getValue();
           EntityManagerProvider.setEntityManagerFactory(emf);
           FullTextEntityManagerProvider.setEntityManager(provider.get());

            //bind EntityManager and FullTextEntityManager for both pure database and search specific integration
            bind(EntityManager.class).toProvider(EntityManagerProvider.class).in(Scopes.SINGLETON);
            bind(FullTextEntityManager.class).toProvider(FullTextEntityManagerProvider.class).in(Scopes.SINGLETON);
     }
}

3) Inject the FullTextEntityManager in the dataservice (DAO) for searching for text tokens using Hibernate Search.

@Name("hybrid")
@Guice
public class HybridDAO
{  @Inject FullTextEntityManager searchManager;
    //other DAO methods to perform search using Hibernate Search and Lucene
}

This quick tip provides us a capability of enhancing Primefaces widgets to use the power of Hibernate Search for search and much more extensible features.

Loading Spring Context from Google Guice

September 15th, 2009 Shrihari No comments

Using Spring framework in any application opens a plethora of opportunities with regard to resolving complex requirement needs in lieu of the number of extensible components available based on the Spring framework. Some of the most preferred specification based stacks (such as Apache CXF)  are coupled with Spring Framework, and it would call for a need to figure out options of getting the best of breed application stacks.

This particular entry looks at loading Spring Framework from Google Guice container. There are two approaches I have across till now, which I will try covering in breif:

1) Using Guice’s SpringIntegration

In this approach you need to download guice-spring.jar (version 1.0) or if your project is maven based, add the following dependency.

<dependency>
     <groupId>com.google.inject.integration</groupId>
     <artifactId>guice-spring</artifactId>
     <version>1.0</version>
</dependency>

You need to generalize an AbstractModule and use the com.google.inject.spring.SpringIntegration to load the Spring context into the Guice’s container.

import com.google.inject.spring.SpringIntegration;
import com.google.inject.AbstractModule;
//other imports...
public class SpringContextModule extends AbstractModule
{ @Override
   protected void configure()
   { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("appcontext-config.xml");
     SpringIntegration.bindAll(binder(), applicationContext);
    }
}

2) Using GuiceyFruit’s SpringModule

In this approach,  the dependency injection is based on JSR-250 common annotations specification and is resolved using the Spring annotation @Autowired (i.e.) all the beans have to be modified, introducing the annotation wherever the injection is required. This approach is suitable for all the beans for which we have control on the source code, and may not be a viable option for integration proven Spring modular components. In case if you have maven project, you need to include the below dependency:

 <dependency>
      <groupId>org.guiceyfruit</groupId>
      <artifactId>guiceyfruit-spring</artifactId>
      <version>2.0-beta-6</version>
    </dependency>

and create a Guice injector using

Injector injector = Guice.createInjector(new SpringModule());

More details can be looked at Guicey-Spring integration wiki page.

Approach 1 is prefered for integration of various most commonly used module component common both between Guice and Spring, as the configuration context can be reused, while the other approach is good enough for custom modules in Spring to be injected in Google Guice.

Using FreemarkerServlet in Google Guice to inject Configuration

September 5th, 2009 Shrihari No comments

Freemarker is a fantastic template parsing framework , and has its own avantages over Apache Velocity.  Google Guice is a straightforward injection framework which injects abstraction-driven ,instance-driven, or annotation driven module classes using bindings.  In order 2 get the best of both these frameworks, the following snippet would aid in doing so.

1) Modify the WEB-INF/web.xml to define FreemarkerServlet

<servlet>
 <servlet-name>freemarker</servlet-name>
 <servlet-class>com.ts.guicefmkr.web.TemplateServlet</servlet-class>
 <init-param>
 <param-name>TemplatePath</param-name>
 <param-value>/WEB-INF/ftl</param-value>
 </init-param>
 <init-param>
 <param-name>NoCache</param-name>
 <param-value>true</param-value>
 </init-param>
 <init-param>
 <param-name>ContentType</param-name>
 <param-value>text/html</param-value>
 </init-param>
 <init-param>
 <param-name>template_update_delay</param-name>
 <param-value>0</param-value>
 </init-param>
 <init-param>
 <param-name>default_encoding</param-name>
 <param-value>ISO-8859-1</param-value>
 </init-param>
 <init-param>
 <param-name>number_format</param-name>
 <param-value>0.##########</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>

2) Extend the FreemarkerServlet and implement to Guice’s Module to bind the created  Configuration object

import com.google.inject.Binder;
import com.google.inject.Injector;
import com.google.inject.Module;
import javax.servlet.ServletException;

import freemarker.ext.servlet.FreemarkerServlet;
import freemarker.template.Configuration;
public class TemplateServlet extends FreemarkerServlet implements Module
{   private Configuration templateConfig;
    public Configuration getTemplateConfig()
    {      return templateConfig;
    }

     public void setTemplateConfig(Configuration templateConfig) {
        this.templateConfig = templateConfig;
     }

    public void init() throws ServletException
     {   super.init();
         templateConfig = getConfiguration();
        Injector injector = com.google.inject.Guice.createInjector(this);
       }

      public void configure(Binder binder)
     {   binder.bind(Configuration.class).toInstance(templateConfig);
     }
}

Thus you could use Configuration object anywhere in your application using @Inject from Guice.

Categories: jee-light Tags: ,

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: ,

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: