<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:blogger='http://schemas.google.com/blogger/2008' xmlns:georss='http://www.georss.org/georss' xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-8553183304177435778</id><updated>2024-09-10T11:55:48.191-06:00</updated><category term="groovy"/><category term="AOP"/><category term="AspectJ"/><category term="Chart"/><category term="JFreeChart"/><category term="JSF"/><category term="annotation"/><category term="database"/><category term="java"/><category term="mapping"/><category term="template"/><title type='text'>Naveen&#39;s Blog</title><subtitle type='html'></subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default?redirect=false'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>10</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-8127588101867907466</id><published>2012-04-27T10:58:00.000-06:00</published><updated>2012-04-27T10:59:27.956-06:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="annotation"/><category scheme="http://www.blogger.com/atom/ns#" term="AOP"/><category scheme="http://www.blogger.com/atom/ns#" term="AspectJ"/><title type='text'>Avoid Null Parameters With Annotation</title><content type='html'>&lt;br/&gt;
In JEE6 there is a &lt;a href=&quot;http://docs.oracle.com/javaee/6/api/javax/validation/constraints/NotNull.html&quot;&gt;NotNull&lt;/a&gt; annotation which is of very limitted
 functionality. In my recent project I came across a requirement to check methods parameters for null. Writing if blocks in all the methods is not a good solution.
 So I decided to go with an AOP solution. I used AspectJ for all my AOP stuff in this blog.
 
 Here is what I did, I created an annotation called NotNull and an Aspect with Around pointcut to intercept method calls which has its
 parameters annotation with NotNull annotation.
 &lt;br/&gt;&lt;br/&gt;
 Now I will walk through the code. &lt;br/&gt;Code Snippet for NotNull Annotation:&lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 package org.naveen.maven.research.annotations;

 import java.lang.annotation.ElementType;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;

 @Retention(RetentionPolicy.RUNTIME)
 @Target(ElementType.PARAMETER)
 public @interface NotNull {
  /**
   * Message set in the exception thrown when parameter is null.
   */
  String message() default &quot;Parameter value is not nullable.&quot;;
  
  /**
   * Will specify how null values have to be treated. 
   */
  NotNullPolicy policy() default NotNullPolicy.THROW_EXCEPTION;
  
  /**
   * If you want to throw a custom exception. 
   * By default this will throw an IllegalArgument Exception.
   */
  Class&amp;lt;? extends Throwable&amp;gt; exception() default IllegalArgumentException.class;
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;
 Here is the NotNullPolicy enumeration:&lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 package org.naveen.maven.research.annotations;

 public enum NotNullPolicy {
  /** Irrespective of method body, method will return null if all arguments with this policy is null. */
  RETURN_NULL, 
  /** Will throw an exception. [Default] */
  THROW_EXCEPTION, 
  /** Don&#39;t do anything and will continue with method body */
  CONTINUE,
  /** Irrespective of method body, method will return null. */
  RETURN_NULL_IMMEDIATE
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;
 And here comes the backbone, the Aspect.
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 package org.naveen.maven.research.aspects;

 import java.lang.annotation.Annotation;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Method;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.logging.Level;
 import java.util.logging.Logger;

 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.Signature;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.reflect.MethodSignature;
 import org.naveen.maven.research.annotations.NotNull;
 import org.naveen.maven.research.annotations.NotNullPolicy;

 @Aspect
 public class NotNullAspect {
  
  private static final Logger logger = Logger.getLogger(NotNullAspect.class.getName());

  @Around(&quot;execution(* org.naveen..*(..,@NotNull (*),..)) &amp;&amp; &quot; +
    &quot;(!within(org.naveen.maven.research.annotations.*))&quot;)
  public Object doNullParamCheck(ProceedingJoinPoint jp) throws Throwable {
   List&amp;lt;Boolean&amp;gt; lazyNullRtValue = new LinkedList&amp;lt;Boolean&amp;gt;();
   boolean hasToContd = false;
   Object[] args = jp.getArgs();
   Signature sig = jp.getSignature();
   if(sig instanceof MethodSignature) {
    MethodSignature mtdSig = MethodSignature.class.cast(sig);
    Method mtd = mtdSig.getMethod();
    logger.log(Level.INFO, String.format(&quot;Checking parameters for method --&amp;gt; %s&quot;, mtd.getName()));
    Annotation[][] anns = mtd.getParameterAnnotations();
    
    for(int i=0;i&amp;lt;anns.length;++i) {
     if(anns[i].length &amp;gt; 0) {
      if(anns[i][0] instanceof NotNull) {
       NotNull ntnAnn = (NotNull) anns[i][0];
       logger.log(Level.INFO, String.format(&quot;NotNull handling policy is set to %s&quot;, ntnAnn.policy()));
       if(args[i] == null) {
        switch(ntnAnn.policy()) {
        case THROW_EXCEPTION:
         Class&amp;lt;? extends Throwable&amp;gt; expCls = ntnAnn.exception();
         logger.log(Level.INFO, String.format(&quot;Exception class set is %s&quot;, expCls.getName()));
         if(expCls == IllegalArgumentException.class) {
          throw new IllegalArgumentException(
           String.format(&quot;In Method %s --&amp;gt; %s&quot;, 
             mtd.getName(), ntnAnn.message()));
         } else {
          Constructor&amp;lt;? extends Throwable&amp;gt; ct = expCls.getConstructor(String.class);
          Throwable t = ct.newInstance(String.format(&quot;In Method %s --&amp;gt; %s&quot;, 
                  mtd.getName(), ntnAnn.message()));
          throw t;
         }
        case RETURN_NULL_IMMEDIATE:
         return null;
        case RETURN_NULL:
         logger.log(Level.WARNING, &quot;One NotNull annotated argument has null value. Continuing with lazy checking.&quot;);
         lazyNullRtValue.add(false);
         break;
        case CONTINUE:
         hasToContd = true;
         lazyNullRtValue.add(true);
         break;
        }
       } else {
        hasToContd = true;
        if(ntnAnn.policy() == NotNullPolicy.RETURN_NULL) 
         lazyNullRtValue.add(true);
       }
      }
     }
    }
   }
   logger.log(Level.INFO, String.format(&quot;Argument length is %d and LazyReturn list is %s and hasToContd %s&quot;, 
            args.length, lazyNullRtValue, hasToContd));
   if(hasToContd &amp;&amp; checkLazyNull(lazyNullRtValue)) 
    return jp.proceed();
   return null;
  }
  
  private boolean checkLazyNull(List&amp;lt;Boolean&amp;gt; list) {
   if(list.size() == 0) return true; 
   for(Boolean b : list)
    if(b) return b;
   return false;
  }
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 @Around(&quot;execution(* org.naveen..*(..,@NotNull (*),..)) &amp;&amp; &quot; +
   &quot;(!within(org.naveen.maven.research.annotations.*))&quot;)
 &lt;/div&gt;
 &lt;/pre&gt;
 Above code snippet will instruct AOP weaver to weave classes which satifies following conditions:
 &lt;ul&gt;
  &lt;li&gt;Which has methods which is declared inside classes which are declared in org.naveen package or sub package of it.&lt;/li&gt;
  &lt;li&gt;Which has methods whoose paramters are annotated with NotNull annotation.&lt;/li&gt;
  &lt;li&gt;Dont weave classes inside org.naveen.maven.research.annotations package or sub package of it.&lt;/li&gt;
 &lt;/ul&gt;
 &lt;br/&gt;
 Different Usage examples:&lt;br/&gt;
 Throws custom exception:&lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 public String test(String message, @NotNull(exception=ParameterException.class) String name) {
  return message + name;
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;
 Throws default exception with custom message:&lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 private String privateTest(@NotNull String message, @NotNull(message=&quot;Name cannot be null.&quot;) String name) {
  return message + name;
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 Method exists with Null:&lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 private String privateTest(@NotNull(policy=NotNullPolicy.RETURN_NULL_IMMEDIATE) String greet) {
  System.out.println(&quot;Message received is &quot; + greet);
  return &quot;Hello World &quot; + greet;
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 If you call above privateTest() method with a null argument, you don&#39;t see that System out getting executed.
 &lt;br/&gt;&lt;br/&gt;
 &lt;b&gt;Suppose if you have a scenario like this: &lt;/b&gt;&lt;br/&gt;
 &lt;ul&gt;
  &lt;li&gt;You have a method which will accept 2 arguments.&lt;/li&gt;
  &lt;li&gt;Method returns null, if both arguments are null.&lt;/li&gt;
  &lt;li&gt;Execute method, if one of the argument is not null.&lt;/li&gt;
 &lt;/ul&gt;
 &lt;b&gt;You can use NotNullPolicy.RETURN_NULL policy to instruct NotNull aspect to do a lazy null checking.&lt;/b&gt;
 &lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 private String privateTest(@NotNull(policy=NotNullPolicy.RETURN_NULL) String message, 
          @NotNull(policy=NotNullPolicy.RETURN_NULL, message=&quot;Name cannot be null.&quot;) String name) {
  System.out.println(&quot;Message received is &quot; + message);
  return &quot;Hello World &quot; + name;
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;
 &lt;b&gt;You can combine both NotNullPolicy.RETURN_NULL and NotNullPolicy.RETURN_NULL_IMMEDIATE together.&lt;/b&gt;
 &lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 private String privateTest(@NotNull(policy=NotNullPolicy.RETURN_NULL) String message, 
          @NotNull(policy=NotNullPolicy.RETURN_NULL_IMMEDIATE) String greet,
                      @NotNull(policy=NotNullPolicy.RETURN_NULL, message=&quot;Name cannot be null.&quot;) String name) {
  System.out.println(&quot;Message received is &quot; + message);
  return &quot;Hello World &quot; + name;
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;
 In the above example, we are saying :
 &lt;ul&gt;
  &lt;li&gt;Execute method body, if either of the arguments &#39;message&#39; or &#39;name&#39; is not null AND greet is not null.&lt;/li&gt;
  &lt;li&gt;Return Null, if both arguments &#39;message&#39; and &#39;name&#39; is null&lt;/li&gt;
  &lt;li&gt;Return Null, if argument &#39;greet&#39; is Null&lt;/li&gt;
 &lt;/ul&gt;
        &lt;br/&gt;&lt;br/&gt;
        All Resources used in this project are available in &lt;a href=&quot;https://github.com/javarebel/GitTesting&quot;&gt;My GitHub Repo&lt;/a&gt;.
 &lt;br/&gt;&lt;br/&gt;&lt;br/&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.config.bloggerMode = true;
 SyntaxHighlighter.defaults[&#39;toolbar&#39;] = false;
    SyntaxHighlighter.all()
&lt;/script&gt;</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/8127588101867907466/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2012/04/avoid-null-parameters-with-annotation.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/8127588101867907466'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/8127588101867907466'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2012/04/avoid-null-parameters-with-annotation.html' title='Avoid Null Parameters With Annotation'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-2256645453469748223</id><published>2012-04-25T10:55:00.002-06:00</published><updated>2013-01-23T19:22:47.263-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="groovy"/><category scheme="http://www.blogger.com/atom/ns#" term="java"/><category scheme="http://www.blogger.com/atom/ns#" term="template"/><title type='text'>Templatize Java Objects</title><content type='html'>&lt;br/&gt;

In my recent project, there is so many places we are using templates. Like web pages with user based custom messages and information, 
 email and letter templates etc. In Java we have MessageFormat class to do some simple templating. But in our case we need to fill these templates 
 from pre-populated java objects. Something similar to JasperReports will do with jrxml templates. &lt;br/&gt;I know we can write a utility to do this in java using Reflection. If I&#39;m using reflection, then I will end up in writing so many lines of code, which I really hate. 
 Groovy has this magical MOP which comes very handy. So I choose groovy to build this utility. 
 &lt;br/&gt;&lt;br/&gt;
 Here is the groovy code for the utility:
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:groovy&quot;&gt;
 @Log4j
 class Templatizer {
      
        def static final PATTERN = ~/[\$]{1}\{([^}]*)\}/
 
        def static String toString(final String template, def target) {
            def tempStr = template
            PATTERN.matcher(template).findAll {it -&gt;
                try {
                    tempStr = tempStr.replace(it[0], target.&quot;${it[1]}&quot;)
                } catch(MissingPropertyException e) { }
            }
            tempStr
        }

        def static String toString(String template, List target) {
            toString(template, target, &quot;\n&quot;)
        }
 
        def static String toString(String template, List target, String seperator) {
            def output = new StringBuilder()
            target.each { output.append(toString(template, it)).append(seperator) }
            output.toString()
        }
 }
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;
 Here is how we use it (Groovy Version):&lt;br/&gt;
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:groovy&quot;&gt;
 EmployedPerson p = new EmployedPerson([name: &quot;David Foo&quot;, dob: new Date(), salary: 90000.00])
 println Templatizer.toString(&quot;Templatizing Test: My Name is ${name}. I born in ${dob} and I am earning a salary of ${salary}&quot;, p)
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;
 Java Version:
 &lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;
 &lt;pre class=&quot;brush:java&quot;&gt;
 EmployedPerson p = new EmployedPerson(&quot;David Foo&quot;, new Date(), 90000.00);
 System.out.println(Templatizer.toString(&quot;Templatizing Test: My Name is ${name}. I born in ${dob} and I am earning a salary of ${salary}&quot;, p));
 &lt;/pre&gt;
 &lt;/div&gt;
 &lt;br/&gt;&lt;br/&gt;
 You can compile this class and you can use with in your java objects. You can use Ant to compile groovy code. 
 For more details on groovy-ant compilation, refer my &lt;a href=&quot;http://javarebel.blogspot.com/2012/02/another-java-database-mapping-utility.html&quot;&gt;previous blog&lt;/a&gt;&lt;br/&gt;&lt;br/&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.config.bloggerMode = true;
 SyntaxHighlighter.defaults[&#39;toolbar&#39;] = false;
    SyntaxHighlighter.all()
&lt;/script&gt; 
&lt;br/&gt;</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/2256645453469748223/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2012/04/templatize-java-objects.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/2256645453469748223'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/2256645453469748223'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2012/04/templatize-java-objects.html' title='Templatize Java Objects'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-4103268667311007393</id><published>2012-02-09T17:18:00.002-07:00</published><updated>2012-02-22T09:39:38.880-07:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="database"/><category scheme="http://www.blogger.com/atom/ns#" term="groovy"/><category scheme="http://www.blogger.com/atom/ns#" term="mapping"/><title type='text'>Another Java-Database Mapping Utility</title><content type='html'>Another Java-Database Mapping Utility&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In one of my previous blog I discussed about one &lt;a href=&quot;http://javarebel.blogspot.com/2010/09/java-resultset-mapping-utility.html&quot;&gt;ResultSet Mapping utility&lt;/a&gt;. After using that utility in couple of my projects, I came across some of the shotfalls of this utility. Like:&lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;There is no support for primitive data types. If you want to retrieve only one column from database also you need to create an Object.&lt;br /&gt;
&lt;/li&gt;
&lt;li&gt;Need to use sql classes like Connection, Statement and Resultset objects explicitly.&lt;br /&gt;
&lt;/li&gt;
&lt;/ul&gt;After looking into Groovy, I was amazed by its dynamic nature and Meta Programming model. Meta Programming model can be used as an alternative to remove lot of boiler plate java reflcetion code. So I decided to go with Groovy for my new Utility. There is another reason to choose groovy, once groovy classes are compiled it is compiled to java byte code. So you can use it in your java applications also.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;pre class=&quot;brush:groovy&quot;&gt;@Log4j
 class DBUtil&amp;lt;T&amp;gt; {
  
  def static final primitives = [Integer.class, String.class, Long.class, Double.class, Float.class]
  
  /**
   * Will execute given query and convert result to a collection of specified class.
   * 
   * @param dataSource - JNDI Name of the Datasource 
   * @param query - Select query
   * @param params - List of parameters in query
   * @param clazz - Return type
   * @return List of objects of clazz argument type
   */
  static def executeQuery(String dataSource, String query, List params, Class clazz) {
   log.debug &quot;Executing query ${query} with parameters ${params} using datasource ${dataSource}&quot;
   
   def objList = [], obj, colName = &quot;&quot;, field, sql
   try {
    sql = Sql.newInstance(lookup(dataSource))
    if(primitives.find {it == clazz}) {
     sql.eachRow(query, params) {row -&gt;
      colName = row.getMetaData().getColumnName(1)
      objList &lt;&lt; row.&quot;$colName&quot;
     }
    } else {
     def fieldMap = mapFieldNames(clazz)
     sql.eachRow(query, params) {row -&gt; 
      obj = clazz.metaClass.invokeConstructor()
      (0..row.getMetaData().columnCount-1).each {
       colName = row.getMetaData().getColumnName(it+1)
       field = fieldMap.find {it.key.compareToIgnoreCase(colName) == 0}
       if(field) obj.&quot;$field.value&quot; = row.&quot;$colName&quot;
      }
      objList &lt;&lt; obj
     }
    }
   } catch(Exception e) {
    log.error e.message, e
    throw new DAOException(e)
   } finally {
    sql?.close()
   }
   objList
  } 
  
  private static Map mapFieldNames(Class&amp;lt;?&amp;gt; clazz) {
   def flds = [], fld, fldMap = [:]
   def metaProps = clazz.metaClass.properties
   def fields = clazz.getDeclaredFields()
   metaProps.each {metaProp -&gt; 
    fld = fields.find {metaProp.name == it.name}
    if(fld) flds &lt;&lt; fld
   }
   flds.each{it-&gt; 
    def fldName = it.name
    if(fldName != &#39;metaClass&#39;) {
     if(it.isAnnotationPresent(Column.class)) {
      def colAnn = it.getAnnotation(Column.class)
      fldMap[colAnn.name()] = fldName
     } else fldMap[fldName] = fldName
    }
   }
   fldMap
  }
  
  /**
   * Will lookup for a datasource with given JNDI Name in the JNDI Context
   */
  private static def lookup = {jndiName -&gt;
   def ctx, ds
   try {
    log.debug &quot;Looking up for a datasource with JNDI name ${jndiName}&quot;
    ctx = new InitialContext()
    ds = ctx.lookup(jndiName)
   } finally {
    ctx?.close()
   }
   return ds
  }.memoize()
 }
 &lt;/pre&gt;&lt;/div&gt;Now let me go through the code. &lt;br /&gt;
&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;&lt;i&gt;mapFieldNames()&lt;/i&gt; method process the Class which we need to map. This method will find all fields in the Class which needs to be mapped and will find whether any name overriding is needed. I reusing the same Column annotation declared in my old &lt;a href=&quot;http://javarebel.blogspot.com/2010/09/java-resultset-mapping-utility.html&quot;&gt;ResultSet Mapper blog&lt;/a&gt; to resolve the colum and variable name difference.&lt;/li&gt;
&lt;li&gt;&lt;i&gt;executeQuery()&lt;/i&gt; method will lookup the datasource and execute the given query. After that it will try to map field names returned by mapFieldNames() with resultset. &lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
Please refer to &lt;a href=&quot;http://groovy.codehaus.org/api/groovy/sql/Sql.html&quot;&gt;Groovy SQL documentation &lt;/a&gt; to use it in a stand alone environment where a datasource is not available.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Usage:&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
In Java:&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;pre class=&quot;brush:java&quot;&gt;DBUtil.executeQuery(&quot;jdbc/MyDBJNDI&quot;, 
         &quot;select empno, lname, fname, birth, deptno from employees where upper(lname) like ?&quot;, 
         Arrays.asList(new String[]{&quot;AND&quot;}), Employee.class);
 &lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
In Groovy:&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;pre class=&quot;brush:groovy&quot;&gt;DBUtil.executeQuery(&quot;jdbc/MyDBJNDI&quot;, 
         &quot;select empno, lname, fname, birth, deptno from employees where upper(lname) like ?&quot;, 
         [&#39;AND&#39;], Employee.class);
 &lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Suppose if your query returns only one String, then you could use this utility as&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;pre class=&quot;brush:groovy&quot;&gt;def emps = DBUtil.executeQuery(&quot;jdbc/MyDBJNDI&quot;, 
         &quot;select lname from employees where empno = ?&quot;, 
         [120L], String.class);
 println &quot;Last Name of Employee with empno 120 is ${emps[0]}&quot;
 &lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Suppose if your query returns multiple String values, then you could use this utility as&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;pre class=&quot;brush:groovy&quot;&gt;def emps = DBUtil.executeQuery(&quot;jdbc/MyDBJNDI&quot;, 
         &quot;select lname from employees where deptno = ?&quot;, 
         [100], String.class);
 println &quot;Employees working in department 100 are ${emps}&quot;
 &lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;i&gt;&lt;font color=&quot;red&quot; style=&quot;font-weight:bold&quot;&gt;&lt;br /&gt;
Since executeQuery() return type is Object you need an explicit cast to java.util.List when using from Java. To avoid this you can add one more function in DBUtil as below&lt;/font&gt;&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid green; padding-left: 10px;&quot;&gt;&lt;pre class=&quot;brush:groovy&quot;&gt;static def &amp;lt;T&amp;gt; List&amp;lt;T&amp;gt; toList(String dataSource, String query, List&amp;lt;?&amp;gt; params, Class clazz) {
  log.debug &quot;Executing query ${query} with parameters ${params} using datasource ${dataSource}&quot;
  executeQuery(dataSource, query, params, clazz)
 }
 &lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Now it is really easy to use this Utility from Java also.&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;pre class=&quot;brush:java&quot;&gt;List&amp;lt;Employee&amp;gt; emps = DBUtil.toList(&quot;jdbc/MyDBJNDI&quot;, 
         &quot;select empno, lname, fname, birth, deptno from employees where upper(lname) like ?&quot;, 
         Arrays.asList(new String[]{&quot;AND&quot;}), Employee.class);
 
 List&amp;lt;String&amp;gt; empLNames = DBUtil.toList(&quot;jdbc/MyDBJNDI&quot;, 
         &quot;select lname from employees where empno = ?&quot;, 
         Arrays.asList(new Long[]{120L}), String.class);
 System.out.println(String.format(&quot;Last Name of Employee with empno 120 is %s&quot;, empLNames.get(0)));
 &lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
To compile this groovy class,  First you need to download &lt;a href=&quot;http://groovy.codehaus.org/Download?nc&quot;&gt;Groovy&lt;/a&gt;. Then you can use either &lt;a href=&quot;http://groovy.codehaus.org/Eclipse+Plugin&quot;&gt;groovy eclipse plugin&lt;/a&gt; or ANT to build it. If you are using ANT, here is the snippet which you need to add to your build.xml for compiling groovy scripts.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;pre class=&quot;brush: xml&quot;&gt;&lt;!-- Compiling groovy scripts --&gt;
 &lt;property name=&quot;GROOVY_HOME&quot; value=&quot;E:/groovy-1.8.4&quot;&gt;&lt;/property&gt;
 &lt;path id=&quot;groovy.classpath&quot;&gt;
  &lt;fileset dir=&quot;${GROOVY_HOME}/embeddable&quot; /&gt;
 &lt;/path&gt;
 &lt;taskdef name=&quot;groovyc&quot; classname=&quot;org.codehaus.groovy.ant.Groovyc&quot; classpathref=&quot;groovy.classpath&quot; /&gt;
 &lt;target name=&quot;groovy_build&quot; description=&quot;Compile groovy scripts&quot;&gt;
  &lt;groovyc srcdir=&quot;${src}/groovy&quot; destdir=&quot;${build}/classes&quot;&gt;
   &lt;classpath refid=&quot;groovy.classpath&quot;/&gt;
  &lt;/groovyc&gt;
 &lt;/target&gt;
 &lt;/pre&gt;&lt;/div&gt;&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.config.bloggerMode = true;
 SyntaxHighlighter.defaults[&#39;toolbar&#39;] = false;
    SyntaxHighlighter.all()
&lt;/script&gt;</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/4103268667311007393/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2012/02/another-java-database-mapping-utility.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/4103268667311007393'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/4103268667311007393'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2012/02/another-java-database-mapping-utility.html' title='Another Java-Database Mapping Utility'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><thr:total>0</thr:total><georss:featurename>Salt Lake City, UT, USA</georss:featurename><georss:point>40.7607793 -111.89104739999999</georss:point><georss:box>40.6844173 -112.07207439999999 40.837141300000006 -111.71002039999999</georss:box></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-5982597227902005605</id><published>2011-09-21T17:54:00.000-06:00</published><updated>2011-09-27T14:21:13.506-06:00</updated><category scheme="http://www.blogger.com/atom/ns#" term="Chart"/><category scheme="http://www.blogger.com/atom/ns#" term="JFreeChart"/><category scheme="http://www.blogger.com/atom/ns#" term="JSF"/><title type='text'>Simple JSF Chart Component</title><content type='html'>&lt;a href=&quot;http://www.web2pdfconvert.com/convert&quot;&gt;Save to PDF&lt;/a&gt;&lt;br/&gt;&lt;br /&gt;
My last project was a conversion project, standalone Swing application to JSF application. Swing renders lot of charts and graphs. To render charts in JSF pages, we need to use some third party components like PrimeFaces. But in our case if we  use primefaces, then we need to reiterate the charting usecase from the scratch. Existing swing application used JFreeCharts API to generate charts. I googled a lot to find any JFreeChart based JSF component. But I couldn&#39;t find one. Then I decided to create one. &lt;br /&gt;
&lt;br /&gt;
My first and main priority in mind was to develop a JSF component to which I can wrap a JFreeChart. So that I can reuse the same charts which is generated by the swing application in my JSF pages. &lt;br /&gt;
&lt;br /&gt;
Finally I got it working as I desired. So I thought of sharing with you friends.&lt;br /&gt;
&lt;br /&gt;
If you are familiar with JFreeChart API, there is a method called createBufferedImage in JFreeChart class which is the vital method used in this component.&lt;br /&gt;
&lt;br /&gt;
Let me explain how I approached the problem:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;Generate Charts using JFreeChart API&lt;/li&gt;
&lt;li&gt;Create a BufferedImage from the generated chart&lt;/li&gt;
&lt;li&gt;Use javax.imageio.ImageIO class to write this BufferedIamge to ServletOutputStream&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
First I created a custom JSF custom component called ChatComponent which will collect data needed to generate the chart.&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;&lt;![CDATA[
//ChartComponent.java
 @FacesComponent(&quot;com.mine.ChartComponent&quot;)
 public class ChartComponent extends UIComponentBase {
 
  private static final Logger logger = Logger.getLogger(ChartComponent.class.getName());

  private static final String CHART_TYPE_ATTR = &quot;chartType&quot;;
  
  private static final String FAMILY = &quot;com.mine.jsf.HtmlFamily&quot;;

  @Override
  public String getFamily() {
   return FAMILY;
  }

  @Override
  public void encodeEnd(FacesContext context) throws IOException {
   Object chartTypeObj = &quot;area&quot;;
   ValueExpression chartTypeExp = this.getValueExpression(CHART_TYPE_ATTR);
   if(chartTypeExp != null) {
    chartTypeObj = chartTypeExp.getValue(context.getELContext());
   } else 
    chartTypeObj = this.getAttributes().get(CHART_TYPE_ATTR);
   logger.info(&quot;Chart type received is &quot; + chartTypeObj);
   
   ChartProcessor processor = 
    ChartProcessorFactory.getProcessor(String.valueOf(chartTypeObj));
   processor.process(this, context);
  }
 }
 ]]&gt;&lt;/script&gt;&lt;br /&gt;
&lt;/div&gt;In the above code ChartProcessorFactory is a Factory class to generate different processors whcih can process different type of Charts like Area, Bar, Line etc. I need to develop this a reusable and extensible component. That is why lot of Fatory and generic abstraction layers.&lt;br /&gt;
&lt;br /&gt;
Here is my ChartProcessor interface:&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;&lt;![CDATA[
//ChartProcessor.java
 public interface ChartProcessor {
 
  String LABEL_ATTR = &quot;label&quot;;
  String VALUE_ATR = &quot;value&quot;;
  String LEGEND_LABEL_ATTR = &quot;legendLabel&quot;;
  String WIDTH_ATTR = &quot;width&quot;;
  String HEIGHT_ATTR = &quot;height&quot;;
  String SERIES_COLOR_ATTR = &quot;seriesColor&quot;;
  String LEGEND_VISIBLE_ATTR = &quot;legendVisible&quot;;
  
  String KEY_TEMPLATE = &quot;com.mine.charts.%s.dataKey&quot;;
  String CHART_URL_TEMPLATE = &quot;%s/faces/com.mine.Chart?data_KEY=%s&quot;;
  
  public void process(UIComponentBase component, FacesContext context) throws IOException;
 }
 ]]&gt;&lt;/script&gt;&lt;br /&gt;
&lt;/div&gt;In this blog I will explain how I generated an Area Chart. Now will create a concrete CharProcessor called AreaChartProcessor.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;&lt;![CDATA[
//AreaChartProcessor.java
 public class AreaChartProcessor implements ChartProcessor {
 
  private static final Logger logger = Logger.getLogger(AreaChartProcessor.class.getName());

  @Override
  public void process(UIComponentBase component, FacesContext context) throws IOException {
   ResponseWriter writer = context.getResponseWriter();
   ExternalContext eCtx = context.getExternalContext();
   
   final String compId = component.getClientId();
   String dataKey = String.format(KEY_TEMPLATE, compId);
   HttpSession session = (HttpSession) eCtx.getSession(true);
   
   Object xData = FacesUtil.getComponentAttribute(component, LABEL_ATTR);
   Comparable&lt;?&gt;[] xDataArray = (Comparable&lt;?&gt;[]) xData;
   
   Object valueSet = FacesUtil.getComponentAttribute(component, VALUE_ATR);
   Double[] yDataArray = (Double[]) valueSet;
   
   Object label = FacesUtil.getComponentAttribute(component, LEGEND_LABEL_ATTR);
   
   ChartData data = new AreaChartData(xDataArray, yDataArray, String.valueOf(label));
   
   ValueExpression sClrExp = component.getValueExpression(SERIES_COLOR_ATTR);
   if(sClrExp != null) {
    Object color = sClrExp.getValue(context.getELContext());
    Color sColor = (Color) color;
    data.setSeriesColor(sColor);
   }
   
   Object isLegendVisible = FacesUtil.getComponentAttribute(component, LEGEND_VISIBLE_ATTR);
   if(isLegendVisible != null)
    data.setLegendVisible(Boolean.valueOf(String.valueOf(isLegendVisible)));
   
   Object width = FacesUtil.getComponentAttribute(component, WIDTH_ATTR);
   if(width != null) 
    data.setWidth(String.valueOf(width));
   
   Object height = FacesUtil.getComponentAttribute(component, HEIGHT_ATTR);
   if(height != null) 
    data.setHeight(String.valueOf(height));
   session.setAttribute(dataKey, data);
   
   String contextName = ((ServletContext)eCtx.getContext()).getContextPath();
   logger.info(&quot;Application context is &quot; + contextName);
   
   writer.startElement(&quot;img&quot;, null);
   String chartURL = String.format(CHART_URL_TEMPLATE,  contextName, dataKey);
   logger.info(&quot;Chart URL &quot; + chartURL);
   writer.writeAttribute(&quot;src&quot;, chartURL, null);
   writer.endElement(&quot;img&quot;);
  }
 }
 ]]&gt;&lt;/script&gt;&lt;br /&gt;
&lt;/div&gt;AreaChartProcessor class will collect all the data required to generate an area chart from JSF page using a custom tag.&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: xml&quot;&gt;&lt;![CDATA[
 &lt;n:chart 
            xmlns:n=&quot;http://www.naveen.com/jsf/chart&quot;
            value=&quot;#{chartBean.valueSet}&quot; 
            label=&quot;#{chartBean.labelSeries}&quot; 
            legendLabel=&quot;#{chartBean.seriesKeyLabel}&quot;
            chartType=&quot;area&quot;
            width=&quot;600&quot; height=&quot;350&quot;/&gt;
 ]]&gt;&lt;/script&gt;&lt;br /&gt;
&lt;/div&gt;Once AreaChartProcessor collects all the data, it will generate an appropriate ChartData object (line #24 of AreaCharProcessor) and store it in session. Key for storing this session is generated using component&#39;s id attribute. This is for rendering multiple charts on same page.&lt;br /&gt;
&lt;br /&gt;
That is all we are doing in the encodeEnd method of UIComponent. But we have not generated chart yet. We need some process to generate chart from this data before the page is rendered. Here come JSF PhaseListeners handy. I created a PhaseListener to hook BEFORE RESTORE_VIEW event. &lt;br /&gt;
&lt;br /&gt;
Not done yet! Now somebody have to fire a faces request to kick in the PhaseListener. This is done by generating an image component with source pointing to FacesServlet.&lt;br /&gt;
&lt;br /&gt;
Our PhaseListener will retrieve all the ChartData stored in session and will generate charts. To retrieve ChartData, listener needs the key used to store ChartData into session. So I stuffed these keys as URL parameters to the above discussed image (line #45 of AreaChartProcessor).&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;&lt;![CDATA[
//ChartComponentListener.java
 public class ChartComponentListener implements PhaseListener {

  private static final long serialVersionUID = -7161035876792824129L;
  
  private static Logger logger = Logger.getLogger(ChartComponentListener.class.getName());

  @Override
  public void afterPhase(PhaseEvent arg0) {
  }

  @Override
  public void beforePhase(PhaseEvent arg0) {
   FacesContext context = arg0.getFacesContext();
   ExternalContext eCtx = context.getExternalContext();
   
   HttpServletRequest req = (HttpServletRequest) eCtx.getRequest();
   String data_KEY = req.getParameter(&quot;data_KEY&quot;);
   logger.info(&quot;Chart Data Key is &quot; + data_KEY);

   HttpSession session = req.getSession();
   Object chartData = session.getAttribute(data_KEY);
   
   if (chartData != null) {
    
    ChartData data = ChartData.class.cast(chartData);
    logger.info(&quot;Chart Type received is &quot; + data.getType());
    IChartGenerator chartGen = ChartGeneratorFactory.getChartGenerator(data.getType());
    logger.info(&quot;ChartGenerator in use -&gt; &quot; + chartGen.getClass().getName());
    JFreeChart chart = chartGen.generateChart(data);
    
    BufferedImage img = chart.createBufferedImage(
          Integer.valueOf(data.getWidth()), 
          Integer.valueOf(data.getHeight()));
    try {
     HttpServletResponse response = (HttpServletResponse) eCtx.getResponse();
     response.setContentType(&quot;image/png&quot;);
     response.setHeader(&quot;Cache-Control&quot;, &quot;no-store&quot;);
     response.setHeader(&quot;Pragma&quot;, &quot;no-cache&quot;);
     response.setDateHeader(&quot;Expires&quot;, 0L);
     
     ServletOutputStream output = response.getOutputStream();
     ImageIO.write(img, &quot;png&quot;, output);
     
     session.removeAttribute(data_KEY);
    
     context.responseComplete();
    } catch (Exception e) {
     logger.log(Level.SEVERE, e.getMessage(), e);
     throw new IllegalStateException(e);
    }
   }
  }

  @Override
  public PhaseId getPhaseId() {
   return PhaseId.RESTORE_VIEW;
  }
 }
 ]]&gt;&lt;/script&gt;&lt;br /&gt;
&lt;/div&gt;Once ChartData is retrieved from session, phaselistener will create an appropriate ChartGenerator from ChartGeneratorFactory. ChartGenerator will generate chart from ChartData. From this chart a BufferedImage is created and which will be written to ServletOutputStream.&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;&lt;![CDATA[
//ChartGenerator.java
 public abstract class ChartGenerator implements IChartGenerator {
 
  protected void configureChart(JFreeChart chart, ChartData data) {
   chart.setBackgroundPaint(Color.WHITE);

   final CategoryPlot plot = (CategoryPlot) chart.getPlot();
   configurePlot(plot, new PlotConfig());

   final CategoryItemRenderer renderer = plot.getRenderer();
   configureBaseItemLabel(renderer, new BaseItemLabelConfig() {
    public Paint getPaint() {
     return Color.BLACK;
    }
   });
   renderer.setBaseSeriesVisibleInLegend(data.isLegendVisible());
   renderer.setSeriesPaint(0, data.getSeriesColor());

   configureAxis(plot.getDomainAxis(), new AxisConfig());

   final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
   rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
  }
  
  protected void configureBaseItemLabel(CategoryItemRenderer renderer, 
             BaseItemLabelConfig config) {
   renderer.setBaseItemLabelGenerator(config.getGenerator());
   renderer.setBaseItemLabelsVisible(config.isVisible());
   renderer.setBaseItemLabelPaint(config.getPaint());
   renderer.setBaseItemLabelFont(config.getFont());
  }
  
  protected void configureAxis(CategoryAxis axis, AxisConfig config) {
   axis.setCategoryLabelPositions(config.getLabelPosition());
   axis.setLabelFont(config.getLabelFont());
   axis.setTickLabelFont(config.getTickLabelFont());
   axis.setLowerMargin(config.getLowerMargin());
   axis.setUpperMargin(config.getUpperMargin());
   axis.setCategoryMargin(config.getCategoryMargin());
  }
  
  protected void configurePlot(CategoryPlot plot, PlotConfig config) {
   plot.setForegroundAlpha(config.getForegroundAlpha());
   plot.setBackgroundPaint(config.getBackgroundPaint());
   plot.setDomainGridlinePaint(config.getDomainGridlinePaint());
   plot.setDomainGridlinesVisible(config.isDomainGridlinesVisible());
   plot.setRangeGridlinePaint(config.getRangeGridlinePaint());
   ValueAxis axis = plot.getRangeAxis();
   axis.setRange(0, axis.getUpperBound() + 1.0D);
  }

  @Override
  public abstract JFreeChart generateChart(ChartData data);
 }

 class ChartLabelGenerator implements CategoryItemLabelGenerator {

  private static final NumberFormat numFrmt = new DecimalFormat(&quot;###0.00&quot;);
  
  @Override
  public String generateColumnLabel(CategoryDataset arg0, int arg1) {
   return null;
  }

  @Override
  public String generateLabel(CategoryDataset arg0, int arg1, int arg2) {
   Number val = arg0.getValue(arg1, arg2);
   return (val != null &amp;&amp; val.doubleValue() != 0.0D) ? numFrmt.format(val) : &quot;&quot;;
  }

  @Override
  public String generateRowLabel(CategoryDataset arg0, int arg1) {
   return null;
  }
 }
 ]]&gt;&lt;/script&gt;&lt;br /&gt;
&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script type=&quot;syntaxhighlighter&quot; class=&quot;brush: java&quot;&gt;&lt;![CDATA[
//AreaChartGenerator.java
 public class AreaChartGenerator extends ChartGenerator {

  @Override
  public JFreeChart generateChart(ChartData data) {
   if(data instanceof AreaChartData) {
    CategoryDataset dataset = data.createDataset();
    final JFreeChart chart = ChartFactory.createAreaChart(
            &quot;Area Chart&quot;, &quot;Months&quot;, &quot;Value&quot;,
            dataset, PlotOrientation.VERTICAL,
            true, true, false);
    super.configureChart(chart, data);
    return chart;
   } else
    throw new IllegalArgumentException();
  }

 }
 ]]&gt;&lt;/script&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUSL2BdFr7CiTKc1nj4Xvz10RimTO-1BUgLN3MiQX65bZY6_VWEbCVIgGTySMQqxfq_fY-gP_657PHryzQaPXYGCmUFdZfbvGTqP8wX6hyg4wIdrhkK3HWCvx711w2qOMOlqY-5hn1UbY/s1600/Charts.jpg&quot; imageanchor=&quot;1&quot; style=&quot;&quot;&gt;&lt;img border=&quot;0&quot; height=&quot;175&quot; width=&quot;320&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUSL2BdFr7CiTKc1nj4Xvz10RimTO-1BUgLN3MiQX65bZY6_VWEbCVIgGTySMQqxfq_fY-gP_657PHryzQaPXYGCmUFdZfbvGTqP8wX6hyg4wIdrhkK3HWCvx711w2qOMOlqY-5hn1UbY/s320/Charts.jpg&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;br /&gt;
For source code and library, visit: &lt;a href=&quot;http://code.google.com/p/jsf-jfreechart/&quot;&gt;Google Project Hosting&lt;/a&gt;&lt;br /&gt;
&lt;/body&gt;&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.config.bloggerMode = false;
 SyntaxHighlighter.defaults[&#39;toolbar&#39;] = false;
    SyntaxHighlighter.all()
&lt;/script&gt;</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/5982597227902005605/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2011/09/simple-jsf-chart-component.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/5982597227902005605'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/5982597227902005605'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2011/09/simple-jsf-chart-component.html' title='Simple JSF Chart Component'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiUSL2BdFr7CiTKc1nj4Xvz10RimTO-1BUgLN3MiQX65bZY6_VWEbCVIgGTySMQqxfq_fY-gP_657PHryzQaPXYGCmUFdZfbvGTqP8wX6hyg4wIdrhkK3HWCvx711w2qOMOlqY-5hn1UbY/s72-c/Charts.jpg" height="72" width="72"/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-2480786295736635210</id><published>2011-09-17T23:30:00.000-06:00</published><updated>2011-09-17T23:52:54.125-06:00</updated><title type='text'>Database Operation Time Logging</title><content type='html'>&lt;br&gt;&lt;br&gt;Everyday in software world we use code for accessing data from database or will use some other libraries for accessing data from database.&lt;br /&gt;
&lt;br /&gt;
During development phase it is very rare to have performance issues mainly because of less volume of data. But when you move your code to production environment you can have performance hits. Consider a scenario, it looks like all database access is slow.&lt;br /&gt;
&lt;br /&gt;
To analyse this situation you want to enable time logging. Like log connection obtaining time and query execution times.&lt;br /&gt;
&lt;br /&gt;
Suppose you haven&#39;t added those log statements while writing code; then it is a going to be tedious job to add those log statements in all your data access objects. Especially if you are working on a big project with more than 100 DAO classes.&lt;br /&gt;
&lt;br /&gt;
If you are using some other external library for data access, and if you don&#39;t have source code for that library; then adding log statements is not possible. In this kind of scenario we need to use some kind of profiling tools. But running profiling tools on production environment is not that easy.&lt;br /&gt;
&lt;br /&gt;
I faced a similar situation in one of my projects. I found AOP programming very useful in this kind of scenario. In this blog I going to explain how I used AOP to solve this problem. I selected AspectJ as the AOP implementation. If you are new to Aspectj, please refer &lt;a href=&quot;http://www.eclipse.org/aspectj/doc/released/progguide/index.html&quot;&gt;AspectJ documention&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
I created an Aspect with two Around pointcuts. &lt;br /&gt;
&lt;ul&gt;&lt;li&gt;One pointcut to log connection time.&lt;/li&gt;
&lt;li&gt;One to log query execution time.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script class=&quot;brush: java&quot; type=&quot;syntaxhighlighter&quot;&gt;
&lt;![CDATA[
// Aspect Code

@Aspect
public class DatabaseTimingAspect {
 
 @Pointcut
 public void logQueryTime() {}
 
 @Around(&quot;logQueryTime() &amp;&amp; execution(public * java.sql.Statement+.executeQuery(..))&quot;)
 public Object executeQuery(ProceedingJoinPoint pjp) throws Throwable {
  long startTime = System.currentTimeMillis();
  Object[] args = pjp.getArgs();
  String qry = (args != null &amp;&amp; args.length &gt; 0) ? String.valueOf(args[0]) : &quot;&quot;;
  if(!&quot;&quot;.equals(qry)) 
   System.out.println(String.format(&quot;Query executing is %s&quot;, qry));
  Object resultSet = pjp.proceed();
  long endTime = System.currentTimeMillis();
  System.out.println(String.format(&quot;Time taken to execute query is : %d&quot;, (endTime - startTime)));
  return resultSet;
 }
 
 @Pointcut(&quot;execution(public * javax.sql.DataSource.getConnection())&quot;)
 public void logConnectionTiming() {}
 
 @Around(&quot;logConnectionTiming()&quot;)
 public Object getConnetion(ProceedingJoinPoint pjp) throws Throwable {
  long startTime = System.currentTimeMillis();
  Object con = pjp.proceed();
  long endTime = System.currentTimeMillis();
  System.out.println(String.format(&quot;Time taken to obtain connection : %d&quot;, (endTime - startTime)));
  return con;
 }
}

]]&gt;
&lt;/script&gt;&lt;/div&gt;&lt;br /&gt;
After developing aspect we need to instruct AspectJ to weave this aspect to our DAO classes. Weaving process can be done either at compile time or at load time. In this blog I will explain about Load Time Weaving. &lt;i&gt;If you don&#39;t have DAO class source code available then Load Time Weaving is the only option for you&lt;/i&gt;. To do this, basically what we need is an XML file named aop.xml. We need to put this file inside META-INF folder of your jar file.&lt;br /&gt;
&lt;br /&gt;
Here is a sample aop.xml file.&lt;br /&gt;
&lt;div class=&quot;myCode&quot; style=&quot;border: 2px solid; padding-left: 10px;&quot;&gt;&lt;script class=&quot;brush: xml&quot; type=&quot;syntaxhighlighter&quot;&gt;
&lt;![CDATA[
&lt;aspectj&gt;
 &lt;aspects&gt;
  &lt;concrete-aspect
   name=&quot;com.mine.reasearch.aspects.DatabaseTimingAspect$&quot; 
   extends=&quot;com.mine.reasearch.aspects.DatabaseTimingAspect&quot;&gt;
   &lt;pointcut name=&quot;logConnectionTiming&quot; expression=&quot;within(com.mine.project.dao.*)&quot; /&gt;
   &lt;pointcut name=&quot;logQueryTime&quot; expression=&quot;within(com.mine.project.dao.*)&quot; /&gt;
  &lt;/concrete-aspect&gt;
 &lt;/aspects&gt;
&lt;/aspectj&gt;
]]&gt;
&lt;/script&gt;&lt;/div&gt;&lt;br /&gt;
After that I configured my server(Websphere) to use Load Time Weaving feature of AspectJ to weave DatabaseTiming aspect to my DAO classes. Please refer to my &lt;a href=&quot;http://javarebel.blogspot.com/2010/09/using-aspectj-with-rad.html&quot;&gt;previous blog&lt;/a&gt; for websphere configuration details.&lt;br /&gt;
&lt;br /&gt;
After making above configuration changes, restart your server. Now you should be able to see those log statements (One for obtaining connection and one for executing query). See how we added those log statements to our DAO classes without touching the DAO class.&lt;br /&gt;
&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 SyntaxHighlighter.config.bloggerMode = false;
 SyntaxHighlighter.defaults[&#39;toolbar&#39;] = false;
    SyntaxHighlighter.all()
&lt;/script&gt;</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/2480786295736635210/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2011/09/database-operation-timeing-logging.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/2480786295736635210'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/2480786295736635210'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2011/09/database-operation-timeing-logging.html' title='Database Operation Time Logging'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-5925314363472813356</id><published>2010-09-18T11:07:00.000-06:00</published><updated>2010-09-18T11:07:46.928-06:00</updated><title type='text'>Java ResultSet Mapping Utility</title><content type='html'>&lt;style&gt;
.codeClass {
background-color:blue;
color:white;
width:98%;
font-size:13px;
}
&lt;/style&gt;&lt;br /&gt;
Most of the time when we are not using any ORM tool like JPA or Hibernate or Toplink for database access; we will be writing lot of code for iterating through ResultSet and populating our DTO objects. Here I am going to introduce a utility for doing this.&lt;br /&gt;
&lt;br /&gt;
Most of the our DAO classes will return either an Object or a Collection of Objects. So in my mapping utility I am going to give two methods - toObject and toList.&lt;br /&gt;
&lt;br /&gt;
This utility doesn&#39;t do any object mapping to database mapping. We can use this only for creating application specific DTO from our ResultSet.&lt;br /&gt;
&lt;br /&gt;
Now look how a typical DAO class look like:&lt;br /&gt;
&lt;div class=&#39;codeClass &#39;&gt;&lt;pre&gt;public class EmployeeDetailsDAO {
 public EmployeeDetailsVO getEmployeeDetails(Long employeeId) {
  EmployeeDetailsVO emp = null;
  PreparedStatement stat = null;
  Connection con = null;
  ResultSet rs = null;
  try {
   con = datasource.getConnection();
   stat = con.prepareStatement(&quot;Query to Fetch Employee Details&quot;);
   stat.setLong(1, Long.valueOf(employeeId));
   rs = stat.executeQuery();

   if(rs.next()) {
    emp = new EmployeeDetailsVO();
    // Code to populate EmployeeDetailsVO from ResultSet
    ......
    .....
   }
  } catch (SQLException e) {
   throw new DAOException(e);
  } finally {
   closeAll(rs, stat, con);
  }
  
  return emp;
 }
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Here suppose if you are fetching like 25 columns, then you will have to write atleast 25 lines of code like &lt;pre&gt;YourDTO.setField(ResultSet.getField())&lt;/pre&gt;which is quiet annoying. &lt;br /&gt;
&lt;br /&gt;
The Basic idea of my utility is very simple:&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;First get all the fields in your DTO class using java Refletction.&lt;/li&gt;
&lt;li&gt;Iterate through each field.&lt;/li&gt;
&lt;li&gt;Get the name and Type of the Field.&lt;/li&gt;
&lt;li&gt;Using the name and type of the field call ResultSet.get&amp;lt;DTO FieldType&amp;gt;.&lt;/li&gt;
&lt;li&gt;Set the value to the corresponsing DTO class object&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
But there are some problems with this approach. &lt;br /&gt;
&lt;ul&gt;&lt;li&gt;It is not always a good idea to name your DTO instance variables same as database column names.&lt;/li&gt; 
&lt;li&gt;Not always database column types match your DTO types.&lt;/li&gt;
&lt;li&gt;Not required that all your DTO instance variable have to be mapped to ResultSet&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
First problem can be solved by using alias names in the query. But I feel like it is not a good idea. If I am the only one who is going to this utility I can live with alias names. But solution to all these problems are there in all the ORM tools. Use Custom Annotation!&lt;br /&gt;
&lt;br /&gt;
For name and type problem I am going to create a custom annotation &lt;b&gt;Column&lt;/b&gt;.&lt;br /&gt;
&lt;div class=&#39;codeClass&#39;&gt;&lt;pre&gt;@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Column {
 String name() default &quot;&quot;;
 Class&lt;? extends Object&gt; type() default Object.class;
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
and for not mapping instance variable with ResultSet I decided to go with the same &lt;b&gt;Transient&lt;/b&gt; annotation available as part of JPA.&lt;br /&gt;
&lt;br /&gt;
Take a loot at a typical DTO object.&lt;br /&gt;
&lt;div class=&#39;codeClass&#39;&gt;&lt;pre&gt;public class EmployeeDetailsVO implements Serializable {

 private static final long serialVersionUID = 4865243695898605677L;

 @Column(name=&quot;emp_id)
 private Long empno;

 @column(name=&quot;dept_id&quot;,type=String.class)
 private String deptno;
 
 private String fname,lname,address1,city,
  state,zip,busphone,busext,title,internetadd,deptName;
  
 @Transient
 private String formattedEmpId;

 .......................
 Geters and Setter will go here
 .....................
}
&lt;/pre&gt;&lt;/div&gt;In the above example you can see empno and deptno field is annotated with &lt;b&gt;Column&lt;/b&gt;. empno is annotated because of the name change and deptno is annotated to handle name as well as type difference. You can see formattedEmpId filed is annotated with &lt;b&gt;Transient&lt;/b&gt;, so Mapper will ignore this field when doing the mapping.&lt;br /&gt;
&lt;br /&gt;
Now the real ResultSetMapper class:&lt;br /&gt;
&lt;div class=&#39;codeClass&#39;&gt;&lt;pre&gt;public class ResultsetMapper&amp;lt;T&amp;gt; {
 
 @SuppressWarnings(&quot;unchecked&quot;)
 private static ResultsetMapper thisInstance;
 
 @SuppressWarnings(&quot;unchecked&quot;)
 public static &amp;lt;T&amp;gt; ResultsetMapper&amp;lt;T&amp;gt; getInstance() {
  if(thisInstance == null) {
   synchronized (ResultsetMapper.class) {
    if(thisInstance == null)
     thisInstance = new ResultsetMapper&amp;lt;T&amp;gt;();
   }
  }
  return thisInstance;
 }
 
 private ResultsetMapper() { }

 public T toObject(ResultSet rs, Class&amp;lt;T&amp;gt; toClazz) {
  T obj = null;
  Field[] fields = toClazz.getDeclaredFields();
  try {
   if(rs.next() &amp;&amp; fields != null &amp;&amp; fields.length &gt; 0) {
    obj = toClazz.newInstance();
    populateFields(rs, obj, fields);
   }
  } catch (Exception e) {
   e.printStackTrace();
   throw new CustomException(e);
  }
  
  return obj;
 }
 
 public List&amp;lt;T&amp;gt; toList(ResultSet rs, Class&amp;lt;T&amp;gt; toClazz) {
  List&amp;lt;T&amp;gt; listObj = Lists.newLinkedList();
  T obj = null; 
  Field[] fields = toClazz.getDeclaredFields();
  if(fields == null || fields.length == 0) return listObj;
  try {
   while(rs.next()) {
    obj = toClazz.newInstance();
    populateFields(rs, obj, fields);
    listObj.add(obj);
   }
  } catch (Exception e) {
   e.printStackTrace();
   throw new CustomException(e);
  }
  
  return listObj;
 }
 

 private void populateFields(ResultSet rs, T obj, Field[] fields)
   throws IllegalAccessException, SQLException {
  String fieldName = null;
  for(Field f : fields) {
   if(&quot;serialVersionUID&quot;.equals(f.getName())) continue;
   f.setAccessible(true);
   fieldName = f.getName();
   Class&lt;? extends Object&gt; fieldType = f.getType();
   Annotation[] annotations = f.getDeclaredAnnotations();
   if(annotations != null &amp;&amp; annotations.length &gt; 0) {
    if(annotations[0].annotationType() == Column.class) {
     Column colAnn = (Column) annotations[0];
     fieldName = colAnn.name();
     if(colAnn.type() != Object.class)
      fieldType = colAnn.type();
    } else if(annotations[0].annotationType() == Transient.class) continue;
   }
   if(fieldType == Long.class) 
    f.set(obj, rs.getLong(fieldName));
   
   if(fieldType == String.class) 
    f.set(obj, rs.getString(fieldName));
   
   if(fieldType == Integer.class) 
    f.set(obj, rs.getInt(fieldName));
   
   if(fieldType == Double.class) 
    f.set(obj, rs.getDouble(fieldName));
   
   if(fieldType == Date.class) {
    java.sql.Date sqlDate = rs.getDate(fieldName);
    f.set(obj, new Date(sqlDate.getTime()));
   }
   if(fieldType == BigDecimal.class) 
    f.set(obj, rs.getBigDecimal(fieldName));
   
   if(fieldType == Boolean.class) 
    f.set(obj, rs.getBoolean(fieldName));
   
   if(fieldType == Float.class) 
    f.set(obj, rs.getFloat(fieldName));
   
   if(fieldType == Short.class) 
    f.set(obj, rs.getShort(fieldName));
   
   if(fieldType == Timestamp.class) 
    f.set(obj, rs.getTimestamp(fieldName));
  }
 }
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
There are certain limitations for this utility. &lt;br /&gt;
&lt;ul&gt;&lt;li&gt;You cannot use primitive types for your DTO fields. Always use wrapper classes. Java5 AutoBoxing feature will minimize this effort.&lt;/li&gt;
&lt;li&gt;Wil support only certain types - Integer, Float, Long, String, BigDecimal, Boolean, Shot, TimeStamp and Date.&lt;/li&gt;
&lt;/ul&gt;&lt;br /&gt;
Now will look at our old EmployeeDetailsDAO.&lt;br /&gt;
&lt;div class=&#39;codeClass&#39;&gt;&lt;pre&gt;public class EmployeeDetailsDAO {
 public EmployeeDetailsVO getEmployeeDetails(Long employeeId) {
  EmployeeDetailsVO emp = null;
  PreparedStatement stat = null;
  Connection con = null;
  ResultSet rs = null;
  try {
   con = datasource.getConnection();
   stat = con.prepareStatement(&quot;Query to fetch employee details&quot;);
   stat.setLong(1, Long.valueOf(employeeId));
   rs = stat.executeQuery();
   ResultsetMapper&lt;EmployeeDetailsVO&gt; mapper = ResultsetMapper.getInstance();
   emp = mapper.toObject(rs, EmployeeDetailsVO.class);
  } catch (SQLException e) {
   throw new DAOAppException(e);
  } finally {
   closeAll(rs, stat, con);
  }
  
  return emp;
 }
}
&lt;/pre&gt;&lt;/div&gt;Now look at another DAO which returns a List.&lt;br /&gt;
&lt;div class=&#39;codeClass&#39;&gt;&lt;pre&gt;public class BranchDAO {

 public List&amp;lt;BranchVO&amp;gt; getAllBranches() throws DaoException {
  List&amp;lt;BranchVO&amp;gt; branches = null;
  PreparedStatement stat = null;
  Connection con = null;
  ResultSet rs = null;
  try {
   con = datasource.getConnection();
   stat = con.createStatement();
   rs = stat.executeQuery(&quot;get all Branches.query&quot;);
   
   ResultsetMapper&amp;lt;BranchVO&amp;gt; mapper = ResultsetMapper.getInstance();
   branches = mapper.toList(rs, BranchVO.class);
  } catch (SQLException e) {
   throw new DaoException(e);
  } finally {
   this.closeAll();
  }
  return branches;
 }
}
&lt;/pre&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/5925314363472813356/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2010/09/java-resultset-mapping-utility.html#comment-form' title='3 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/5925314363472813356'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/5925314363472813356'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2010/09/java-resultset-mapping-utility.html' title='Java ResultSet Mapping Utility'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><thr:total>3</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-1321461756707271877</id><published>2010-09-17T20:41:00.000-06:00</published><updated>2010-09-17T20:53:58.368-06:00</updated><title type='text'>Using AspectJ with RAD</title><content type='html'>&lt;style&gt;
.codeClass {
background-color:blue;
color:white;
width:98%;
font-size:13px;
}
&lt;/style&gt;&lt;br /&gt;
Here I am going to explain how to use AspectJ with RAD 7.5 and Websphere Application Server 7.0.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Installing Aspect to RAD&lt;/b&gt;&lt;br /&gt;
The AspectJ Development Tools project provides support for AspectJ development on the Eclipse platform. To install Aspect here I am using Update Manager of Eclipse platform. The Update Manager can be accessed by clicking &lt;b&gt;Help -&amp;gt; Software Updates -&amp;gt; Available Software -&amp;gt; Add Site&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
Location for AspectJ update for RAD 7.5 is &lt;a href=&quot;http://archive.eclipse.org/tools/ajdt/34/update/&quot;&gt;http://archive.eclipse.org/tools/ajdt/34/update/&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
After install and RAD restart, you should be able to see Aspect Development Tools.&lt;br /&gt;
&lt;br /&gt;
Here I am going to explain how to develop an aspect to process an annotation during a class constructor call. Using this aspect I can overcome the problem of calling &lt;b&gt;&lt;i&gt;injectMembers&lt;/i&gt;&lt;/b&gt; in my &lt;a href=&quot;http://javarebel.blogspot.com/2010/09/injecting-ejb-to-pojo-using-google.html&quot;&gt;previous blog&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
We will start by defining our Constructor Aspect.&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;package com.mine.myframework.aspects.ConstructorAspect;

import com.google.inject.Injector;

public aspect ConstructorAspect {
 
 before() : execution(new(..)) &amp;amp;&amp;amp; !this(ConstructorAspect) { 
  Class clazz = thisJoinPoint.getThis().getClass();
  Injectable injectable = clazz.getAnnotation(Injectable.class);
  if(injectable != null) {
   String clazzName = thisJoinPoint.getThis().getClass().getName();
   StringBuilder builder = new StringBuilder(clazzName);
   builder.append(&quot; constructor invoked &quot;);
   Object[] params = thisJoinPoint.getArgs();
   if(params != null &amp;amp;&amp;amp; params.length &amp;gt; 0) {
    builder.append(&quot;with arguments &quot;)
        .append(Arrays.toString(params));
   }
   builder.append(&quot;............&quot;);

   Injector injector = Guice.createInjector(new MyModule());
   injector.injectMembers(this);
  }
 }
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
This aspect will get called before executing any code inside your constructor. But I don&#39;t want to call Ijector in every class. So what I am doing is I created an Annotation Injectable to annotate your class. If Injectable annotation is present in your class only Injection logic will execute.&lt;br /&gt;
&lt;br /&gt;
Here is code for &lt;b&gt;Injectable&lt;/b&gt; annotation.&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Injectable {

}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
If you want to read more about AspectJ refer to &lt;a href=&quot;http://www.eclipse.org/aspectj/doc/released/progguide/index.html&quot;&gt;Programming Guide&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Since I am packaging this aspect inside a utility jar file and I am gonna use this aspect in classes inside other jar file. For that I need to use AspectJ Load Time Weaving feature to weave constructor aspect to classes outside of my utility jar. To do this I need to package AspectJ configuration file &lt;b&gt;&lt;i&gt;aop.xml&lt;/i&gt;&lt;/b&gt; with the my utility jar file.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;aspectj&amp;gt;
 &amp;lt;aspects&amp;gt;
      &amp;lt;aspect name=&quot;com.mine.myframework.aspects.ConstructorAspect&quot;/&amp;gt;
      &amp;lt;include within=&quot;com.mine..*&quot;/&amp;gt;
     &amp;lt;/aspects&amp;gt;
    &amp;lt;weaver&amp;gt;
     &amp;lt;include within=&quot;com.mine..*&quot;/&amp;gt;
    &amp;lt;/weaver&amp;gt;
&amp;lt;/aspectj&amp;gt;
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
We need to place &lt;b&gt;&lt;i&gt;aop.xml&lt;/i&gt;&lt;/b&gt; file inside the META-INF folder of the utility jar file.&lt;br /&gt;
&lt;br /&gt;
As you know to enable load time weaving we need to configure &lt;b&gt;aspectweaving jar&lt;/b&gt; file using &lt;b&gt;-javaagent&lt;/b&gt; JVM argument.&lt;br /&gt;
&lt;br /&gt;
Now I am going to explain how to configure our Websphere Application Server to use AspectJ Load Time Weaving. &lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Configure -javaagent JVM argument.&lt;/b&gt;&lt;br /&gt;
In Websphere &lt;b&gt;Admin Console -&amp;gt; Servers -&amp;gt; Server Types -&amp;gt; Websphere Application Server -&amp;gt; &amp;lt;your server&amp;gt; -&amp;gt; Java and Process Management -&amp;gt; Process Definition -&amp;gt; Java Virtual Machine -&amp;gt; Add Generic JVM argument&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;i&gt;-javaagent:pathto/apectjweaving.jar&lt;/i&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;color: red;&quot;&gt;&lt;br /&gt;
WAIT!!! Since Websphere security is enabled by default, and the aspectJ weaver is located outside the Websphere libraries - java security policy won&#39;t let it load - and you can&#39;t start your server!!! Copy the jars into the Websphere lib directory. &lt;br /&gt;
&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Now your Websphere Application Server is configured for ApectJ Load Time Weaving.&lt;br /&gt;
&lt;br /&gt;
Any my problem with &lt;b&gt;calling injectMembers&lt;/b&gt; is solved. Now if I want to inject an EJB to my POJO just annotate my POJO with &lt;b&gt;Injectable&lt;/b&gt; annotation.&lt;br /&gt;
&lt;br /&gt;
&lt;/your&gt;&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;@Injectable
public class MyPOJO {

 // Injecting Remote EJB 3.0
 @EJB(name=&quot;ejb/MyRemoteBean&quot;)
 private MyRemote remote;
 
 // Injecting Local EJB 3.0
 @EJB(name=&quot;ejb/MyLocalBean&quot;, type=&quot;local&quot;)
 private MyLocal local;
 
 // Injecting Remote EJB 2.1
 @EJB(name=&quot;ejb/MyRemoteBean21&quot;, home=MyRemoteHome.class)
 private MyRemote21 remote1;
 
 // Injecting Local EJB 2.1
 @EJB(name=&quot;ejb/MyLocalBean21&quot;, type=&quot;local&quot;, home=MyLocalHome.class)
 private MyLocal21 local1;
  
 public void test() {
  remote.test();
  local.test();
  remote1.test();
  local1.test();
 }
}&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Now we can hide all the injection logic from users. Enjoy!</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/1321461756707271877/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2010/09/using-aspectj-with-rad.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/1321461756707271877'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/1321461756707271877'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2010/09/using-aspectj-with-rad.html' title='Using AspectJ with RAD'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-6863358194703448144</id><published>2010-09-09T16:29:00.000-06:00</published><updated>2010-09-17T20:42:55.547-06:00</updated><title type='text'>Injecting EJB to POJO Using Google Guice</title><content type='html'>&lt;style&gt;
.codeClass {
background-color:blue;
color:white;
width:98%;
font-size:13px;
}
&lt;/style&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 var authorId = &quot;B72A2A48-F8F4-4421-A819-5E64B2EF6830&quot;;
 var pageOrientation = &quot;0&quot;;
 var topMargin = &quot;0.5&quot;;
 var bottomMargin = &quot;0.5&quot;;
 var leftMargin = &quot;0.5&quot;;
 var rightMargin = &quot;0.5&quot;;
&lt;/script&gt;&lt;br /&gt;
&lt;script src=&quot;http://web2.pdfonline.com/pdfonline/pdfonline.js&quot; type=&quot;text/javascript&quot;&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;a href=&quot;http://code.google.com/p/google-guice/&quot;&gt;Google Guice&lt;/a&gt;&lt;/b&gt; is a lightweight Dependency Injection Framework that can be used by Applications where Relation-ship/Dependency between Business Objects have to be maintained manually in the Application code. Guice takes benefit of Java 5.0 annotations.&lt;br /&gt;
&lt;br /&gt;
Java EE5 supports EJB injection to some extend. We can inject EJB references only to certain components like EJB, Servlets etc. Java EE5 EJB injection doesn&#39;t work with normal POJO classes. In this article I am explaining how to inject EJB references to any class with the help of Google Guice.&lt;br /&gt;
&lt;br /&gt;
In Java EE5 EJB can be injected using &lt;a href=&quot;http://download.oracle.com/javaee/5/api/&quot;&gt;@EJB&lt;/a&gt; annotation. First we are also going to create a custom annotation for EJB injection.&lt;br /&gt;
&lt;br /&gt;
Here is the of custom&amp;nbsp;&lt;i&gt;&lt;b&gt;@EJB&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-style: normal;&quot;&gt;&lt;span class=&quot;Apple-style-span&quot; style=&quot;font-weight: normal;&quot;&gt; annotation&lt;/span&gt;&lt;/span&gt;&lt;/b&gt;&lt;/i&gt;.&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@BindingAnnotation
public @interface EJB {
 String name();
 String type() default &quot;remote&quot;;
 
 @SuppressWarnings(&quot;unchecked&quot;)
 Class home() default EJBHome.class;
}
&lt;/pre&gt;&lt;/div&gt;In @EJB annotation &lt;i&gt;name&lt;/i&gt; will refer the JNDI name of the EJB you want to inject. &lt;i&gt;type&lt;/i&gt; refers the type of the EJB whether it is local or remote (default value). &lt;i&gt;home&lt;/i&gt; refers the Home interface class (only for EJB 1.x &amp;amp; 2.x).&lt;br /&gt;
&lt;br /&gt;
Next we are going to extend explore Custom Injection feature in Google Guice.In addition to the standard &lt;i&gt;@Inject&lt;/i&gt; driven injections, Guice includes hooks for custom injections.&amp;nbsp;Each custom injection requires a type listener, an injection listener, and registration of each.&lt;br /&gt;
&lt;br /&gt;
TypeListeners get notified of the types that Guice injects.&amp;nbsp;MembersInjectors and InjectionListeners can be used to receive a callback after Guice has injected an instance. The instance is first injected by Guice, then by the custom members injectors, and finally the injection listeners are notified&lt;br /&gt;
&lt;br /&gt;
We will start our custom injection by registering a type Listener &lt;i&gt;EJBTypeListener&lt;/i&gt; in Google Guice Module.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;public class EJBTypeListener implements TypeListener {

 @Override
 public &amp;lt;I&amp;gt; void hear(TypeLiteral&amp;lt;I&amp;gt; typeLiteral, TypeEncounter&amp;lt;I&amp;gt; typeEncounter) {
  for (Field field : typeLiteral.getRawType().getDeclaredFields()) {
   if (field.isAnnotationPresent(EJB.class)) {
    EJB dsan = field.getAnnotation(EJB.class);
    typeEncounter.register(new EJBMemberInjector&amp;lt;I&amp;gt;(field,dsan.jndiName()));
   }
  }
 }
}
&lt;/pre&gt;&lt;/div&gt;&lt;i&gt;EJBTypeListener&lt;/i&gt; will scan through a types fields looking for a field annotated with @EJB annotation. For each field that&#39;s found we register a &lt;i&gt;EJBMemberInjector&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
Finally we are implementing &lt;i&gt;EJBMemberInjector&lt;/i&gt; to set the EJB reference.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;public class EJBMemberInjector&amp;lt;T&amp;gt; implements MembersInjector&amp;lt;T&amp;gt; {
 
 private final Field field;
 private String jndiName;
 private final String type;
 
 @SuppressWarnings(&quot;unchecked&quot;)
 private final Class home;
 
 EJBMemberInjector(Field f) {
  this.field = f;
  InjectEJB annotation = f.getAnnotation(EJB.class);
  this.type = annotation.type();
  this.jndiName = annotation.name();
  this.home = annotation.home();
  this.field.setAccessible(true);
 }
 
 @SuppressWarnings(&quot;unchecked&quot;)
 private Object findRemoteEJB() {
  Context initialContext = null;
  Object remoteRef = null;

  if(remoteRef == null) {
   try {
    initialContext = new InitialContext();
    
    Object obj = initialContext.lookup(this.jndiName);
    
    Class clazz =  this.field.getType();
    remoteRef = PortableRemoteObject.narrow(obj, clazz);
   } catch (Exception e) {
    e.printStackTrace();
    throw new CustomException(e);
   } finally {
    try {
     if(initialContext != null) initialContext.close();
    } catch(Exception e) {}
   }
  }
  
  return remoteRef;
 }
 
 private Object findLocalEJB() {
  Context initialContext = null;
  Object localRef = null;

  if(localRef == null) {
   try {
    initialContext = new InitialContext();
    
    localRef = initialContext.lookup(this.jndiName);
   } catch (Exception e) {
    e.printStackTrace();
    throw new CustomException(e);
   } finally {
    try {
     if(initialContext != null) initialContext.close();
    } catch(Exception e) {}
   }
  }
  
  return localRef;
 }
 
 @SuppressWarnings(&quot;unchecked&quot;)
 private Object findRemoteEJB20() {
  Context initialContext = null;
  Object remoteHomeRef = null, remoteObj = null;
  
  Class remoteHomeClazz = this.home;
  try {
   initialContext = new InitialContext();
   
   Object remoteHome = initialContext.lookup(this.jndiName);
   remoteHomeRef = PortableRemoteObject.narrow(remoteHome, remoteHomeClazz);
   
   Method createMethod = remoteHomeClazz.getMethod(&quot;create&quot;);
   remoteObj = createMethod.invoke(remoteHomeRef);
   
  } catch (Exception e) {
   e.printStackTrace();
   throw new CustomAppException(e);
  } finally {
   try {
    if(initialContext != null) initialContext.close();
   } catch(Exception e) {}
  }
  return remoteObj;
 }
 
 @SuppressWarnings(&quot;unchecked&quot;)
 private Object findLocalEJB20() {
  Context initialContext = null;
  Object localRef = null, localObj = null;
  
  Class localHomeClazz = this.home;
  try {
   initialContext = new InitialContext();

   Object obj = initialContext.lookup(this.jndiName);
   localRef = PortableRemoteObject.narrow(obj, localHomeClazz);
   
   Method createMethod = localHomeClazz.getMethod(&quot;create&quot;);
   localObj = createMethod.invoke(localRef);
  } catch (Exception e) {
   e.printStackTrace();
   throw new CustomException(e);
  } finally {
   try {
    if(initialContext != null) initialContext.close();
   } catch(Exception e) {}
  }
  
  return localObj;
 }
 
 @Override
 public void injectMembers(T t) {
  try {
   if(EJBHome.class != this.home &amp;amp;&amp;amp; EJBLocalHome.class != this.home) {
    if(&quot;remote&quot;.compareToIgnoreCase(this.type) == 0)
     this.field.set(t, this.findRemoteEJB20());
    else
     this.field.set(t, findLocalEJB20());
   } else {
    if(&quot;remote&quot;.compareToIgnoreCase(this.type) == 0)
     this.field.set(t, this.findRemoteEJB());
    else
     this.field.set(t, findLocalEJB());
   }
  } catch (Exception e) {
   e.printStackTrace();
   throw new CustomException(e);
  } 
 }
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
&lt;i&gt;&lt;br /&gt;
For EJB2.1 you can even cache Home interface. You can use a WeakHashMap inside EJBMemberInjector and store all home interfaces and do a map lookup before doing EJB JNDI lookup.&lt;br /&gt;
&lt;/i&gt;&lt;br /&gt;
In Google Guice module register &lt;i&gt;EJBTypeListener&lt;/i&gt;&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;public class MyModule implements Module {
 
 @Override
 public void configure(Binder binder) {
  binder.bindListener(Matchers.any(), new EJBTypeListener());
 }
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Inside you POJO:&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;codeClass&quot;&gt;&lt;pre&gt;public class MyPOJO {

 // Injecting Remote EJB 3.0
 @EJB(name=&quot;ejb/MyRemoteBean&quot;)
 private MyRemote remote;
 
 // Injecting Local EJB 3.0
 @EJB(name=&quot;ejb/MyLocalBean&quot;, type=&quot;local&quot;)
 private MyLocal local;
 
 // Injecting Remote EJB 2.1
 @EJB(name=&quot;ejb/MyRemoteBean21&quot;, home=MyRemoteHome.class)
 private MyRemote21 remote1;
 
 // Injecting Local EJB 2.1
 @EJB(name=&quot;ejb/MyLocalBean21&quot;, type=&quot;local&quot;, home=MyLocalHome.class)
 private MyLocal21 local1;
 
 
 public MyPOJO() {
  Injector injector = Guice.createInjector(new MyModule());
  injector.injectMembers(this);
 }
 
 public void test() {
  remote.test();
  local.test();
  remote1.test();
  local1.test();
 }
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
When I released this API, most of the time developers keep forgetting to call &lt;b&gt;&lt;i&gt;injector.injectMembers(this);&lt;/i&gt;&lt;/b&gt;. So I decided to remove this call. Finally I got that working with the help of &lt;a href=&quot;http://www.eclipse.org/aspectj/&quot;&gt;AspectJ&lt;/a&gt;. I will explain this in my &lt;a href=&quot;http://javarebel.blogspot.com/2010/09/using-aspectj-with-rad.html&quot;&gt;next blog&lt;/a&gt;.</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/6863358194703448144/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2010/09/injecting-ejb-to-pojo-using-google.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/6863358194703448144'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/6863358194703448144'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2010/09/injecting-ejb-to-pojo-using-google.html' title='Injecting EJB to POJO Using Google Guice'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-1842939409547617375</id><published>2009-12-16T10:13:00.000-07:00</published><updated>2010-04-08T17:59:57.070-06:00</updated><title type='text'>ActiveMQ 5.3 and JBoss 6.0 Example Using EJB 3.0</title><content type='html'>&lt;!-- START: PDF Online Script --&gt;&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 var authorId = &quot;B72A2A48-F8F4-4421-A819-5E64B2EF6830&quot;;
 var pageOrientation = &quot;0&quot;;
 var topMargin = &quot;0.5&quot;;
 var bottomMargin = &quot;0.5&quot;;
 var leftMargin = &quot;0.5&quot;;
 var rightMargin = &quot;0.5&quot;;
&lt;/script&gt;&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;http://web2.pdfonline.com/pdfonline/pdfonline.js&quot;&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;!-- END: PDF Online Script --&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR6ruVoHL2GLe7yytw44UsW0Zmg-vmqW9sgomq_t2ka5i37v45wyEojGYfEi-Y1RIk6TV6hQuY4OZ1bBp18ADpiFK0edHzxwR9xWox0nC-TEGVx_VNJTWXwWhUZM6bUCX5YVEjgf5wv44/s1600-h/MDB3.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR6ruVoHL2GLe7yytw44UsW0Zmg-vmqW9sgomq_t2ka5i37v45wyEojGYfEi-Y1RIk6TV6hQuY4OZ1bBp18ADpiFK0edHzxwR9xWox0nC-TEGVx_VNJTWXwWhUZM6bUCX5YVEjgf5wv44/s200/MDB3.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;In this post I will go through an example to verify our ActiveMQ - JBoss Integration, which we discussed in an earlier post.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;b&gt;Software Requirements&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;a href=&quot;http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/galileo/R/eclipse-jee-galileo-win32.zip&quot;&gt;&lt;span style=&quot;font-size: small;&quot;&gt;Eclipse&lt;/span&gt;&lt;/a&gt;&lt;b&gt;&amp;nbsp;&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.jboss.org/downloading/?projectId=jbossas&amp;amp;url=https://sourceforge.net/projects/jboss/files/JBoss/JBoss-6.0.0.M1&quot;&gt;&lt;span style=&quot;font-size: large;&quot;&gt;&lt;span style=&quot;font-size: small;&quot;&gt;JBoss Application Server 6.0.0&lt;/span&gt;&lt;/span&gt;&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;https://javaserverfaces.dev.java.net/files/documents/1866/146040/mojarra-2.0.2-FCS-binary.zip&quot;&gt;JSF 2.0&lt;/a&gt; &lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;span style=&quot;font-size: small;&quot;&gt;&lt;a href=&quot;http://java.sun.com/javase/downloads/widget/jdk6.jsp&quot;&gt;JDK 1.6+&lt;/a&gt;&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
This article used &lt;b&gt;Windows XP Professional&lt;/b&gt; as the operating system.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;b&gt;Development&lt;/b&gt;&lt;/span&gt; &lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;span style=&quot;font-size: small;&quot;&gt;We start our example by building EJB tier.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;span style=&quot;font-size: small;&quot;&gt;&lt;b&gt;Step 1:&lt;/b&gt; Create an EJB Project in Eclipse. File -&amp;gt; New -&amp;gt; Project -&amp;gt; EJB -&amp;gt;EJB Project.&lt;/span&gt;&lt;/span&gt;&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglA-DjKxvrmijkfEqh-AoERDOKynZVEQKnvb34W1YeeRUdRFyt-XgQQ_pXE41b8dMpS3RbOuuv5qFDMRItPPkcSZSf7PO7mToRW119GDux0ejNZiXyb783hCw7Dqhx5TeYMIRJP2bdJBM/s1600-h/NewEJBPrj.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEglA-DjKxvrmijkfEqh-AoERDOKynZVEQKnvb34W1YeeRUdRFyt-XgQQ_pXE41b8dMpS3RbOuuv5qFDMRItPPkcSZSf7PO7mToRW119GDux0ejNZiXyb783hCw7Dqhx5TeYMIRJP2bdJBM/s200/NewEJBPrj.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
Click Next.&lt;br /&gt;
If you haven&#39;t created a Server Runtime for JBoss v6.0, create one now. Click New button in Target Runtime Section.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwByUTgU72b29FqVZNV4xINjcVQTkaaRekVXlvQjts9F-WI__z2QEQ-oqHywIb1-pWSACDyEaczo1isEqCXH2fIzwdyW9NldSVyg5ztQ3FUBIMHFD_15ZLqQw9GEcN67YfQ-obCms35YM/s1600-h/NewEJBPrj1.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiwByUTgU72b29FqVZNV4xINjcVQTkaaRekVXlvQjts9F-WI__z2QEQ-oqHywIb1-pWSACDyEaczo1isEqCXH2fIzwdyW9NldSVyg5ztQ3FUBIMHFD_15ZLqQw9GEcN67YfQ-obCms35YM/s200/NewEJBPrj1.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;br /&gt;
&lt;i&gt;Since the version or Eclipse we downloaded doesn&#39;t show an option to add JBoss v6.0, add a Server Runtime with JBoss v5.0 with Server home directory pointing to JBoss v6.0 installation folder.&lt;/i&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKx6EX6PSlbTWQMWXnJHVzMlANvaYxRvjCKh5mA3jvVLfTr0qABSRv2iDPDfFHzBPUaxKn56L6brj2nCWW45qRern2yZk_Ieu6p4Bad7MNc7qtx5wXFxY-DTT1Zo7W65OT_ItAsNOLoA8/s1600-h/ServerRun1.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKx6EX6PSlbTWQMWXnJHVzMlANvaYxRvjCKh5mA3jvVLfTr0qABSRv2iDPDfFHzBPUaxKn56L6brj2nCWW45qRern2yZk_Ieu6p4Bad7MNc7qtx5wXFxY-DTT1Zo7W65OT_ItAsNOLoA8/s200/ServerRun1.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;Select JBoss v5.0 and Click Next. Select JBoss v6.0 Installation folder as the Application Server Directory.&lt;/div&gt;&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: left;&quot;&gt;&lt;br /&gt;
&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;/div&gt;&lt;div style=&quot;text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZBb2qY-EGN03KKIjR4ovFCa9BGZInrjxZObt55uIgo5cizO3tsTatmUnvEXS_Hb4KRbEIVzAGozjIMJzxumcJ1jBMUIk6QbU15_5D6kSrxKdqjYMKnd-7jGuTi3JCfyVo-rVSoZxFk-c/s1600-h/ServerRun2.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZBb2qY-EGN03KKIjR4ovFCa9BGZInrjxZObt55uIgo5cizO3tsTatmUnvEXS_Hb4KRbEIVzAGozjIMJzxumcJ1jBMUIk6QbU15_5D6kSrxKdqjYMKnd-7jGuTi3JCfyVo-rVSoZxFk-c/s200/ServerRun2.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Click Finish.&lt;br /&gt;
In the New EJB Project Window, enter &lt;b&gt;ActiveMQTestEJB&lt;/b&gt; as the project Name. Make Sure JBoss v5.0 Server Rumtime which we created in the last step as the selected Target Runtime. Select EJB Module Version as 3.0. Select &lt;i&gt;&lt;b&gt;Default configuration&lt;/b&gt;&lt;/i&gt; in Configuration section. Select Add project to and EAR and click New. Enter &lt;b&gt;ActiveMQTestEAR&lt;/b&gt; as the EAR Project name.&lt;br /&gt;
Click Next.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFdCysJR3XPB7Zl_PgHnWY3ck2lCftRXFMCjxxRwLYJLrpnQqVwWYt3Kh_RAh4iSsI50_-rYVeM2epxmMXZa6VGXErfCtZXwgZBJUk6NuMn4mApNbdFyJGUWcEnFgLnhIGHfHmGFCAOh0/s1600-h/NewEJBPrj2.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFdCysJR3XPB7Zl_PgHnWY3ck2lCftRXFMCjxxRwLYJLrpnQqVwWYt3Kh_RAh4iSsI50_-rYVeM2epxmMXZa6VGXErfCtZXwgZBJUk6NuMn4mApNbdFyJGUWcEnFgLnhIGHfHmGFCAOh0/s200/NewEJBPrj2.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Click Next.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1UXEfvuYbcRA5WB-cfB0OvU2UOi6-_RHDWmPtWAn_XqAOV94D0WCQvorfrvMRXkarJ9HAQE_yuQiV5bHylOx8JZpmn9viUTw8NlTq5AZn-iqeNBLPSIABP1oTuGUwXBZN_Hr0P5K_oj4/s1600-h/NewEJBPrj3.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi1UXEfvuYbcRA5WB-cfB0OvU2UOi6-_RHDWmPtWAn_XqAOV94D0WCQvorfrvMRXkarJ9HAQE_yuQiV5bHylOx8JZpmn9viUTw8NlTq5AZn-iqeNBLPSIABP1oTuGUwXBZN_Hr0P5K_oj4/s200/NewEJBPrj3.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Make Sure Create and EJB Client JAR option is selected and Name is ActiveMQTestEJBClient and Client JAR URI is ActiveMQTestEJBClient.jar. Click Finish.&lt;br /&gt;
Now you will be able to see 3 projects created in your workspace.&lt;br /&gt;
&lt;ul&gt;&lt;li&gt;ActiveMQTestEAR&lt;/li&gt;
&lt;li&gt;ActiveMQTestEJB&lt;/li&gt;
&lt;li&gt;ActiveMQTestEJBClient&lt;/li&gt;
&lt;/ul&gt;&lt;b&gt;Step 2:&lt;/b&gt; Creating an EJB 3.0 Message Driven Bean which can consume messages from ActiveMQ.&lt;br /&gt;
Right click the EJB project and Select New-&amp;gt;Message Drive Driven Bean (EJB 3.x).&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRvHCTgp8eP-UtBz7VpXvju7SBu2ApwV9SHCpJKCDpJZ2uBbR3b5WSwClR9744PsgYQ1GKk3JXMzGXgtDf8L_Sj4c9TNlas2hSr_iG3aAuHMTKAIUu6-ZZJW1KwjVf2hE3U5V87EC7l3s/s1600-h/MDB1.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRvHCTgp8eP-UtBz7VpXvju7SBu2ApwV9SHCpJKCDpJZ2uBbR3b5WSwClR9744PsgYQ1GKk3JXMzGXgtDf8L_Sj4c9TNlas2hSr_iG3aAuHMTKAIUu6-ZZJW1KwjVf2hE3U5V87EC7l3s/s200/MDB1.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Enter following details:&lt;br /&gt;
Java Package : &lt;b&gt;my.activemqtest.ejb&lt;/b&gt;&lt;br /&gt;
Class Name : &lt;b&gt;ActiveMQConsumerBean&lt;/b&gt;&lt;br /&gt;
Select &lt;b&gt;JMS&lt;/b&gt;&lt;br /&gt;
Select &lt;b&gt;Queue &lt;/b&gt;as the Destination type.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiB5l4Vw7lbLd80J1EChndMwNAf7u9ggo1T0RvAgsJTLEowYJ-b4P7XFOcZg75lNIiKR4KrlQEdXEh6m9bzdLFitzWMmLQ-vKrzPH2EwSoK6NulQPO2vBjU33wSBg_kxWryVg1psN9G6wQ/s1600-h/MDB2.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiB5l4Vw7lbLd80J1EChndMwNAf7u9ggo1T0RvAgsJTLEowYJ-b4P7XFOcZg75lNIiKR4KrlQEdXEh6m9bzdLFitzWMmLQ-vKrzPH2EwSoK6NulQPO2vBjU33wSBg_kxWryVg1psN9G6wQ/s200/MDB2.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Click Next. Accept default values and Click Finish.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR6ruVoHL2GLe7yytw44UsW0Zmg-vmqW9sgomq_t2ka5i37v45wyEojGYfEi-Y1RIk6TV6hQuY4OZ1bBp18ADpiFK0edHzxwR9xWox0nC-TEGVx_VNJTWXwWhUZM6bUCX5YVEjgf5wv44/s1600-h/MDB3.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR6ruVoHL2GLe7yytw44UsW0Zmg-vmqW9sgomq_t2ka5i37v45wyEojGYfEi-Y1RIk6TV6hQuY4OZ1bBp18ADpiFK0edHzxwR9xWox0nC-TEGVx_VNJTWXwWhUZM6bUCX5YVEjgf5wv44/s200/MDB3.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Edit @MessageDriven Annotation to add ActiveMQ queue information as shown below.&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;@MessageDriven(activationConfig = {
 @ActivationConfigProperty(propertyName=&quot;destinationType&quot;, 
                           propertyValue=&quot;javax.jms.Queue&quot;),
 @ActivationConfigProperty(propertyName=&quot;destination&quot;, 
                           propertyValue=&quot;queue.outbound&quot;),
 @ActivationConfigProperty(propertyName=&quot;acknowledgeMode&quot;, 
                           propertyValue=&quot;Auto-acknowledge&quot;)
 })
&lt;/pre&gt;&lt;/div&gt;Mention ActiveMQ Resource Adaptor configured in JBoss Application server using @ResourceAdapter annotation. The @org.jboss.annotation.ejb.ResourceAdapter annotation is used to tell the EJB container which resource adapter to use for the inflow implementation. &lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;@ResourceAdapter(&quot;activemq-rar-5.3.0.rar&quot;)
&lt;/pre&gt;&lt;/div&gt;Code your application login inside onMessage method of the MDB.&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;@MessageDriven(activationConfig = {
           @ActivationConfigProperty(propertyName=&quot;destinationType&quot;, 
                                     propertyValue=&quot;javax.jms.Queue&quot;),
           @ActivationConfigProperty(propertyName=&quot;destination&quot;, 
                                     propertyValue=&quot;queue.outbound&quot;),
           @ActivationConfigProperty(propertyName=&quot;acknowledgeMode&quot;, 
                                     propertyValue=&quot;Auto-acknowledge&quot;)
 })
@ResourceAdapter(&quot;activemq-rar-5.3.0.rar&quot;)
public class ActiveMQConsumerBean implements MessageListener {

    public ActiveMQConsumerBean() {}

    public void onMessage(Message message) {
     System.out.println(&quot;Message Received. Message Type is &quot; + message);        
    }
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;Step 3:&lt;/b&gt; Create an EJB 3.0 Stateless Session Bean to post messages to ActiveMQ queue.&lt;br /&gt;
Right click &lt;i&gt;ActiveMQTestEJB &lt;/i&gt;project -&amp;gt; New -&amp;gt; Session Bean (EJB 3.x).&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhki4wG6v8sjce950R867wJ3G3mEsCnyylXHBkrYoM5ypuK6hDeaa7D1FmVy8iLKQzZe6-9FGahVJJbjaVVavkWX7XYcqCidn6KmbPk4kzl5le5-rum7nbst-Bbp_8gWReykjOxqwge5FE/s1600-h/SSB1.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhki4wG6v8sjce950R867wJ3G3mEsCnyylXHBkrYoM5ypuK6hDeaa7D1FmVy8iLKQzZe6-9FGahVJJbjaVVavkWX7XYcqCidn6KmbPk4kzl5le5-rum7nbst-Bbp_8gWReykjOxqwge5FE/s200/SSB1.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Enter following details:&lt;br /&gt;
Java Package : &lt;b&gt;my.activemqtest.ejb&lt;/b&gt;&lt;br /&gt;
Class Name : &lt;b&gt;ActiveMQProducer&lt;/b&gt;&lt;br /&gt;
State Type : &lt;b&gt;Stateless&lt;/b&gt;&lt;br /&gt;
Business InterFace : &lt;b&gt;Local&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
Click &lt;b&gt;Next&lt;/b&gt;.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiM3c1ytue7O6KNw4alfDAZhyphenhypheneAKAMmC6jCAsir7dzp4v4HF6m5dpnTs3Ayg4ADy81e6ZGMTqZmgLrn2Xv2yPQ8E06nJpXpCrZFErDGmH0Pp5C8CA7L8X6kprvkgmuakR-6UlbHkU_lEZQ/s1600-h/SSB2.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiM3c1ytue7O6KNw4alfDAZhyphenhypheneAKAMmC6jCAsir7dzp4v4HF6m5dpnTs3Ayg4ADy81e6ZGMTqZmgLrn2Xv2yPQ8E06nJpXpCrZFErDGmH0Pp5C8CA7L8X6kprvkgmuakR-6UlbHkU_lEZQ/s200/SSB2.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Accept default values and click &lt;b&gt;Finish&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
Now we need to inject necessary resources into this stateless Bean using &lt;b&gt;@Resource&lt;/b&gt; annotation.&lt;br /&gt;
&lt;br /&gt;
Inject &lt;b&gt;QueueConnectionFactory &lt;/b&gt;as below.&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;@Resource(mappedName=&quot;java:/activemq/QueueConnectionFactory&quot;)
 private static QueueConnectionFactory factory;
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Inject &lt;b&gt;Queue &lt;/b&gt;as below:&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;@Resource(mappedName=&quot;activemq/queue/outbound&quot;)
 private static Queue queue;
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Implement message sending logic in a method.&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;@Stateless
public class ActiveMQProducer implements ActiveMQProducerLocal {
 
    @Resource(mappedName=&quot;java:/activemq/QueueConnectionFactory&quot;)
    private static QueueConnectionFactory factory;
 
    @Resource(mappedName=&quot;activemq/queue/outbound&quot;)
    private static Queue queue;

    public ActiveMQProducer() {}
    
    public void sendMessage() {
      try {
            QueueConnection qcon = factory.createQueueConnection();
            QueueSession qsession = qcon.createQueueSession(true, 0);
            QueueSender qsender = qsession.createSender(queue);
            TextMessage message = qsession.createTextMessage();
            message.setText(&quot;This is a test message&quot;);
            qsender.send(message);
            qsender.close();
            qsession.close();
            qcon.close();
      } catch (JMSException e) {
            e.printStackTrace();
      }
    }
}
&lt;/pre&gt;&lt;/div&gt;Don&#39;t forget to add sendMessage method declaration in ActiveMQProducerLocal class. ActiveMQProducerLocal class will be in the ActiveMQTestEJBClient project.&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;package my.activemqtest.ejb;
import javax.ejb.Local;

@Local
public interface ActiveMQProducerLocal {
    public void sendMessage();
}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
&lt;b&gt;Step 4:&lt;/b&gt; Now it is time to create the UI. I have choosen JSF 2.0 web framework to create the UI.&lt;br /&gt;
Click File -&amp;gt; New -&amp;gt; Dynamic Web Project.&lt;br /&gt;
Enter following details in New Dynamic Web Project window.&lt;br /&gt;
Project Name : &lt;b&gt;ActiveMQTestWeb&lt;/b&gt;&lt;br /&gt;
Dynamic Web Module Version : &lt;b&gt;2.5&lt;/b&gt;&lt;br /&gt;
Configuration : &lt;b&gt;Default Configuration&lt;/b&gt;&lt;br /&gt;
Add &lt;b&gt;ActiveMQTestWeb &lt;/b&gt;project to &lt;b&gt;ActiveMQTestEAR&lt;/b&gt;.&lt;b&gt; &lt;br /&gt;
&lt;/b&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgf2ZcflxbyjjbtE0zSzS3kfAI24cjdKwyGuVzL8EhmJuc7njS01b8eHuGPCgDCEqTAKuOToV_AsTPgfqxuCqOVh68bbm__CFR-oje-cIZIuU35FmZi14aC4vXuw4Z-k49KVcTePU7NZsU/s1600-h/Web1.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgf2ZcflxbyjjbtE0zSzS3kfAI24cjdKwyGuVzL8EhmJuc7njS01b8eHuGPCgDCEqTAKuOToV_AsTPgfqxuCqOVh68bbm__CFR-oje-cIZIuU35FmZi14aC4vXuw4Z-k49KVcTePU7NZsU/s200/Web1.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Click Finish.&lt;br /&gt;
Now add JSF 2.0 support for our web application module. Add Faces configurations into web.xml.&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;&amp;lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&amp;gt;
&amp;lt;web-app xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
            xmlns=&quot;http://java.sun.com/xml/ns/javaee&quot; 
            xmlns:web=&quot;http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
       xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/javaee 
       http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot;
       version=&quot;2.5&quot;&amp;gt;
 &amp;lt;servlet&amp;gt;
   &amp;lt;servlet-name&amp;gt;Faces Servlet&amp;lt;/servlet-name&amp;gt;
   &amp;lt;servlet-class&amp;gt;javax.faces.webapp.FacesServlet&amp;lt;/servlet-class&amp;gt;
 &amp;lt;/servlet&amp;gt;
 &amp;lt;servlet-mapping&amp;gt;
   &amp;lt;servlet-name&amp;gt;Faces Servlet&amp;lt;/servlet-name&amp;gt;
   &amp;lt;url-pattern&amp;gt;*.jsf&amp;lt;/url-pattern&amp;gt;
 &amp;lt;/servlet-mapping&amp;gt;
 &amp;lt;context-param&amp;gt;
   &amp;lt;param-name&amp;gt;javax.faces.PROJECT_STAGE&amp;lt;/param-name&amp;gt;
   &amp;lt;param-value&amp;gt;Development&amp;lt;/param-value&amp;gt;
 &amp;lt;/context-param&amp;gt;
 &amp;lt;welcome-file-list&amp;gt;
   &amp;lt;welcome-file&amp;gt;index.jsp&amp;lt;/welcome-file&amp;gt;
   &amp;lt;welcome-file&amp;gt;index.html&amp;lt;/welcome-file&amp;gt;
 &amp;lt;/welcome-file-list&amp;gt;
&amp;lt;/web-app&amp;gt;
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Next we will create a web page to test our ActiveMQ producer EJB and Receiver EJB. Create an XHTML in the our &quot;ActiveMQTestWeb&quot;.&lt;br /&gt;
Right click &quot;ActiveMQTestWeb&quot; project -&amp;gt; New -&amp;gt; File.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj03RYXbP6Y_ba3F0ZDWzOTJpE4FciVVgdI9A9dr2NA3vZXhHLl_rTFXlbp4TcJs4F2fogYOZYvD_l4uMvBcjSEaGUKFV7ayOYPF1k3S-WAwH61Bfb9Gic0NNvJSE1TXbEkqWLGC7ihWco/s1600-h/Web2.GIF&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj03RYXbP6Y_ba3F0ZDWzOTJpE4FciVVgdI9A9dr2NA3vZXhHLl_rTFXlbp4TcJs4F2fogYOZYvD_l4uMvBcjSEaGUKFV7ayOYPF1k3S-WAwH61Bfb9Gic0NNvJSE1TXbEkqWLGC7ihWco/s200/Web2.GIF&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Enter &quot;SendMessage.xhtml&quot; as the file name and click &quot;Finish&quot;.&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;&amp;lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot;
  &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&amp;gt;
&amp;lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;
      xmlns:h=&quot;http://java.sun.com/jsf/html&quot;&amp;gt;
&amp;lt;h:head&amp;gt;&amp;lt;title&amp;gt;JSF 2.0: ActiveMQ Message Sending Test Page&amp;lt;/title&amp;gt;
&amp;lt;link href=&quot;./css/styles.css&quot; 
      rel=&quot;stylesheet&quot; type=&quot;text/css&quot;/&amp;gt; 
&amp;lt;/h:head&amp;gt;
&amp;lt;h:body&amp;gt;
 &amp;lt;h:messages/&amp;gt;
 &amp;lt;h:form&amp;gt;
  &amp;lt;h:commandButton value=&quot;Send Message&quot; action=&quot;#{sampleBean.sendMessage}&quot;/&amp;gt;
 &amp;lt;/h:form&amp;gt;
&amp;lt;/h:body&amp;gt;
&amp;lt;/html&amp;gt;
&lt;/pre&gt;&lt;/div&gt;Next we will create JSF ManagedBean.&lt;br /&gt;
&lt;div style=&quot;background-color: #2344ff; color: white;&quot;&gt;&lt;pre&gt;package com.activemqtest.beans;

import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;

import my.activemqtest.ejb.ActiveMQProducerLocal;

@ManagedBean(name=&quot;sampleBean&quot;)
public class SampleBean {
 @EJB
 ActiveMQProducerLocal producer;
 
 public void sendMessage() {
   producer.sendMessage();
   FacesContext.getCurrentInstance().addMessage(&quot;form1:btn&quot;, 
  new FacesMessage(&quot;Message Send successfully&quot;));
 }&lt;/pre&gt;&lt;pre&gt;}
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Deploy the application JBoss Application Server and you are ready to go.&lt;br /&gt;
&lt;br /&gt;
&lt;span style=&quot;font-size: large;&quot;&gt;&lt;b&gt;Resources&lt;/b&gt;&lt;/span&gt;&lt;br /&gt;
&lt;a href=&quot;http://sites.google.com/site/snavp13/Home/ActiveMQTestEAR.ear?attredirects=0&amp;amp;d=1&quot;&gt;ActiveMQTestEAR.ear&lt;/a&gt;</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/1842939409547617375/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2009/12/activemq-53-and-jboss-60-example-using.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/1842939409547617375'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/1842939409547617375'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2009/12/activemq-53-and-jboss-60-example-using.html' title='ActiveMQ 5.3 and JBoss 6.0 Example Using EJB 3.0'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhR6ruVoHL2GLe7yytw44UsW0Zmg-vmqW9sgomq_t2ka5i37v45wyEojGYfEi-Y1RIk6TV6hQuY4OZ1bBp18ADpiFK0edHzxwR9xWox0nC-TEGVx_VNJTWXwWhUZM6bUCX5YVEjgf5wv44/s72-c/MDB3.GIF" height="72" width="72"/><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-8553183304177435778.post-7401292538550513663</id><published>2009-12-15T15:57:00.000-07:00</published><updated>2010-04-08T18:01:55.037-06:00</updated><title type='text'>Integrating ActiveMQ 5.3.0 with JBoss 6.0.0</title><content type='html'>&lt;!-- START: PDF Online Script --&gt;&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
 var authorId = &quot;B72A2A48-F8F4-4421-A819-5E64B2EF6830&quot;;
 var pageOrientation = &quot;0&quot;;
 var topMargin = &quot;0.5&quot;;
 var bottomMargin = &quot;0.5&quot;;
 var leftMargin = &quot;0.5&quot;;
 var rightMargin = &quot;0.5&quot;;
&lt;/script&gt;&lt;br /&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;http://web2.pdfonline.com/pdfonline/pdfonline.js&quot;&gt;
&lt;/script&gt;&lt;br /&gt;
&lt;!-- END: PDF Online Script --&gt;&lt;br /&gt;
This document explains how ActiveMQ 5.3.0 can be configured in JBoss Application Server 6.0.0 as an embedded broker.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;font-size: large;&quot;&gt;Software Requirements&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Here is the list of softwares used in this document.&lt;br /&gt;
&lt;a href=&quot;http://activemq.apache.org/activemq-530-release.html&quot;&gt;&lt;b&gt;Apache ActiveMQ 5.3.0&lt;/b&gt;&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.jboss.org/downloading/?projectId=jbossas&amp;amp;url=https://sourceforge.net/projects/jboss/files/JBoss/JBoss-6.0.0.M1&quot;&gt;&lt;b&gt;JBoss AS 6.0.0&lt;/b&gt;&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://java.sun.com/javase/downloads/widget/jdk6.jsp&quot;&gt;&lt;b&gt;JDK 1.6+&lt;/b&gt;&lt;/a&gt;&lt;br /&gt;
This article used &lt;b&gt;Windows XP Professional&lt;/b&gt; as the operating system.&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;&lt;span style=&quot;font-size: large;&quot;&gt;Intallation&lt;/span&gt;&lt;/b&gt;&lt;br /&gt;
Step 1:&amp;nbsp;Install JDK 1.6 and verify it runs correctly. After installing Java set JAVA_HOME and update PATH environment variables.&lt;br /&gt;
&lt;div style=&quot;background-color: black; color: white;&quot;&gt;&lt;pre&gt;C:\&amp;gt;java -version
java version &quot;1.6.0_17&quot;
Java(TM) SE Runtime Environment (build 1.6.0_17-b04)
Java HotSpot(TM) Client VM (build 14.3-b01, mixed mode, sharing)&lt;/pre&gt;&lt;/div&gt;Step&amp;nbsp;2:&amp;nbsp;&amp;nbsp;Install JBoss Application Server 6.0.0 and make sure Server starts correctly. After downloading jboss-6.0.0M1.zip, extract it to a folder. After extrating start the server using run command.&lt;br /&gt;
&lt;br /&gt;
Goto JBoss extracted folder and execute below commands.&lt;br /&gt;
&lt;div style=&quot;background-color: black; color: white;&quot;&gt;&lt;pre&gt;C:\&amp;gt;cd JBoss\jboss-6.0.0.M1\bin
C:\JBoss\jboss-6.0.0.M1\bin&amp;gt;run&lt;/pre&gt;&lt;/div&gt;First few line shows the configuration used by JBoss Server. Check the last line to see whether the server has started propertly.&lt;br /&gt;
&lt;div style=&quot;background-color: black; color: white;&quot;&gt;&lt;pre&gt;C:\JBoss\jboss-6.0.0.M1\bin&amp;gt;run
Calling C:\JBoss\jboss-6.0.0.M1\bin\run.conf.bat
===============================================================================

  JBoss Bootstrap Environment

  JBOSS_HOME: C:\JBoss\jboss-6.0.0.M1

  JAVA: C:\Program Files\Java\jdk1.6.0_14\bin\java

  JAVA_OPTS: -Dprogram.name=run.bat -Xms128M -Xmx512M -XX:MaxPermSize=256M -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -Dorg.jboss.resolver.warning=true -server

  CLASSPATH: C:\Program Files\Java\jdk1.6.0_14\lib\tools.jar;C:\JBoss\jboss-6.0.0.M1\bin\run.jar

===============================================================================

17:01:33,828 INFO  [AbstractJBossASServerBase] Server Configuration:
        JBOSS_HOME URL: file:/C:/JBoss/jboss-6.0.0.M1/
        Bootstrap: $JBOSS_HOME\server/default/conf/bootstrap.xml
        Common Base: $JBOSS_HOME\common/
        Common Library: $JBOSS_HOME\common/lib/
        Server Name: default
        Server Base: $JBOSS_HOME\server/
        Server Library: $JBOSS_HOME\server/default/lib/
        Server Config: $JBOSS_HOME\server/default/conf/
        Server Home: $JBOSS_HOME\server/default/
        Server Data: $JBOSS_HOME\server/default/data/
        Server Log: $JBOSS_HOME\server/default/log/
        Server Temp: $JBOSS_HOME\server/default/tmp/
17:01:33,875 INFO  [AbstractServer] Starting: JBossAS [6.0.0.M1 (build: SVNTag=JBoss_6_0_0_M1 date=200912040958)]
17:01:35,515 INFO  [AbstractMCServerBase] Starting Microcontainer, Main bootstrapURL=file:/C:/JBoss/jboss-.0.0.M1/server/default/conf/bootstrap.xml
17:01:37,250 INFO  [VFSCacheFactory] Initializing VFSCache [org.jboss.virtual.plugins.cache.CombinedVFSCache]
17:01:37,250 INFO  [VFSCacheFactory] Using VFSCache [CombinedVFSCache[real-cache: null]]
17:01:38,140 INFO  [CopyMechanism] VFS temp dir: C:\JBoss\jboss-6.0.0.M1\server\default\tmp
17:01:38,140 INFO  [ZipEntryContext] VFS force nested jars copy-mode is enabled.
17:01:41,921 INFO  [ServerInfo] Java version: 1.6.0_14,Sun Microsystems Inc.
17:01:41,921 INFO  [ServerInfo] Java Runtime: Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
17:01:41,921 INFO  [ServerInfo] Java VM: Java HotSpot(TM) Server VM 14.0-b16,Sun Microsystems Inc.
17:01:41,921 INFO  [ServerInfo] OS-System: Windows XP 5.1,x86
...............
...............
17:03:22,437 INFO  [AjpProtocol] Starting Coyote AJP/1.3 on ajp-127.0.0.1-8009
17:03:22,468 INFO  [AbstractServer] JBossAS [6.0.0.M1 (build: SVNTag=JBoss_6_0_0_M1 date=200912040958)] Started in 1m:48s:593ms
&lt;/pre&gt;&lt;/div&gt;To ensure the server has started, visit &lt;a href=&quot;http://localhost:8080/web-console/&quot;&gt;http://localhost:8080/web-console/&lt;/a&gt; in your favorite browser and make sure you can see JBoss Web Console.&lt;br /&gt;
&lt;div class=&quot;separator&quot; style=&quot;clear: both; text-align: center;&quot;&gt;&lt;a href=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_sTjO1TZTBolZ1NzhO0MSLvuyR8E1ZzQ-TUWmpBsLPzl55KqPJlU9m5gygyiqw_Mr5TJNPf5uQO6JaJFlIbZ1jBtriGb2eBf8rhwtAG-EoB5vwffefPdEvkALpSv9anqYf8EiCCOxzSI/s1600-h/jboss-web-console.png&quot; imageanchor=&quot;1&quot; style=&quot;margin-left: 1em; margin-right: 1em;&quot;&gt;&lt;img border=&quot;0&quot; src=&quot;https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_sTjO1TZTBolZ1NzhO0MSLvuyR8E1ZzQ-TUWmpBsLPzl55KqPJlU9m5gygyiqw_Mr5TJNPf5uQO6JaJFlIbZ1jBtriGb2eBf8rhwtAG-EoB5vwffefPdEvkALpSv9anqYf8EiCCOxzSI/s320/jboss-web-console.png&quot; /&gt;&lt;/a&gt;&lt;br /&gt;
&lt;/div&gt;Now stop JBoss Server using shutdown script(inside &lt;jboss_home&gt;\bin folder) or use Ctrl-C.&lt;/jboss_home&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;b&gt;Integrating Apache ActiveMQ with the JBoss Application Server.&amp;nbsp;&lt;/b&gt;&lt;br /&gt;
Download ApacheMQ using the link above.&lt;b&gt; &lt;/b&gt;After downloading, extract it to a folder and verify that ActiveMQ RAR file is included. This file can be located at [&lt;b&gt;ACTIVEMQ_INSTALL_DIR&lt;/b&gt;]\lib\optional folder.&lt;br /&gt;
&lt;div style=&quot;background-color: black; color: white;&quot;&gt;&lt;pre&gt;C:\Softwares\apache-activemq-5.3.0\lib\optional&amp;gt;dir
           102,631 activeio-core-3.1.2.jar
            81,267 activemq-jmdns_1.0-5.3.0.jar
           116,081 activemq-optional-5.3.0.jar
            38,517 activemq-pool-5.3.0.jar
         6,905,784 activemq-rar-5.3.0.rar
           175,130 activemq-xmpp-5.3.0.jar
           118,726 commons-beanutils-1.6.1.jar
            30,085 commons-codec-1.2.jar
           575,389 commons-collections-3.2.1.jar
           121,757 commons-dbcp-1.2.2.jar
           305,001 commons-httpclient-3.1.jar
           197,067 commons-net-2.0.jar
            87,077 commons-pool-1.4.jar
            37,477 geronimo-j2ee-connector_1.5_spec-2.0.0.jar
            67,758 jettison-1.1.jar
           367,444 log4j-1.2.14.jar
           325,942 spring-aop-2.5.6.jar
           488,282 spring-beans-2.5.6.jar
           476,940 spring-context-2.5.6.jar
           285,491 spring-core-2.5.6.jar
           195,350 spring-jms-2.5.6.jar
            15,980 spring-oxm-tiger-1.5.8.jar
           231,173 spring-tx-2.5.6.jar
           474,413 wstx-asl-3.0.1.jar
           130,519 xbean-spring-3.6.jar
            24,544 xmlpull-1.1.3.4d_b4_min.jar
           431,406 xstream-1.3.1.jar
&lt;/pre&gt;&lt;/div&gt;In our case ActiveMQ RAR file name will be &lt;b&gt;activemq-rar-5.3.0.rar&lt;/b&gt;.&lt;br /&gt;
&lt;br /&gt;
Now go to JBoss intallation folder and create a folder for ActiveMQ inside &lt;i&gt;deploy &lt;/i&gt;directory for the required context. Here we are using &lt;i&gt;default &lt;/i&gt;JBoss context.&lt;br /&gt;
&lt;div style=&quot;background-color: black; color: white;&quot;&gt;&lt;pre&gt;C:\JBoss\jboss-6.0.0.M1\server\default\deploy&amp;gt;mkdir activemq-rar-5.3.0.rar
&lt;/pre&gt;&lt;/div&gt;Extract the contents of ActiveMQ RAR file(activemq-rar-5.3.0.rar) to this folder.&lt;br /&gt;
&lt;div style=&quot;background-color: black; color: white;&quot;&gt;&lt;pre&gt;102,631 activeio-core-3.1.2.jar
         2,923,854 activemq-core-5.3.0.jar
           147,717 activemq-protobuf-1.0.jar
            85,474 activemq-ra-5.3.0.jar
             4,467 aopalliance-1.0.jar
             1,868 broker-config.xml
            52,915 commons-logging-1.1.jar
            44,598 commons-logging-api-1.1.jar
           197,067 commons-net-2.0.jar
         2,141,382 derby-10.1.3.1.jar
            16,030 geronimo-j2ee-management_1.0_spec-1.0.jar
            20,220 geronimo-j2ee-management_1.1_spec-1.0.1.jar
           152,481 kahadb-5.3.0.jar
           367,444 log4j-1.2.14.jar
             1,625 log4j.properties
    &amp;lt;DIR&amp;gt;          META-INF
           488,282 spring-beans-2.5.6.jar
           476,940 spring-context-2.5.6.jar
           285,491 spring-core-2.5.6.jar
           130,519 xbean-spring-3.6.jar
&lt;/pre&gt;&lt;/div&gt;Now we can start configuring ActiveMQ.&lt;br /&gt;
&lt;br /&gt;
Edit &lt;i&gt;&lt;b&gt;ra.xml&lt;/b&gt;&lt;/i&gt; file inside &lt;i&gt;[JBOSS_HOME]\server\default\deploy\activemq-rar-5.3.0.rar\META-INF&lt;/i&gt; folder.&lt;br /&gt;
&lt;div style=&quot;background-color: #1211aa; color: white;&quot;&gt;&lt;pre&gt;&amp;lt;config-property&amp;gt;
   &amp;lt;description&amp;gt;
      The URL to the ActiveMQ server that you want this connection to 
      connect to. If using an embedded broker, this value should be                
      &#39;vm://localhost&#39;.
   &amp;lt;/description&amp;gt;
   &amp;lt;config-property-name&amp;gt;ServerUrl&amp;lt;/config-property-name&amp;gt;
   &amp;lt;config-property-type&amp;gt;java.lang.String&amp;lt;/config-property-type&amp;gt;
   &amp;lt;config-property-value&amp;gt;vm://localhost&amp;lt;/config-property-value&amp;gt;
&amp;lt;/config-property&amp;gt;
&amp;lt;config-property&amp;gt;
   &amp;lt;description&amp;gt;
     Sets the XML configuration file used to configure the embedded ActiveMQ broker via 
     Spring if using embedded mode. BrokerXmlConfig is the filename which is assumed 
     to be on the classpath unless a URL is specified. So a value of foo/bar.xml 
     would be assumed to be on the classpath whereas file:dir/file.xml would use the file system. 
     Any valid URL string is supported.              
    &amp;lt;/description&amp;gt;
    &amp;lt;config-property-name&amp;gt;BrokerXmlConfig&amp;lt;/config-property-name&amp;gt;
    &amp;lt;config-property-type&amp;gt;java.lang.String&amp;lt;/config-property-type&amp;gt;
    &amp;lt;config-property-value&amp;gt;xbean:broker-config.xml&amp;lt;/config-property-value&amp;gt;
&amp;lt;/config-property&amp;gt;
&lt;/pre&gt;&lt;/div&gt;A Pre-Configured &lt;a href=&quot;http://sites.google.com/site/snavp13/Home/ra.xml?attredirects=0&amp;amp;d=1&quot;&gt;ra.xml&lt;/a&gt; can be downladed.&lt;br /&gt;
&lt;br /&gt;
The &lt;b&gt;&lt;i&gt;broker-config.xml&lt;/i&gt;&lt;/b&gt; file inside&lt;i&gt; [JBOSS_HOME]\server\default\deploy\activemq-rar-5.3.0.rar&lt;/i&gt; is the ActiveMQ configuration file. This is the file used to configure ActiveMQ. The default contents of this file are usable, but should be customized to suit your environment.&lt;br /&gt;
&lt;br /&gt;
A Pre-Configured &lt;a href=&quot;http://sites.google.com/site/snavp13/Home/broker-config.xml?attredirects=0&amp;amp;d=1&quot;&gt;broker-config.xml&lt;/a&gt; can be downloaded.&lt;br /&gt;
&lt;br /&gt;
Now start JBoss server to ensure it start without any errors using the same commands we used before. If JBoss Server starts without any errors you can move to next step. Stop the server and continue to next step.&lt;br /&gt;
&lt;br /&gt;
Next step is to configure JBoss to initialize and start ActiveMQ whenever JBoss starts up. This is accomplished by putting an XML (&lt;i&gt;activemq-jms-ds.xml&lt;/i&gt;) inside &lt;i&gt;[JBOSS_HOME]\server\default\deploy&lt;/i&gt;.&lt;br /&gt;
&lt;br /&gt;
A Pre-Configured &lt;a href=&quot;http://sites.google.com/site/snavp13/Home/activemq-jms-ds.xml?attredirects=0&amp;amp;d=1&quot;&gt;activemq-jms-ds.xml&lt;/a&gt; can be downloaded.&lt;br /&gt;
&lt;br /&gt;
&amp;nbsp;Now start JBoss server to ensure it start without any errors using the same commands we used before.&amp;nbsp; Examine the startup messages for ActiveMQ messages.&lt;br /&gt;
&lt;div style=&quot;background-color: black; color: white;&quot;&gt;&lt;pre&gt;21:20:17,453 INFO  [RARDeployment] Required license terms exist, view vfszip:/C:
/JBoss/jboss-6.0.0.M1/server/default/deploy/mail-ra.rar/META-INF/ra.xml
21:20:17,515 INFO  [RARDeployment] Required license terms exist, view vfszip:/C:
/JBoss/jboss-6.0.0.M1/server/default/deploy/quartz-ra.rar/META-INF/ra.xml
21:20:17,968 INFO  [AdminObject] Bound admin object &#39;org.apache.activemq.command
.ActiveMQQueue&#39; at &#39;activemq/queue/outbound&#39;
21:20:17,984 INFO  [AdminObject] Bound admin object &#39;org.apache.activemq.command
.ActiveMQTopic&#39; at &#39;activemq/topic/inbound&#39;
21:20:18,171 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager
&#39;jboss.jca:service=ConnectionFactoryBinding,name=activemq/QueueConnectionFactory&#39;
to JNDI name &#39;java:activemq/QueueConnectionFactory&#39;
21:20:18,281 INFO  [ConnectionFactoryBindingService] Bound ConnectionManager
&#39;jboss.jca:service=ConnectionFactoryBinding,name=activemq/TopicConnectionFactory&#39; 
to JNDI name &#39;java:activemq/TopicConnectionFactory&#39;
&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
Now our environment is ready to go.</content><link rel='replies' type='application/atom+xml' href='http://javarebel.blogspot.com/feeds/7401292538550513663/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://javarebel.blogspot.com/2009/12/integrating-activemq-53-with-jboss-6.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/7401292538550513663'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/8553183304177435778/posts/default/7401292538550513663'/><link rel='alternate' type='text/html' href='http://javarebel.blogspot.com/2009/12/integrating-activemq-53-with-jboss-6.html' title='Integrating ActiveMQ 5.3.0 with JBoss 6.0.0'/><author><name>Naveen Sisupalan</name><uri>http://www.blogger.com/profile/16951209009574556509</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='24' height='32' src='//blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjPleT2cVoVUNJDXuvE5e8errhtAfZ4r3U1701nTKyaoQlSuDTWtb8_aHh3wa-QFchuf1xuYbV6Ef4U5wBcr3xpaYq4AQWXPxxd_MA2wZ7tag057M4B4bzMSYPAg5HTHg/s220/DSC01465.JPG'/></author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj_sTjO1TZTBolZ1NzhO0MSLvuyR8E1ZzQ-TUWmpBsLPzl55KqPJlU9m5gygyiqw_Mr5TJNPf5uQO6JaJFlIbZ1jBtriGb2eBf8rhwtAG-EoB5vwffefPdEvkALpSv9anqYf8EiCCOxzSI/s72-c/jboss-web-console.png" height="72" width="72"/><thr:total>2</thr:total></entry></feed>