Archive

Author Archive

Using Embedded JBoss to bulk deploy EJBs

July 12th, 2010 Shrihari No comments

This tip explores implementation of test cases for testing multiple EJB (stateless or stateful) in Embedded JBoss Container. Suppose if a test case is a client for multiple EJBs hosted in multiple jar files, this post will help you configure your test environment to deploy all the EJBs in the Embedded JBoss Container and run test cases against it.
The configuration is simple and is just three stepped process. Assume all the jars containing the EJBs are available as maven artifacts and the tests are deployed as a maven project, the following are sequence of steps:

1) In the project’s pom.xml, specify the maven-dependency-plugin under build/plugins as given below:


<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-ejbs</id>
<phase>process-test-resources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>my.package</groupId>
<artifactId>my.ejbmodule</artifactId>
<version>1.0.0</version>
<type>ejb</type>
</artifactItem>
<!-- Other EJB module artifacts -->
</artifactItems>
<outputDirectory>${project.build.testOutputDirectory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>

Here the plugin is copying the ejb modules to the target/test-classes/lib before test phase (during process-test-resources phase). If you a non-maven set of ejb module, one could use the maven-antrun-plugin to copy these jar files under target/test-classes/lib in process-test-resources phase.

2) Now since we are using Embedded JBoss as the container and we have the container configurations under src/test/resources, edit the src/test/resources/conf/bootstrap-beans.xml and append the following


<!-- My custom deployment -->
<bean name="ResourcesToDeploy4">
<property name="filter">
<inject bean="DeploymentFilter"/>
</property>
<property name="mainDeployer">
<inject bean="MainDeployer"/>
</property>
<property name="kernel">
<inject bean="jboss.kernel:service=Kernel"/>
</property>
<property name="directoriesByResource">
<list elementClass="java.lang.String">
<value>${jboss.embedded.bootstrap.resource.path}conf/jboss-service.xml/../lib</value>
</list>
</property>
</bean>

Here we are creating a deployment folder ../lib relative to conf/jboss-service.xml, where the ejb modules gets copied as explained in the previous step.

3)  Now in your test-case (implemented either JUnit/TestNG), implement a @BeforeClass annotated method to do the embedded jboss bootstrapping as given below

static MyEJB ejb1 = null;

@BeforeClass
public static void startup() {
Bootstrap bootstrap = Bootstrap.getInstance();
try {
if (!bootstrap.isStarted())
bootstrap.bootstrap();
} catch (DeploymentException deploy)
{}
InitialContext ctx = new InitialContext();
ejb1 =  (MyEJB)ctx.lookup("myejb");
}

All your other ejbs can as well looked upon like specified above.  During test runtime, you can check how embedded jboss is initializing and starting discovered EJB modules. This way one may not need to deployResource for every EJB defined.

Categories: jee-light Tags: , ,

Using Mockito’s Spy to mock hierarchical objects

July 6th, 2010 Shrihari No comments

Mocking in Mockito using mock() method is straight-forward for POJO(s) with no inheritance.  However for objects which are defined as part of class hierarchies, using mock() to alter parental behaviour cannot be implemented. Lets take an example of a base class such as Staff with derived classes: Employee and Contractor as given below:

public class Staff {
    protected String name;
    protected Integer age;
    protected String deptname;
    //other fields, setters and accessors.
}

The Employee/Contractor class look like this

public class Employee extends Staff {
   private String employeeID;
   private Date joinDate;
   //setters and accessors.
}

public class Contractor extends Staff {
    private String contractorID;
    private String fromCompany;
    private Long contractDuration'
    //setters and accessors.
}

Lets now mock Contractor object and stub the name (parental attribute) behaviour:

  Contractor contractor = mock(Contractor.class);
  when(contractor.getName()).thenReturn("John Smith");
  assertEquals(contractor.getName(), "John Smith");

Unfortunately the above code is not able to induce name behaviour using stubbing and assertEquals fails in the above code . Now Mockito provides spy() for creating pseudo mock on real objects. This indeed provides a breather to mock hierarchical objects as show below for the example we have

  Contractor contractor = new Contractor();
  contractor.setName("John Smith");
  Contractor mocked = spy(contractor);
  //other stubbing logic
  assertEquals(contractor.getName(), "John Smith");

This way we can alter functional behaviour for parental properties as well.

Categories: jee-light Tags:

Using Embedded JBoss for functional flow testing for EJB3

June 21st, 2010 Shrihari No comments

From the past few days, I have been trying to evaluate various mechanisms to acheive functional flow testing for a runtime EAR deployable. Under the assumption that the final deployment will be on JBOSS-AS-5.1.x, our goal is to chalk out a testing environment thats close to the actual deployed environment.

Various mechanisms for setting up the environment surfaced.

  • Deploying EAR using Maven-Cargo-Plugin (jboss51x) including options to start jboss (pre-integration-test) and stop jboss(post-integration-test) and perform integration tests.
  • Using Embedded JBOSS to start/stop the container pre/post test-case execution and deploy the EAR.
  • Using OpenEJB, an embeddable and lightweight EJB 3.0 Implementation container environment.
  • Using Arquillian(framework to perform integration test) and Shrinkwrap(framework to create JAR/WAR/EAR archive dynamically) APIs from JBOSS

In this edition of the write-up, I would like to focus on the preparing a deployable for Embedded JBOSS, for an example flow. Lets consider
a naive shopping cart example which would given a list of items (with valid item codes), would persist the cart details, generate an invoice
amount. Following are the stateless bean interface and implementation in EJB3 semantics:

package shoppingcart;
import javax.ejb.Local;

@Local
public interface ShoppingCart
{   public Double generateInvoice(List items,String coupon) throws InvalidCartException;
}

Assuming isCouponValid() and getDiscount()/addTax are functional stubs implemented appropriately, following is the bean code.

package shoppingcart;
import javax.ejb.Stateless;
import javax.jpa.PersistenceContext;

@Stateless
public class ShoppingCartBean implements ShoppingCart
{   @PersistenceContext EntityManager em;

public Double generateInvoice(List items,String coupon) throws InvalidCartException
{  if(items.size() <= 0)
throw new InvalidCartException("No items present in the shopping cart!");
if(isCouponValid(coupon))
throw new InvalidCartException("Shopping cart's Coupon Code is not valid!");
Double totalPrice = 0;
for(Item item:items)
{   totalPrice += (item.getQuantity()*item.getPrice()));
}
totalPrice -= getDiscount(coupon);
totalPrice += addTax(totalPrice);
return totalPrice;
}
}

Use the Maven configuration for Embedded JBoss, we could set up the necessary environment for implementing the test cases. Following are the additional changes:
1) If you have a datasource file, copy it under test/resources/deploy.
2) Copy persistence.xml under test/resources/META-INF.

Once done. here is the JUnit code to test the functional flow for shopping cart

package shoppingcarttest;

import org.jboss.bootstrap.spi.Bootstrap;
import org.jboss.deployers.spi.DeploymentException;
//other imports..

public class ShoppingCartTest
{  @BeforeClass
public static void startup() {
try {
if (!Bootstrap.getInstance().isStarted()) {
Bootstrap.getInstance().bootstrap();
}
deploy();
} catch (DeploymentException deploy) {
deploy.printStackTrace();
}
}

private static void deploy() {
Bootstrap bootstrap = Bootstrap.getInstance();
try
{    bootstrap.deployResourceBase(ShoppingCart.class);
bootstrap.deployResourceBases("META-INF/persistence.xml");
} catch (DeploymentException e)
{    throw new RuntimeException("Unable to deploy", e);
}
}

@Test
public void testShoppingCart()
{   InitialContext ctxt = new InitialContext();
ShoppingCart cart = (ShoppingCart)ctxt.lookup("ShoppingCartBean/local");
List items = new ArrayList(2);
items.add(new Item("Nokia E61",1));
items.add(new Item("Nokia E61 cable",1));
Double totalPrice = cart.generateInvoice(items, "XYZ123");
assertTrue(totalPrice > 0);
}

}

Using JBoss’s Bootstrap SPI, one can start the embedded container and deploy the EAR containing the enterprise-bean-under-test. We can also embrace TDD/BDD approach using mocks, er. Mockito

Understanding Exception Handling on Mock objects

June 6th, 2010 Shrihari No comments

Mockito is the recommended and used mocking testing framework which provides varied function points to mock and verify interactions. It provides a parallel support to TestNG or JUnit for faster Test Driven Development (TDD) adoption in newer teams. In this edition of the write-up I would explore the concept of mocking with exception handling.

Lets consider a user credential validation login, before user getting authenticated into the system. If the credential validation fails, the system is expected to throw an application exception. However if it passes, the actual authentication to the system should
happen. With the familiarity with TestNG and Mockito, lets look the test case code

@Test(expectedException=UserValidationException.class)
public void testCredentialsValidation()
{  //create a mock to return false for validation - to fail login
UserCredentials credentials = mock(UserCredentials.class);
when(credentials.validate(anyString(),anyString())).thenReturn(false);

//Call the login service to gain entry
LoginService service = new LoginService(credentials);
service.loginuser("sample","sampl3");
}

Please note here that UserCredentials is only being mocked here, not the LoginService. The reason is to run the induced behaviour of the mocked UserCredentials on the actual LoginService functionality. A mocked object will behaviour only according to what has been induced.

Having looked at the test code, lets look at the actual logic implementation

public interface UserCredentials
{  public boolean validate(String username,String passwordtext);
}
public class LoginService
{  private UserCredentials credentials;

public LoginService(UserCredentials credentials)
{ this.credentials = credentials;
}

public void loginuser(String user, String passwd) throws UserValidationException
{   if(!credentials.validate(user,passwd))
throw new UserValidationException("Username or password invalid..");
//actual authentication process...
}
}
public UserValidationException extends RuntimeException
{  private String message;

public UserValidationException(String msg)
{   message = msg;
}
}

UserValidationException extends RuntimeException for brevity purposes, so that the test code signature is not affected. There is another methodology whereby we could induce behaviour of throwing an exception on the mocked object, even though the actual need not throw any exception.

doThrow(new UserValidation()).when(loginservice).loginuser(anyString(),anyString());

Unfortunately this is at the method level and not at the individual statement level. Am looking at options on mocking exceptions at the method  statement level for the mocked objects. Any thoughts!

Categories: jee-light Tags: ,

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

Tip: Listing and Compressing modified files on SVN since latest update on Linux

November 26th, 2009 Shrihari No comments

In order to find or look at the list of all the modified files on SVN (since the last update) on any Linux host, you may use the following command (say we need to find java or xhtml files)


svn status -u | grep -e '.java' -e '.xhtml' | awk '{if($2 ~/^[0-9]+$/) {print $3} else {print $2}}'

This command would also print the unversioned (not added to SVN) files as well. Now if you want to compress these list of files (using tar), issue the following shell command:


svn status -u | grep -e '.java' -e '.xhtml' | awk '{if($2 ~/^[0-9]+$/) {print $3} else {print $2}}' | xargs tar cvfz modifiedfiles.tar.z
Categories: Uncategorized Tags: ,