Archive

Archive for September, 2009

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.

A Quick note about Hibernate Caching

September 14th, 2009 Shrihari No comments

1)    First Level Cache (Transaction Layer)

a) Associated with a Hibernate Session (transaction scoped) and this cache is used by Hibernate transparently. Hibernate requires a key to load object from the session cache. Hence its better to call a load() or get(), when the key(EntityKey) is known, rather than using a HQL query.
b) All queries (state of an entity, updates) in the cache gets flushed / committed to the database only when  Transaction context ends (i.e.) getTransaction().commit is called.
c) Always used and cannot be turned off.

2)    Second Level Cache (Application Layer)

a) Associated with a Hibernate’s SessionFactory (process scoped). Enabled by default in Hibernate 3 and uses EHCache as default cache provider.
b) The cache entries are dehydrated states of entity objects. A dehydrated state of entity refers to a key­-value  pair where key is the entity id (of the dehydrated entity) and the set of (deep copy) of attribute­values  (dehydrated entity fields) refer to the value.  Hibernate does not cache associations in a dehydrated object by default. One has to manually configured which association in a dehydratable entity to be cached.

Syntax : { id ­> { atribute1, attribute2, attribute3,{attribute41, attribute42},… } }

3)   Query cache (org.hibernate.cache.QueryCache)

a) Defines 2 cache regions : org.hibernate.cache.StandardQueryCache (stores query with parameters as cache key) and org.hibernate.cache.UpdateTimestampsCache (keeps stale query results of last results fetch). Both the cache regions are evicted when the entity related to the cacheable query is updated.

Syntax : { query,{parameters}} —> {id of cached entity}

b) A specific query results are cached, by specifying setCacheable(true) on Session’s Query handle.

1)    First Level Cache (Transaction Layer)

a) Associated with a Hibernate Session (transaction scoped) and this cache is used by Hibernate transparently. Hibernate requires a key to load object from the session cache. Hence its better to call a load() or get(), when the key(EntityKey) is known, rather than using a HQL query.

b) All queries (state of an entity, updates) in the cache gets flushed / committed to the database only when  Transaction context ends (i.e.) getTransaction().commit is called.

c) Always used and cannot be turned off.

2)    Second Level Cache (Application Layer)

a) Associated with a Hibernate’s SessionFactory (process scoped). Enabled by default in Hibernate 3 and uses EHCache as default cache provider.

b) The cache entries are dehydrated states of entity objects. A dehydrated state of entity refers to a key­-value  pair where key is the entity id (of the dehydrated entity) and the set of (deep copy) of attribute­values  (dehydrated entity fields) refer to the value.  Hibernate does not cache associations in a dehydrated object by default. One has to manually configured which association in a dehydratable entity to be cached.

Syntax : { id ­> { atribute1, attribute2, attribute3,{attribute41, attribute42},… } }

3)   Query cache (org.hibernate.cache.QueryCache)

a) Defines 2 cache regions : org.hibernate.cache.StandardQueryCache (stores query with parameters as cache key) and org.hibernate.cache.UpdateTimestampsCache (keeps stale query results of last results fetch). Both the cache regions are evicted when the entity related to the cacheable query is updated.

Syntax : { query,{parameters}} —> {id of cached entity}

b) A specific query results are cached, by specifying setCacheable(true) on session’s Query handle.

Adding Code Syntaxhiglighter plugin to Richfaces text editor

September 12th, 2009 Shrihari No comments

Exadel’s Richfaces Rich text editor integrates with TinyMCE javascript plugin to provide the rich text editor functions present in any document processing application. However often would be a need where we have to embed source code from a particular programming  language. In order to support embedding code in the richtext editor, the code should be surrounded wuth appropriate “pre” tags with options for the selected programming language. This particular tip explores integrating a SyntaxHighlighter plugin with Richfaces rich text editor, enabling the editor support for source code editing:

1) Download the sources from site.

2) Create a folder under ${contextroot}/js/tinymceplugins/syntaxhighlight and extract all the contents of the downloaded zip/sources here. Remember that the folder name should be ‘tinymceplugin’ as the TinyMCE javascript plugin looks for this folder for additional plugins if configured. Also note that ${contextroot} is your web application context root.

3) The different languages you need to support are present under ${contextroot}/js/tinymceplugins/syntaxhighlight/dialog.htm, where you retain only the relevant ones. For XML/XHTML support, you may need to add 2 additional lines, which would convert the XML tags to respective character equivalents in ${contextroot}/js/tinymceplugins/syntaxhighlight/js/dialog.js

content_text = f.syntaxhl_code.value.replace(/</g,"&lt;");
 content_text = content_text.replace(/>/g,"&gt;");
 textarea_output +=  content_text;

4) Create a properties file rteplugins.properties (name with custom plugins are resolved) with a property containing full path (relative with regard to ${contextroot}) of the editor_plugin.js from the downloaded sources as given below. Remember that property name used here (syntaxhl) is the plugin name used in the richtext editor configuration

syntaxhl=/js/tinymceplugins/syntaxhighlight/editor_plugin.js

5) The richfaces text editor configuration should be modified as below:

<rich:editor id="description" width="750" height="250" value="#{mybackingbean.description}"
 theme="advanced" viewMode="visual"  customPlugins="rteplugins" plugins="media,fullscreen,syntaxhl">
          <f:param name="theme_advanced_buttons1"  value="code,bold,italic,underline,fullscreen,justifyleft,justifycenter,justifyright,
                                    fontselect,fontsizeselect,styleprops,tablecontrols,syntaxhl,
                                    search,replace,selectall,media,forecolor,backcolor,cut,copy,paste"/>
          <f:param name="theme_advanced_toolbar_location" value="top" />
          <f:param name="theme_advanced_toolbar_align" value="left" />
          <f:param name="extended_valid_elements" value="pre[name|class]"/>
 </rich:editor>

Note: parameter ‘extended_valid_elements’ identifies valid tags that can be present in the text in raw HTML form.

Well now you are ready to use the rich text editor to contain code snippets. Lets also try to look at how to view code in highlighted format in the next tip.

Chaining Apache CXF, JackRabbit using SpringModules

September 11th, 2009 Shrihari 2 comments

Apache CXF integration with Spring and SpringModules support for Apache JackRabbit provides a nice combination for chaining command of actions to be delegated across layers of the enterprise application tiers . Here is a quick tip as how to do this. A more detailed tutorial has been hosted at http://bit.ly/TmmJx

1) Web application configuration (/WEB-INF/web.xml) snippet (as specified below) loads Apache CXF configuration (classpath:cxf.xml) and delegates to CXF container

<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:cxf.xml</param-value>
 </context-param>

 <servlet>
 <servlet-name>CXFServlet</servlet-name>
 <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 <servlet-name>CXFServlet</servlet-name>
 <url-pattern>/service/*</url-pattern>
 </servlet-mapping>

2) Apache CXF’s configuration (cxf.xml) loads the Spring context configuration

 <import resource="classpath:META-INF/cxf/cxf.xml" />
 <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
 <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
 <import resource="classpath:jcrcontext.xml"/>

where the SpringModules JCRContext configuration loads the JackRabbit’s RepositoryFactoryBean

<bean id="repository" class="org.springmodules.jcr.jackrabbit.RepositoryFactoryBean">
  <property name="configuration" value="classpath:repository.xml"/>
  <property name="homeDir" ref="./target/myrepository"/>
 </bean>

 <bean id="sessionFactory"  class="org.springmodules.jcr.jackrabbit.JackrabbitSessionFactory">
  <property name="repository" ref="repository" />
  <property name="credentials" ref="simpleCredentials"/>
 </bean>

 <bean id="jcrTemplate" class="org.springmodules.jcr.JcrTemplate">
  <property name="sessionFactory" ref="sessionFactory" />
  <property name="allowCreate" value="true" />
 </bean>

 <bean id="simpleCredentials" class="javax.jcr.SimpleCredentials">
  <constructor-arg index="0" value="bogus"/>
  <constructor-arg index="1">
   <bean factory-bean="password" factory-method="toCharArray"/>
  </constructor-arg>
 </bean>

 <bean id="password"  class="java.lang.String">
  <constructor-arg index="0" value="pass"/>
 </bean>

This chaining can be extended to any depth and a myriad range of implementation stacks could be acheived, if a container (Spring, Seam, Guice) offer support for seamless intra-container configuration and component resolution.

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