Archive

Archive for the ‘jee-light’ Category

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

Playing with Yahoo Maps on PrimeFaces

August 4th, 2009 Shrihari No comments

Yahoo Map services expose REST web-services API which aid the consumer to retreive maps given a locations based on address (street, city, state or zip) or coordinates (longitude, latitude). This cool tip explores an option to render a Yahoo hosted map for a PrimeFaces driven application.

1) Login to Yahoo Developer Network and generate an Yahoo Developer Application ID.

2) Define and implement a PrimeFaces Controller which defines a MapMetadata POJO (containing address based attributes or coordinate based attributes) and defines a method to render the map accordingly.

@Controller(name = "mapController", scope = REQUEST)
public class YahooMapController
{   private String mapURL = new String();
    private boolean showMap = false;
    private MapMetadata map = new MapMetadata();
    //setters and accessors
    public void renderMapByAddress()
    {   StringBuilder query = new StringBuilder();
        String details = map.getStreet();
        query.append((details!=null)?"street=" + details + "&amp;":"");
        details = map.getCity();

        query.append((details!=null)?"city=" + details + "&amp;":"");
        details = map.getState();

        query.append((details!=null)?"state=" + details + "&amp;":"");
        details = map.getZip();

        query.append((details!=null)?"zip=" + details + "&amp;":"");
        details = map.getLatitude();

        query.append((details1!=null)?"latitude=" + details1 + "&amp;":"");
        details = map.getLongitude();

        query.append((details!=null)?"longitude=" + details + "&amp;":"");
       renderMap(query.toString());
    }

    private void renderMap(String query)
    {   if (query.length() > 0)
        {   try {
                query = query.replace(" ", "+");
                String requestquery = "http://local.yahooapis.com/MapsService/V1/mapImage?appid=[my-app-id]" + query;
                HttpClient client = new HttpClient();
                GetMethod method = new GetMethod(requestquery);
                int statusCode = client.executeMethod(method);
                if (statusCode != HttpStatus.SC_OK)
                {   FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERTY_ERROR, "Unable to find map based on details!", "Unable to find map based on details!"));
                    showMap = false;
                    return;
                }
                InputStream rstream = method.getResponseBodyAsStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(rstream));
		String line;
		int i = 0;
		while ((line = br.readLine()) != null)
                {   if (i == 1 &amp;&amp; line.contains("Result"))
                    {   mapURL = line.substring(62, line.length() - 9);
                        showMap = true;
                    }
                    i++;
		}
            } catch (IOException ex)
            {   ex.printStackTrace();
            }
        }
    }
}

The REST Get request is being placed using the Apache Commons HTTPClient library. The response from REST Get call is striped to fetch only the URL which displays the actual image of the Map.

3) Define and implement a XHTML page which defines a the view for accepting the location details and a rendering panel which is displayed if the map is successfully retrieved.

<ui:define name="content">
    <h:form>
        <h:messages/>
        <p:panel header="View Map">
          <h:panelGrid columns="2">
             <h:outputLabel value="Street :" for="street"></h:outputLabel>
             <h:inputText id="street" value="#{mapController.map.street}"/>

             <!-- Other input fields with labels accordingly -->

            <h:panelGroup>
             <h:commandButton action="#{mapController.renderMapByAddress}" value="Show Map" />
            </h:panelGroup>
          </h:panelGrid>
        </p:panel>
        <p:panel header="Map" rendered="#{mapController.showMap}">
           <h:panelGrid columns="1">
              <h:graphicImage value="#{mapController.mapURL}"/>
           </h:panelGrid>
        </p:panel>
     </h:form>
 </ui:define>

The graphicImage from JSF HTML taglib displays the URL generated image. One can also use the PrimeFaces dynamicImage Streaming (with StreamedContent)

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

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