Archive

Archive for the ‘jee-light’ Category

CDI Power Constructs for JEE-6: @Inject, @Qualifier, @Produces, @Disposes and @Named

February 8th, 2010 Shrihari No comments

In pre-JEE 5 era, tiered architectures boasted of having loosely coupled layers and a predefined flows for the request-response were outlined, designed, implemented and tested. Core JEE patterns evolved which defined breadths of request processing and response throwbacks, for variety of scenarios.
A thick layered architecture would have a view controlled by controller command, which invoked a facade and chain of command passed on to DAO or EntityBean which manipulated the model. Various configuration idiosyncrasies had to be carefully set and presented in the final deployment.

Enter JEE 6 – the era of configuration free, and annotation driven wiring of components. The JSR-299 (Contexts and Dependency Injection for Java) improvises over JSR-330 (Dependency Injection for Java) and brings the power of Inversion of Controller to enterprise container. Five annotation constructs : @Inject, @Qualifier, @Produces, @Disposes and @Named provide the basic building blocks for getting a thin loosely coupled layered modular structure to the view, hiding the boilerplate code one had to write before JEE 6. Lets briefly look at these annotations and how do they fit in with regard to a shopping cart example:

@Qualifier
We use @Qualifier for defining different bean types. In JEE 6 context, @Qualifier is used to define independent functional flows. In case of shopping cart example, it could denote the shopping cart access manager as shown below:

@Qualifier
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ShoppingCart {}

@Produces
The annotation @Produces is used to instantiate a bean type, specifically on an . If a bean type is a qualified (i.e.) annotated with @Qualifier, the @Produces with be followed by the custom qualifier interface. In the shopping cart example above, if we need to define a factory method to return a manager instance to be available under a managed bean, we could defines as below:

public @Produces @ShoppingCart ShoppingCartManager getShoppingCart() {
      return new ShoppingCartManagerImpl();
 }

where ShoppingCartManager defines methods to query and add items to the cart as below:

public abstract class ShoppingCartManager{
    @PersistenceContext EntityManager em;

     public abstract List<Items> getAllItems();
     public abstract void addItem(Item item);
     ...
 }

@Disposes
A @Dispose annotation is used in exact opposite semantics of @Produces. If you want release some held resources by the manager, or destroy the session specific shopping cart in this example, you could use it on the method.

public void clearShoppingItem(@Disposes @ShoppingCart ShoppingCartManager cart) {
      cart.clearItems();
      cart = null;
 }

@Inject
@Inject provides the ability to define the dependency injection at the point of usage, qualified or unqualified. If a bean type has been qualified, the appropriate Qualifier is as well used.

@Inject @ShoppingCart ShoppingCartManager manager;

@Named
@Named annotation helps the component to be used in the presentation or view layer using EL, supported by Camelcase variable naming convention. So in the shopping cart example, using #{items} would query the accessor method to retreive the shopping cart items

@Inject @ShoppingCart ShoppingCartManager manager;

@Named
public List<Item> getItems() {
      return manager.getAllItems();
 }

Using these constructs, one can implement complex workflows, without configuration hassles, and maintaining high cohesion and loose coupling.

Categories: jee-light Tags: ,

Controlling Thread Execution using CyclicBarriers in Java

February 3rd, 2010 Shrihari No comments

Barriers are threading concepts which define checkpoints within the thread-execution semantics which aid in controlling a group of threads to proceed after all threads in the group has arrived at that checkpoint.  Java’s java.util.concurrent package defines a CyclicBarrier class which is aptly used for such as scenario. It is prefixed with cyclic to denote that we can reuse it any number of times in case of repeatable checkpoints.

We will see how this specific class could be used for the two different scenarios.

1)Single post-barrier action thread.
Single Post Barrier Action
In this scenario you could create a CyclicBarrier with number of threads and a reference to action thread so that it gets invoked post-barrier. Lets look at an example for deriving an average throughput time taken for compute intensive modules whose start and end times are captured. So the example fits the barrier scenario where by the pre-barrier thread computes the difference between the start and end time and post-barrier action thread computes the average out of the accumulated differences.

public class SingleActionPostBarrier
{ private int numberOfThreads = 1;
  private int responseTimes[];

  public SingleActionPostBarrier(int threadCount)
  {  numberOfThreads = threadCount;
     responseTimes = new int[threadCount];
  }

  public void doRun()
  { CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, new ComputeAverage());
    ExecutorService execservice = Executors.newFixedThreadPool(numberOfThreads);
    for (int i = 0; i < numberOfThreads; i++)
    {   execservice.execute(new Runnable()
        {   public void run()
            {  long start = System.currentTimeMillis();
               //invoke the process centric action method..
               long end = System.currentTimeMillis();
               responseTimes[i] = (end-start)/1000;

               try
               { barrier.await();
               }catch(BarrierBrokenException bbe)
	       {
	       }catch(InterruptedException inex)
	       {}
	     }
         }
     }//end of for-loop
  }

  class ComputeAverage implements Runnable
  {    public void run()
       { int sum = 0;
         for(int diff:responseTimes)
         {  sum += diff;
         }
         if (sum!=0) System.out.println("Average Response Time :"+(sum/responseTimes.length));
       }
  }
}

2) Multiple post-barrier action thread.
Multiple Post Barrier Action
From the previous example, lets tweak it and say we need to repeat the same profile computation but for a different action workflow and capture in another responseTimes array. The end result is compute the difference in profile times for these actions for multi threaded behavior and deduce a sorted list. The following snippet would explain it

public class MultiActionPostBarrier
{ private int numberOfThreads = 1;
  private int responseTimes[];
  private int responseTimesForAnotherAction[];

  public SingleActionPostBarrier(int threadCount)
  {  numberOfThreads = threadCount;
     responseTimes = new int[threadCount];
     responseTimesForAnotherAction = new int[threadCount];
  }

  public void doRun()
  { CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, new SortDiffResponse());
    ExecutorService execservice = Executors.newFixedThreadPool(numberOfThreads);
    for (int i = 0; i < numberOfThreads; i++)
    {   execservice.execute(new Runnable()
        {   public void run()
            {  long start = System.currentTimeMillis();
               //invoke the process centric action method..
               long end = System.currentTimeMillis();
               responseTimes[i] = (end-start)/1000;

               try
               { barrier.await();
               }catch(BarrierBrokenException bbe)
	       {
	       }catch(InterruptedException inex)
	       {}

               start = System.currentTimeMillis();
               //invoke the process centric action method..
               end = System.currentTimeMillis();
               responseTimesForAnotherAction[i] = (end-start)/1000;

		// compute the difference
	       responseTimes[i] = responseTimes[i] - responseTimesForAnotherAction[i];
               try
               { barrier.await();
               }catch(BarrierBrokenException bbe)
	       {
	       }catch(InterruptedException inex)
	       {}
	     }
         }
     }//end of for-loop
  }

  class SortDiffResponse implements Runnable
  {    public void run()
       { Arrays.sort(responseTimes);
         for(int diff:responseTimes)
         {  System.out.println(responseTimes[i]);
         }
       }
  }
}

Using CyclicBarriers one could reuse the barrier checkpoint for complex thread behaviors. Please refer to dzone article for an interesting read on the same,.

Categories: jee-light Tags:

Wooah! Back after two months

February 2nd, 2010 Shrihari No comments

Took a break from technical blogging! Am back and will make it my habit to blog regularly ! Keep visiting and learning! And drop your most valuable and priceless comments!

Categories: jee-light Tags:

Managing Teams – Brake/Accelerator Pedal Way

January 20th, 2010 Shrihari No comments

“You have not sticked to your timeliness! you have been silent in the customer interaction calls!”, recalling the interaction with the manager, a team member says with disgust, “Aaargh! the team sucks! the manager sucks! I have no future in this team!”. This can be overheard from members of most prestigious current day delivery project teams in any organization after an appraisal or inter personal review meetings. Quite evidently both the manager and team member seem to be dissatisfied with the outcome of the meeting.

To some extent, the onus of how team member chose to what he/she has done till date, in the team, is very much with the manager. Most managers view the performance of their team members as cars with automated gears and controls on a highway called project delivery. But the reality is that members of team are most like cars with manual gears and control systems. Controlling and calibrating each component of a control system increases the efficiency of a car. Likewise each team member has to be nurtured, identifying the capacity factor each of these control systems, so that the outcome of such soul stirring meetings are not grumbles and mumbles, but praise and respect for each other.

Its everybody guess that car have a foot brake and accelerator with varying dimensions. In fact the surface area of a foot brake is more than that of an accelerator. In a way a car’s foot brake symbolizes the negative tenets of your team member and the accelerator, the positive qualities denoting the freedom to achieve something great. Most project manager falter in identifying which are brakes and accelerators, going on by bigger and visible surface area as that of an accelerator. They try pedaling the brake, thinking they are pressing the accelerator and can better control the team member and ignore on the actuals, he/she is capable of. The more they press the brake, the more the negative energies and currents flow, and the more the friction develops. At the end of the game, everybody is dissatisfied and frustrated.

Identifying an accelerator is little tedious and time-consuming, during which the manager has to engage the member to think and contribute freely. The better option is to make him/her a stakeholder in the delivery either through incentives or giveaways. The other complimenting options would be to monitor him/her closely as a friend which counts to delivery.

Categories: jee-light Tags:

How to open a new window from JSF commandLink tag?

December 2nd, 2009 Shrihari 2 comments

Some of the JSF reference implementations (including jsf-html) do not provide commandLink option with a target attribute, which we could use as in <a href=”myurl” target=”_blank”/>. This quick tip would explore 2 ways to do that

1) If there in only single commandLink in the form, you could specify it the enclosing form level as given below:

<h:form id="form1" target="blank">
...
<h:commandLink action="#{mybean.myaction}" id="link" value="Click here to open new window">
</h:commandLink>
...
</h:form>

2) If there are multiple commandLink tags in the enclosing form, you could use onclick attribute to navigate in a new page:

<h:form id="form2">
...
<h:commandLink action="#{mybean.myaction1}" id="link1" value="Click here to open new window1" onclick="javascript:window.open('#{request.contextPath}/myview.1jsf');">
</h:commandLink>
....
<h:commandLink action="#{mybean.myaction2}" id="link2" value="Click here to open new window2" onclick="javascript:window.open('#{request.contextPath}/myview2.jsf');">
</h:commandLink>
...
</h:form>
Categories: jee-light Tags: ,

Formatting messages on JSF page in JBoss Seam

November 18th, 2009 Shrihari No comments

In many scenarios we may need to format messages on the JSF page using JBoss Seam without calling a backing bean method, One typical example could be displaying a welcome message when the user logs in to the application. This tip explores a component called Interpolator in Seam which helps us the solution.

Lets assume we have defined a message property as welcome.message as below

#different message properties
...
welcome.message= Welcome! Dear #0
...

In the homepage.xhtml (jsf page), we come populate the greeting message with, say the logged in username, using interpolator as below:

   ....
   <h:outputText value="#{interpolator.interpolate(messages['welcome.message'],identity.username)}"/>
....
Categories: jee-light Tags:

How to end JBoss Seam conversation in menu links?

November 17th, 2009 Shrihari No comments

Not all the times, we may be interested in using JBoss Seam’s link tag s:link to end conversation scope propagation. This holds good specifically for menu links and random hotkey navigations. One quick tip could be to specify the redirection url link with the parameter conversationPropagation=end.

Categories: jee-light Tags:

How to change authentication success/failure message in JBoss Seam?

November 16th, 2009 Shrihari No comments

If we rely on JBoss Seam’s Security Identity Management for user authentication on a web application, we certainly think of changing the default ‘Welcome <username>’ to something different and catchy. This particular tip explores such a possibility successfully in 2-3 steps:

1)  Assuming that you have defined the security identity and core resource loader components have been defined in WEB-INF/components.xml as below, we have to modify the properties myapplication_en.properties (_en is the default locale)

<security:identity authenticate-method="#{authenticator.authenticate}" remember-me="true"/>
<core:resource-loader bundle-names="myapplication"/>

define your custom message like this, where #0 is a parameter placeholder.

welcome.message=Good to see you, #0
loginfailed.message=Unable to login mate, please check your credentials!

2) Modify your authenticator component to add custom message if login/authentication is successful.

public boolean authenticate()
{  User loggedInUser = authenticationservice.autheticate(credentials.getUsername(), credentials.getPassword());
   FacesMessages messages = FacesMessages.instance();
    if(loggedInUser==null)
    {    messages.addFromResourceBundle("loginfailed.message", null);
         return false;
    }
    messages.addFromResourceBundle("welcome.message", loggedInUser.getFullname());
    return true;
}

Are we done? wait… We need to reset the earlier messages (the default ones)

3) Add two more entries to myapplication_en.properties and set these properties as blank. This would reset the existing default ones.

org.jboss.seam.loginSuccessful=
org.jboss.seam.loginFailed=

Aint it easy and cool!

Categories: jee-light Tags:

Integrating Hibernate Search on PrimeFaces using Google Guice and JBoss Seam

November 14th, 2009 Shrihari No comments

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

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

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

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

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

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

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

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

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

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

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

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

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

Context specific Outjection modes in JBoss Seam

November 13th, 2009 Shrihari No comments

There are 7 types of contexts available in JBoss Seam. In order to outject (make an instantiated/ populated object available to other components participating in the same context) for a particular scope, say CONVERSATION, there are at least 2 ways of outjecting an instance as follows:

1) Declaratively : This could be used when there are component boundaries clearly demarcated and the instance needs to available for a longer running conversation. An example snippet is given below:

@Name("producer")
public class Producer
{   @Out(scope=ScopeType.CONVERSATION)
      private QueueFeed feed;

      //methods to produce and populate the feed
      @Begin public void doStart(){}
      @End public void close(){}
}
@Name("consumer")
public class Consumer
{   @In  private QueueFeed feed;
       //methods to consume and cleanup the feed
}

2) Programmaticaly : This approach is used when one would want place the instance in the already established context, and other seam components just reference the instance and used as given below:

@Name("producer")
public class Producer
{   public void produceIntermediate()
    {   QueueFeed queueFeed;
         //populate queueFeed
        Contexts.getConversationContext().set("queueFeed", queueFeed);
     }
}
@Name("consumer")
public class Consumer
{  public void consumeIntermediate()
    {   QueueFeed queueFeed = (QueueFeed) ( Contexts.getConversationContext().get("queueFeed",));
     }
}

This way one can manage scopes effectively with regard to instance usage across participating components

Categories: jee-light Tags: