<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Technotrance, Illusions and Perspectives &#187; jee-light</title>
	<atom:link href="http://myblog.shriharisc.com/category/jee-light/feed/" rel="self" type="application/rss+xml" />
	<link>http://myblog.shriharisc.com</link>
	<description>A dose of everyday bruises with Java/JEE</description>
	<lastBuildDate>Mon, 12 Jul 2010 17:55:59 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Using Embedded JBoss to bulk deploy EJBs</title>
		<link>http://myblog.shriharisc.com/2010/07/12/using-embedded-jboss-to-bulk-deploy-ejbs/</link>
		<comments>http://myblog.shriharisc.com/2010/07/12/using-embedded-jboss-to-bulk-deploy-ejbs/#comments</comments>
		<pubDate>Mon, 12 Jul 2010 17:55:59 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>
		<category><![CDATA[ejb]]></category>
		<category><![CDATA[embedded-jboss]]></category>
		<category><![CDATA[maven]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=293</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.<br />
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:</p>
<p>1) In the project&#8217;s pom.xml, specify the maven-dependency-plugin under build/plugins as given below:</p>
<pre class="brush: xml">

&lt;plugin&gt;
&lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
&lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt;
&lt;executions&gt;
&lt;execution&gt;
&lt;id&gt;copy-ejbs&lt;/id&gt;
&lt;phase&gt;process-test-resources&lt;/phase&gt;
&lt;goals&gt;
&lt;goal&gt;copy&lt;/goal&gt;
&lt;/goals&gt;
&lt;configuration&gt;
&lt;artifactItems&gt;
&lt;artifactItem&gt;
&lt;groupId&gt;my.package&lt;/groupId&gt;
&lt;artifactId&gt;my.ejbmodule&lt;/artifactId&gt;
&lt;version&gt;1.0.0&lt;/version&gt;
&lt;type&gt;ejb&lt;/type&gt;
&lt;/artifactItem&gt;
&lt;!-- Other EJB module artifacts --&gt;
&lt;/artifactItems&gt;
&lt;outputDirectory&gt;${project.build.testOutputDirectory}/lib&lt;/outputDirectory&gt;
&lt;/configuration&gt;
&lt;/execution&gt;
&lt;/executions&gt;
&lt;/plugin&gt;
</pre>
<p>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.</p>
<p>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</p>
<pre class="brush: xml">

&lt;!-- My custom deployment --&gt;
&lt;bean name=&quot;ResourcesToDeploy4&quot;&gt;
&lt;property name=&quot;filter&quot;&gt;
&lt;inject bean=&quot;DeploymentFilter&quot;/&gt;
&lt;/property&gt;
&lt;property name=&quot;mainDeployer&quot;&gt;
&lt;inject bean=&quot;MainDeployer&quot;/&gt;
&lt;/property&gt;
&lt;property name=&quot;kernel&quot;&gt;
&lt;inject bean=&quot;jboss.kernel:service=Kernel&quot;/&gt;
&lt;/property&gt;
&lt;property name=&quot;directoriesByResource&quot;&gt;
&lt;list elementClass=&quot;java.lang.String&quot;&gt;
&lt;value&gt;${jboss.embedded.bootstrap.resource.path}conf/jboss-service.xml/../lib&lt;/value&gt;
&lt;/list&gt;
&lt;/property&gt;
&lt;/bean&gt;
</pre>
<p>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.</p>
<p>3)  Now in your test-case (implemented either JUnit/TestNG), implement a @BeforeClass annotated method to do the embedded jboss bootstrapping as given below</p>
<pre class="brush: java">
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(&quot;myejb&quot;);
}
</pre>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2010/07/12/using-embedded-jboss-to-bulk-deploy-ejbs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Mockito&#8217;s Spy to mock hierarchical objects</title>
		<link>http://myblog.shriharisc.com/2010/07/06/using-mockitos-spy-to-mock-hierarchical-objects/</link>
		<comments>http://myblog.shriharisc.com/2010/07/06/using-mockitos-spy-to-mock-hierarchical-objects/#comments</comments>
		<pubDate>Tue, 06 Jul 2010 16:26:54 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>
		<category><![CDATA[mockito]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=287</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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:</p>
<pre class="brush: java">
public class Staff {
    protected String name;
    protected Integer age;
    protected String deptname;
    //other fields, setters and accessors.
}
</pre>
<p>The Employee/Contractor class look like this</p>
<pre class="brush: java">
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&#039;
    //setters and accessors.
}
</pre>
<p>Lets now mock Contractor object and stub the name (parental attribute) behaviour:</p>
<pre class="brush: java">
  Contractor contractor = mock(Contractor.class);
  when(contractor.getName()).thenReturn(&quot;John Smith&quot;);
  assertEquals(contractor.getName(), &quot;John Smith&quot;);
</pre>
<p>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</p>
<pre class="brush: java">
  Contractor contractor = new Contractor();
  contractor.setName(&quot;John Smith&quot;);
  Contractor mocked = spy(contractor);
  //other stubbing logic
  assertEquals(contractor.getName(), &quot;John Smith&quot;);
</pre>
<p>This way we can alter functional behaviour for parental properties as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2010/07/06/using-mockitos-spy-to-mock-hierarchical-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Embedded JBoss for functional flow testing for EJB3</title>
		<link>http://myblog.shriharisc.com/2010/06/21/using-embedded-jboss-for-functional-flow-testing-for-ejb3/</link>
		<comments>http://myblog.shriharisc.com/2010/06/21/using-embedded-jboss-for-functional-flow-testing-for-ejb3/#comments</comments>
		<pubDate>Mon, 21 Jun 2010 17:16:22 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>
		<category><![CDATA[embedded-jboss]]></category>
		<category><![CDATA[integration-test]]></category>
		<category><![CDATA[junit]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=268</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>Various mechanisms for setting up the environment surfaced.</p>
<ul>
<li>Deploying EAR using <a href="http://cargo.codehaus.org/JBoss+5.1.x">Maven-Cargo-Plugi</a>n (jboss51x) including options to start jboss (pre-integration-test) and stop jboss(post-integration-test) and perform integration tests.</li>
<li>Using Embedded JBOSS to start/stop the container pre/post test-case execution and deploy the EAR.</li>
<li> Using <a href="http://nickermansays.blogspot.com/2009/07/openejb-31-jboss-embedded-and-ejb-30.html">OpenEJB</a>, an embeddable and lightweight EJB 3.0 Implementation container environment.</li>
<li> Using <a href="http://community.jboss.org/docs/DOC-14376">Arquillian</a>(framework to perform integration test) and <a href="http://www.jboss.org/shrinkwrap">Shrinkwrap</a>(framework to create JAR/WAR/EAR archive dynamically) APIs from JBOSS</li>
</ul>
<p>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<br />
a naive shopping cart example which would given a list of items (with valid item codes), would persist the cart details, generate an invoice<br />
amount. Following are the stateless bean interface and implementation in EJB3 semantics:</p>
<pre class="brush: java">
package shoppingcart;
import javax.ejb.Local;

@Local
public interface ShoppingCart
{   public Double generateInvoice(List items,String coupon) throws InvalidCartException;
}
</pre>
<p>Assuming isCouponValid() and getDiscount()/addTax are functional stubs implemented appropriately, following is the bean code.</p>
<pre class="brush: java">
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() &lt;= 0)
throw new InvalidCartException(&quot;No items present in the shopping cart!&quot;);
if(isCouponValid(coupon))
throw new InvalidCartException(&quot;Shopping cart&#039;s Coupon Code is not valid!&quot;);
Double totalPrice = 0;
for(Item item:items)
{   totalPrice += (item.getQuantity()*item.getPrice()));
}
totalPrice -= getDiscount(coupon);
totalPrice += addTax(totalPrice);
return totalPrice;
}
}
</pre>
<p>Use the <a href="http://ptruax.wordpress.com/2008/05/29/jboss-embedded-and-maven/">Maven configuration for Embedded JBoss</a>, we could set up the necessary environment for implementing the test cases. Following are the additional changes:<br />
1) If you have a datasource file, copy it under test/resources/deploy.<br />
2) Copy persistence.xml under test/resources/META-INF.</p>
<p>Once done. here is the JUnit code to test the functional flow for shopping cart</p>
<pre class="brush: java">
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(&quot;META-INF/persistence.xml&quot;);
} catch (DeploymentException e)
{    throw new RuntimeException(&quot;Unable to deploy&quot;, e);
}
}

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

}
</pre>
<p>Using JBoss&#8217;s <a href="http://community.jboss.org/wiki/JBossBootstrap">Bootstrap</a> 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. <a href="http://mockito.org">Mockito</a></p>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2010/06/21/using-embedded-jboss-for-functional-flow-testing-for-ejb3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Understanding Exception Handling on Mock objects</title>
		<link>http://myblog.shriharisc.com/2010/06/06/understanding-exception-handling-on-mock-objects/</link>
		<comments>http://myblog.shriharisc.com/2010/06/06/understanding-exception-handling-on-mock-objects/#comments</comments>
		<pubDate>Sun, 06 Jun 2010 15:40:46 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>
		<category><![CDATA[mockito]]></category>
		<category><![CDATA[testng]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=258</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://mockito.org/" target="_blank"><strong>Mockito</strong></a> is the recommended and used mocking testing framework which provides varied function points to mock and verify interactions. It provides a parallel support to<a href="http://testng.org" target="_blank"><strong> TestNG</strong></a> or <strong><a href="http://junit.org" target="_blank">JUnit</a></strong> 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.</p>
<p>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<br />
happen. With the familiarity with TestNG and Mockito, lets look the test case code</p>
<pre class="brush: java">
@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(&quot;sample&quot;,&quot;sampl3&quot;);
}
</pre>
<p>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.</p>
<p>Having looked at the test code, lets look at the actual logic implementation</p>
<pre class="brush: java">
public interface UserCredentials
{  public boolean validate(String username,String passwordtext);
}
</pre>
<pre class="brush: java">
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(&quot;Username or password invalid..&quot;);
//actual authentication process...
}
}
</pre>
<pre class="brush: java">
public UserValidationException extends RuntimeException
{  private String message;

public UserValidationException(String msg)
{   message = msg;
}
}
</pre>
<p>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.</p>
<pre class="brush: java">
doThrow(new UserValidation()).when(loginservice).loginuser(anyString(),anyString());
</pre>
<p>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!</p>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2010/06/06/understanding-exception-handling-on-mock-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CDI Power Constructs for JEE-6: @Inject, @Qualifier, @Produces, @Disposes and @Named</title>
		<link>http://myblog.shriharisc.com/2010/02/08/cdi-power-constructs-for-jee-6-inject-qualifier-produces-disposes-and-named/</link>
		<comments>http://myblog.shriharisc.com/2010/02/08/cdi-power-constructs-for-jee-6-inject-qualifier-produces-disposes-and-named/#comments</comments>
		<pubDate>Mon, 08 Feb 2010 17:56:56 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>
		<category><![CDATA[cdi]]></category>
		<category><![CDATA[jee6]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=253</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.<br />
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.</p>
<p>Enter JEE 6 &#8211; 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:</p>
<p><strong>@Qualifier</strong><br />
   We use <a href="http://docs.sun.com/app/docs/doc/820-7627/gjbck?a=view">@Qualifier</a> 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:</p>
<pre class="brush: java">
@Qualifier
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface ShoppingCart {}
</pre>
<p><strong>@Produces</strong><br />
 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:</p>
<pre class="brush: java">
public @Produces @ShoppingCart ShoppingCartManager getShoppingCart() {
      return new ShoppingCartManagerImpl();
 }
</pre>
<p>where ShoppingCartManager defines methods  to query and add items to the cart as below:</p>
<pre class="brush: java">
public abstract class ShoppingCartManager{
    @PersistenceContext EntityManager em;

     public abstract List&lt;Items&gt; getAllItems();
     public abstract void addItem(Item item);
     ...
 }
</pre>
<p><strong>@Disposes</strong><br />
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.</p>
<pre class="brush: java">
public void clearShoppingItem(@Disposes @ShoppingCart ShoppingCartManager cart) {
      cart.clearItems();
      cart = null;
 }
</pre>
<p><strong>@Inject</strong><br />
    @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.</p>
<pre class="brush: java">
@Inject @ShoppingCart ShoppingCartManager manager;
</pre>
<p><strong>@Named</strong><br />
 <a href="http://java.sun.com/javaee/6/docs/api/javax/inject/Named.html">@Named</a> 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</p>
<pre class="brush: java">
@Inject @ShoppingCart ShoppingCartManager manager;

@Named
public List&lt;Item&gt; getItems() {
      return manager.getAllItems();
 }
</pre>
<p>Using these constructs, one can implement complex workflows, without configuration hassles, and maintaining high cohesion and loose coupling.</p>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2010/02/08/cdi-power-constructs-for-jee-6-inject-qualifier-produces-disposes-and-named/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Controlling Thread Execution using CyclicBarriers in Java</title>
		<link>http://myblog.shriharisc.com/2010/02/03/controlling-thread-execution-using-cyclicbarriers-in-java/</link>
		<comments>http://myblog.shriharisc.com/2010/02/03/controlling-thread-execution-using-cyclicbarriers-in-java/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 18:39:34 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=236</guid>
		<description><![CDATA[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&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://en.wikipedia.org/wiki/Barrier_%28computer_science%29">Barriers</a> 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&#8217;s java.util.concurrent package defines a <a href="http://java.sun.com/j2se/1.5.0/docs/api/index.html?java/util/concurrent/CyclicBarrier.html">CyclicBarrier</a> 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.</p>
<p>We will see how this specific class could be used for the two different scenarios.</p>
<p>1)<b>Single post-barrier action thread. </b><br />
<img src="http://myblog.shriharisc.com/wp-content/uploads/2010/02/single-thread-exit.jpg" alt="Single Post Barrier Action" /><br />
    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.</p>
<pre class="brush: java">
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 &lt; 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(&quot;Average Response Time :&quot;+(sum/responseTimes.length));
       }
  }
}
</pre>
<p>2) <b>Multiple post-barrier action thread.</b><br />
<img src="http://myblog.shriharisc.com/wp-content/uploads/2010/02/multi-thread-exit.jpg" alt="Multiple Post Barrier Action" /><br />
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</p>
<pre class="brush: java">
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 &lt; 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]);
         }
       }
  }
}
</pre>
<p>Using CyclicBarriers one could reuse the barrier checkpoint for complex thread behaviors. Please refer to <a href="http://java.dzone.com/news/coordinating-threads">dzone article</a> for an interesting read on the same,.</p>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2010/02/03/controlling-thread-execution-using-cyclicbarriers-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wooah! Back after two months</title>
		<link>http://myblog.shriharisc.com/2010/02/02/wooah-back-after-two-months/</link>
		<comments>http://myblog.shriharisc.com/2010/02/02/wooah-back-after-two-months/#comments</comments>
		<pubDate>Tue, 02 Feb 2010 16:30:02 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=234</guid>
		<description><![CDATA[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!
]]></description>
			<content:encoded><![CDATA[<p>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!</p>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2010/02/02/wooah-back-after-two-months/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Managing Teams &#8211; Brake/Accelerator Pedal Way</title>
		<link>http://myblog.shriharisc.com/2010/01/20/managing-teams-brakeaccelerator-pedal-way/</link>
		<comments>http://myblog.shriharisc.com/2010/01/20/managing-teams-brakeaccelerator-pedal-way/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 09:21:14 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>
		<category><![CDATA[team-management]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=227</guid>
		<description><![CDATA[&#8220;You have not sticked to your timeliness! you have been silent in the customer interaction calls!&#8221;, recalling the interaction with the manager, a team member says with disgust, &#8220;Aaargh! the team sucks! the manager sucks! I have no future in this team!&#8221;. This can be overheard from members of most prestigious current day delivery project [...]]]></description>
			<content:encoded><![CDATA[<p>&#8220;You have not sticked to your timeliness! you have been silent in the customer interaction calls!&#8221;, recalling the interaction with the manager, a team member says with disgust, &#8220;Aaargh! the team sucks! the manager sucks! I have no future in this team!&#8221;. 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.</p>
<p>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.</p>
<p>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&#8217;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.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2010/01/20/managing-teams-brakeaccelerator-pedal-way/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to open a new window from JSF commandLink tag?</title>
		<link>http://myblog.shriharisc.com/2009/12/02/how-to-open-a-new-window-from-jsf-commandlink-tag/</link>
		<comments>http://myblog.shriharisc.com/2009/12/02/how-to-open-a-new-window-from-jsf-commandlink-tag/#comments</comments>
		<pubDate>Wed, 02 Dec 2009 18:06:41 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jsf]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=223</guid>
		<description><![CDATA[Some of the JSF reference implementations (including jsf-html) do not provide commandLink option with a target attribute, which we could use as in &#60;a href=&#8221;myurl&#8221; target=&#8221;_blank&#8221;/&#62;. 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 [...]]]></description>
			<content:encoded><![CDATA[<p>Some of the JSF reference implementations (including jsf-html) do not provide commandLink option with a target attribute, which we could use as in &lt;a href=&#8221;myurl&#8221; target=&#8221;_blank&#8221;/&gt;. This quick tip would explore 2 ways to do that</p>
<p>1) If there in only single commandLink in the form, you could specify it the enclosing form level as given below:</p>
<pre class="brush: xml">
&lt;h:form id=&quot;form1&quot; target=&quot;blank&quot;&gt;
...
&lt;h:commandLink action=&quot;#{mybean.myaction}&quot; id=&quot;link&quot; value=&quot;Click here to open new window&quot;&gt;
&lt;/h:commandLink&gt;
...
&lt;/h:form&gt;
</pre>
<p>2) If there are multiple commandLink tags in the enclosing form, you could use onclick attribute to navigate in a new page:</p>
<pre class="brush: xml">
&lt;h:form id=&quot;form2&quot;&gt;
...
&lt;h:commandLink action=&quot;#{mybean.myaction1}&quot; id=&quot;link1&quot; value=&quot;Click here to open new window1&quot; onclick=&quot;javascript:window.open(&#039;#{request.contextPath}/myview.1jsf&#039;);&quot;&gt;
&lt;/h:commandLink&gt;
....
&lt;h:commandLink action=&quot;#{mybean.myaction2}&quot; id=&quot;link2&quot; value=&quot;Click here to open new window2&quot; onclick=&quot;javascript:window.open(&#039;#{request.contextPath}/myview2.jsf&#039;);&quot;&gt;
&lt;/h:commandLink&gt;
...
&lt;/h:form&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2009/12/02/how-to-open-a-new-window-from-jsf-commandlink-tag/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Formatting messages on JSF page in JBoss Seam</title>
		<link>http://myblog.shriharisc.com/2009/11/18/formatting-messages-on-jsf-page-in-jboss-seam/</link>
		<comments>http://myblog.shriharisc.com/2009/11/18/formatting-messages-on-jsf-page-in-jboss-seam/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 17:58:18 +0000</pubDate>
		<dc:creator>Shrihari</dc:creator>
				<category><![CDATA[jee-light]]></category>
		<category><![CDATA[jboss-seam]]></category>

		<guid isPermaLink="false">http://myblog.shriharisc.com/?p=203</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <a href="http://docs.jboss.org/seam/2.2.0.CR1/api/org/jboss/seam/core/Interpolator.html">Interpolator</a> in Seam which helps us the solution. </p>
<p>Lets assume we have defined a message property as welcome.message as below</p>
<pre class="brush: sql">
#different message properties
...
welcome.message= Welcome! Dear #0
...
</pre>
<p>In the homepage.xhtml (jsf page), we come populate the greeting message with, say the logged in username, using interpolator as below:</p>
<pre class="brush: xml">
   ....
   &lt;h:outputText value=&quot;#{interpolator.interpolate(messages[&#039;welcome.message&#039;],identity.username)}&quot;/&gt;
....
</pre>
]]></content:encoded>
			<wfw:commentRss>http://myblog.shriharisc.com/2009/11/18/formatting-messages-on-jsf-page-in-jboss-seam/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
