<?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>JavaBeat &#187; Java / J2EE</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Sun, 16 Jun 2013 11:17:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>What is SLF4J?</title>
		<link>http://www.javabeat.net/2013/03/what-is-slf4j/</link>
		<comments>http://www.javabeat.net/2013/03/what-is-slf4j/#comments</comments>
		<pubDate>Thu, 28 Mar 2013 01:07:09 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[slf4j]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=6378</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Logging is a common issue for development teams. And right now there are a lot of options on what exactly to use for logging in Java. The most famous frameworks are: Log4j, Logback, Commons-logging, java.util.logging. But what happens if we want to change a logging framework by another one, did we have to change the whole [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p>Logging is a common issue for development teams. And right now there are a lot of options on what exactly to use for logging in Java. The most famous frameworks are: Log4j, Logback, Commons-logging, java.util.logging. But what happens if we want to change a logging framework by another one, did we have to change the whole application? If the project is high coupled with the logging framework, there&#8217;s no choice.</p>
<p>Here comes the role of The <strong>Simple Logging Facade for Java or (SLF4J)</strong> who serves as a simple facade or abstraction for various logging frameworks, allowing the end user to plug in the desired logging framework at deployment time. In this post we will discover how SLF4J works by analyzing it by <a href="http://www.jarchitect.com/">JArchitect</a>.</p>
<h2><b>JArchitect Overview</b></h2>
<p>JArchitect is a static analysis tool for Java codebases that provides interactive GUI(s) and HTML reports for finding overly complex or problematic areas of your code, performing analysis for refactoring and comparing changes over time.</p>
<p>The cool and powerful feature of the JArchitect is the support for Code Query Linq (CQLinq). The CQLinq lets the developers to query the Java code using LINQ queries, for example CQlinq can answer to the following requests:</p>
<p><strong><i>Which methods create objects of a particular class?</i></strong></p>
<pre class="brush: java; title: ; notranslate">

from m in Methods where m.CreateA (&quot;MyPackage.MyClass&quot;) select m

</pre>
<p><strong><i>Which methods assign a particular field?</i></strong></p>
<p>from m in Methods</p>
<pre class="brush: java; title: ; notranslate">

where m.AssignField(&quot;MyPackage.MyClass.m_Field&quot;) select m

</pre>
<p><strong><i>Which complex method is not enough commented?</i></strong></p>
<pre class="brush: java; title: ; notranslate">

&amp;nbsp;

from m in Application.Methods  where m.CyclomaticComplexity &gt;  15 &amp;&amp; m.PercentageComment &lt;  10

select new { m, m.CyclomaticComplexity, m.PercentageComment }

</pre>
<p>JArchitect provides more than 80 metrics that are related to your code organization, code quality and code structure. These metrics could be used in CQLinq to create your coding custom rules, JArchitect could be integrated into your build system to enforce the quality of your codebase.</p>
<h2><b>SLAF4J Analysis</b></h2>
<p>We analyze a solution containing SLF4JSample.jar a sample project using SLF4J, slf4j-api.jar and slf4j-log4j.jar. Here&#8217;s the dependency graph after the analysis:</p>
<p style="text-align: center;"><a href="http://www.javabeat.net/wp-content/uploads/2013/03/1.png"><img class="aligncenter  wp-image-6379" alt="1" src="http://www.javabeat.net/wp-content/uploads/2013/03/1.png" width="564" height="216" /></a> <a href="http://www.javabeat.net/wp-content/uploads/2013/03/2.png"><br />
</a> <a href="http://www.javabeat.net/wp-content/uploads/2013/03/3.png"><br />
</a> <a href="http://www.javabeat.net/wp-content/uploads/2013/03/4.png"><br />
</a></p>
<p>This dependency graph reveals two remarks:</p>
<p>- SLF4JSample is not coupled directly with log4j, it knows only the facade slf4j-api.</p>
<p>- There&#8217;s a dependency cycle between slf4j-api and slf-log4j</p>
<p>And to have more infos about dependencies between all jars, the Dependency matrix shows also the dependency weight between them.</p>
<p align="center"><a href="http://www.javabeat.net/wp-content/uploads/2013/03/2.png"><img class="aligncenter size-full wp-image-6380" alt="2" src="http://www.javabeat.net/wp-content/uploads/2013/03/2.png" width="367" height="309" /></a></p>
<p>For example SLF4JSample use two members from slf4j-api.</p>
<p>To understand better how SLF4J works, let&#8217;s discover how all these jars collaborates with each other, and we can begin with SLF4jSample and search which methods it uses, for that we can execute the following CQLinq query:</p>
<pre class="brush: java; title: ; notranslate">

from m in Methods where m.IsUsedBy (&quot;com.srccodes.examples.SLF4JHello&quot;)

select new { m, m.NbBCInstructions }

</pre>
<p>Here&#8217;s the result:</p>
<p align="center"><a href="http://www.javabeat.net/wp-content/uploads/2013/03/3.png"><img class="aligncenter size-full wp-image-6381" alt="3" src="http://www.javabeat.net/wp-content/uploads/2013/03/3.png" width="367" height="363" /></a></p>
<p>SLF4JHello ask for a logger from slf4j-api by invoking LoggerFactory.getLogger method, and after use it. What’s interesting is that SLF4JHello is not coupled directly with the logger implementation, but pass by the interface Logger.</p>
<p><b>How SLF4J got the logger?</b></p>
<p>To discover that let&#8217;s see which methods are invocked by LoggerFactory.getLogger</p>
<p style="text-align: center;"> <a href="http://www.javabeat.net/wp-content/uploads/2013/03/4.png"><img class="aligncenter  wp-image-6382" alt="4" src="http://www.javabeat.net/wp-content/uploads/2013/03/4.png" width="496" height="161" /></a></p>
<p>The getLogger method try to get a LoggerFactory from StaticLoggerBinder to ask it for a logger, the StaticLoggerBinder exist in slf4j-log4j.jar, this jar act as a binder between SLF4J and Log4j.</p>
<p>Let&#8217;s discover which methods are invoked by LoggerFactory.getILoggerFactory</p>
<pre class="brush: java; title: ; notranslate">

from m in Methods where m.IsUsedBy (&quot;org.slf4j.LoggerFactory.getILoggerFactory()&quot;)

select new { m, m.NbBCInstructions }

</pre>
<p align="center"><a href="http://www.javabeat.net/wp-content/uploads/2013/03/5.png"><img class="aligncenter size-full wp-image-6383" alt="5" src="http://www.javabeat.net/wp-content/uploads/2013/03/5.png" width="367" height="367" /></a></p>
<p>So getILoggerFactory search for org.slf4j.impl.StaticLoggerBinder to create the logger factory. What means that if we create a jar containing this method and copy it where slf4j-api exists, this method will be invoked when a logger factory is asked.</p>
<p>And in this case to switch from a logging framework to another we need only to copy the right binder corresponding to the framework used. What explains also the dependency cycle between slf4j-api and slf4j-log4j.</p>
<p>slf4j use a simple technique to act as a logging facade, and permit to have a low coupling between the application and the logging framework, and  we can also change at runtime the logging framework.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fjava-j2ee%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/java-j2ee/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/java-j2ee/feed/" data-count="vertical" data-text="Java / J2EE" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/03/what-is-slf4j/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>What is load on startup element in web.xml file</title>
		<link>http://www.javabeat.net/2013/02/what-is-load-on-startup-element-in-web-xml-file/</link>
		<comments>http://www.javabeat.net/2013/02/what-is-load-on-startup-element-in-web-xml-file/#comments</comments>
		<pubDate>Thu, 21 Feb 2013 04:33:47 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JSP]]></category>
		<category><![CDATA[Servlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=5941</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>specify the order in which we want to initialize various Servlets. Like first initialize Servlet1 then Servlet2 and so on. This is accomplished by specifying a numeric value for the  &#60;load-on-startup&#62; tag. &#60;load-on-startup&#62; tag specifies that the servlet should be loaded automatically when the web application is started. The value is a single positive integer, [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>specify the order in which we want to initialize various Servlets. Like first initialize Servlet1 then Servlet2 and so on.<br />
This is accomplished by specifying a numeric value for the  &lt;load-on-startup&gt; tag. &lt;load-on-startup&gt; tag specifies that the servlet should be loaded<br />
automatically when the web application is started.</p>
<p>The value is a single positive integer, which specifies the loading order. Servlets with lower values are loaded before servlets with<br />
higher values (ie: a servlet with a load-on-startup value of 1 or 5 is loaded before a servlet with a value of 10 or 20). When loaded, the init() method of the servlet is called. Therefore this tag provides a good way to do the following:</p>
<p>start any daemon threads, such as a server listening on a TCP/IP port, or a background maintenance thread perform initialisation of the application, such as parsing a settings file which provides data to other servlets/JSPs If no &lt;load-on-startup&gt; value is specified, the servlet will be loaded when the container decides it needs to be loaded &#8211; typically on it&#8217;s first access. This is suitable for servlets that don&#8217;t need to perform special initialisation.</p>
<p>I hope that clears all the doubts regarding &lt;load-on-startup&gt; in web.xml.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2013/02/what-is-load-on-startup-element-in-web-xml-file/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Lazy Initialization, Singleton Pattern and Double Checked locking</title>
		<link>http://www.javabeat.net/2012/07/lazy-initialisation-singleton-and-double-check-locking/</link>
		<comments>http://www.javabeat.net/2012/07/lazy-initialisation-singleton-and-double-check-locking/#comments</comments>
		<pubDate>Tue, 24 Jul 2012 17:21:48 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4779</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Lazy Initialization Lazy Initialization is a technique where one postpones the instantiation of a object until its first use. In other words the instance of a class is created when its required to be used for the first time. The idea behind this is to avoid unnecessary instance creation. But there are concerns related to [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h3>Lazy Initialization</h3>
<p><a href="http://en.wikipedia.org/wiki/Lazy_initialization" target="_blank"><strong>Lazy Initialization</strong></a> is a technique where one postpones the instantiation of a object until its first use. In other words the instance of a class is created when its required to be used for the first time. The idea behind this is to avoid unnecessary instance creation. But there are concerns related to using such approaches in a concurrent scenario. But before that lets see how lazy initialization looks:</p>
<pre class="brush: java; title: ; notranslate">
class ResourceManager{
  private Resource resource;
  public Resource getResource(){
    if ( resource == null ){
      resource = new Resource();
    }
    return resource;
  }
}
</pre>
<p>When the above code is executed in a multi threaded program the concern that immediately comes to the mind is the &#8220;Race condition&#8221;.<br />
Thread A would check that resource == null so it goes inside to create the instance but might go into Runnable status before it creates the Resource instance.<br />
Thread B also checks that resource == null and it goes ahead, creates the instance and uses it for its operations.<br />
Thread A comes back to running status and it also continues to create its own instance and start using it. </p>
<p>Now in the above case suppose we wanted both Thread A and Thread B to work on the same instance, but due to the race condition they would work on different instances. If the Resource instances has state information associated with it then it because a critical problem. Lets stop here and then see how Singleton is related to this.</p>
<h3>Singleton</h3>
<p><strong>Singleton</strong> is one of the Creational Design Patterns discussed in the GoF Design Patterns. The main idea behind the Singleton pattern is to control the creation of objects for a given class such that at any time there&#8217;s only one instance of that particular class. So lets see how we can implement the Singleton pattern:</p>
<pre class="brush: java; title: ; notranslate">
class Resource{
  private static Resource instance;
  public static Resource getInstance(){
    if ( instance == null){
      instance = new Resource();
    }
    return instance;
  }
}
</pre>
<p>where in the above example Resource is a singleton. This is very similar to the concept of lazy initialization and this as well suffers from the issues seen while using this is a multi threaded environment/program. </p>
<h3>Double Checked Locking</h3>
<p>One way to solve the problem with Lazy initialization and singleton in a multi threaded program is to declare the getInstance() or getResource() method as <strong>synchronized</strong>. But its a huge overhead because everytime the method is invoked it has to go through the process of waiting for the lock and then obtaining the lock and its unnecessary because its only once that the instance is created and all subsequent invocations would just return that instance. </p>
<p>To work around this issue, <strong><a href="http://en.wikipedia.org/wiki/Double-checked_locking" target="_blank">Double Checked Locking</a></strong> is the pattern used. In this approach the methods are not synchronized instead the instance creation code is put in a synchronized block. Let me show an example:</p>
<pre class="brush: java; title: ; notranslate">
class Resource{
  private static Resource instance;
  public static Resource getInstance(){
    if ( instance == null ){
      synchronized(Resource.class){
        if ( instance == null ){
          instance = new Resource();
        }
      }/end of synchronized block.
    }
    return instance;
  }
}
</pre>
<p>In the above code there are two null checks- one outside the synchronized block and one within it. The synchronized block is executed at most once and any other thread trying to get instance would have to wait until the instantiation to complete. </p>
<p>The above approach also has some issues. The initialization of an object and the creation of instance of that class are 2 different operations. Once the instance of the class has been created that instance is then used to initialize the values of its state either with default values or some user defined values. Now between these 2 operations another thread might invoke the method to get the instance and sees that the instance is already not null and then proceeds with using that instance. Though its the correct instance we wanted the thread to use but that instance hasn&#8217;t been initialized yet. This issue is called as Unsafe Publication. <a href="http://www.javabeat.net/2012/07/book-review-java-concurrency-practice/" title="Book Review: Java Concurrency in Practice" target="_blank">Java Concurrency in Practice</a> book has a really good chapter on Java Memory Model and issues related to Safe Publication and Unsafe Publication of instances. </p>
<h3>Lazy Initialization holder class idiom</h3>
<p>One can read about this Lazy Initialization holder class Idiom in the interview with Joshua Bloch <a href="http://java.sun.com/developer/technicalArticles/Interviews/bloch_effective_08_qa.html" target="_blank">here</a>. It has been covered in Effective Java by Joshua Bloch and also in <a href="http://www.javabeat.net/2012/07/book-review-java-concurrency-practice/" title="Book Review: Java Concurrency in Practice" target="_blank">Java Concurrency in Practice</a>. Let me just share that idea here:</p>
<pre class="brush: java; title: ; notranslate">
class Resource{
  private static class ResourceHolder{
    static final Resource instance = new Resource();
  }
  public static Resource getInstance(){
    return ResourceHolder.instance;
  }
}
</pre>
<p>This takes advantage of: </p>
<ul>
<li>Eager Initialization</li>
<li>Class not initialized unless its used/loaded by the class loader the first time its used. </li>
</ul>
<p>Another <a href="http://www.coderanch.com/t/500367/threads/java/No-synchronization-there-Lazy-Initialization" target="_blank">interesting discussion</a> related to this on JavaRanch.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/07/lazy-initialisation-singleton-and-double-check-locking/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Implementing a Producer-Consumer scenario using BlockingQueue in Java</title>
		<link>http://www.javabeat.net/2012/06/implementing-producer-consumer-scenario-using-blockingqueue-java/</link>
		<comments>http://www.javabeat.net/2012/06/implementing-producer-consumer-scenario-using-blockingqueue-java/#comments</comments>
		<pubDate>Wed, 27 Jun 2012 10:00:47 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[Java 5.0]]></category>
		<category><![CDATA[java concurrency]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4486</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Before we start with the actual example, lets have a look at the few concepts we should be aware of. Producer-Consumer Problem Wikipedia here says that: The consumer producer problem (also known as the bounded-buffer problem) is a classical example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Before we start with the actual example, lets have a look at the few concepts we should be aware of. </p>
<h4>Producer-Consumer Problem</h4>
<p>Wikipedia <a href="http://en.wikipedia.org/wiki/Producer-consumer_problem" target="_blank">here</a> says that:<br />
The consumer producer problem (also known as the bounded-buffer problem) is a classical example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer&#8217;s job is to generate a piece of data, put it into the buffer and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer) one piece at a time. The problem is to make sure that the producer won&#8217;t try to add data into the buffer if it&#8217;s full and that the consumer won&#8217;t try to remove data from an empty buffer.</p>
<p>The solution for the producer is to either go to sleep or discard data if the buffer is full. The next time the consumer removes an item from the buffer, it notifies the producer, who starts to fill the buffer again. In the same way, the consumer can go to sleep if it finds the buffer to be empty. The next time the producer puts data into the buffer, it wakes up the sleeping consumer. The solution can be reached by means of inter-process communication, typically using semaphores. An inadequate solution could result in a deadlock where both processes are waiting to be awakened. The problem can also be generalized to have multiple producers and consumers.</p>
<p>There are numerous ways to solve a Producer-Consumer problem and in this post I will show one simple way to solve this problem by using the Data Structures and other constructs provided in the JDK. Java 5 introduced a new set of concurrency related APIs in its java.util.concurrent package. As I said <a href="http://www.javabeat.net/2012/06/simple-introduction-to-fork-join-framework-in-java-7/" title="Simple introduction to Fork-Join Framework in Java 7" target="_blank">here</a>, not many of the developers are aware of these APIs and very few of the make use of it in their code. </p>
<p>There were quite a few new Collection classes which got introduced in Java 5 and one of them is the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html" title="BlockingQueue in Java" target="_blank">BlockingQueue</a>.</p>
<h4>BlockingQueue in Java</h4>
<p>The JavaDoc says:<br />
<a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html" target="_blank">BlockingQueue</a> is &#8220;A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.&#8221; There are multiple methods which are supported to retrieve and add elements to the queue wherein one pair throws an exceptions, one of them waits for some fixed time and one pair which blocks until the queue is full/empty. The methods which blocks the thread are the <strong>put(e)</strong> and <strong>take</strong>. </p>
<p>In a typical producer-consumer problem we would want the consumer thread to be blocked until there is something in the queue to be consumed and the producer thread to be blocked until there is some free space in the queue to add some element. With the use of normal collection classes it because quite a bit of work in implementing inter thread communication by waiting and notifying other threads about the status of the queue. The put(e) and take() methods of the BlockingQueue class are the ones which make it very easy to solve producer-consumer like problems.  </p>
<p>Lets take a scenario where the producer thread would watch for the files being modified in some directory and add those files to the queue and the consumer thread would print the contents of those files on to the console. </p>
<h4>Producer thread</h4>
<p>If you are not familiar with implementing the WatchService in Java, you must first read <a href="http://www.javabeat.net/2012/06/watchservice-api-java7-monitor-directory/" title="Implementing WatchService API in Java 7 to monitor the directory changes" target="_blank">this</a> to get an idea of how it works. </p>
<pre class="brush: java; title: ; notranslate">
class FileProducer implements Runnable{

  BlockingQueue&lt;Path&gt; filesList;
  Path rootPath;

  public FileProducer(BlockingQueue&lt;Path&gt; filesList, 
                      Path rootPath){
    this.filesList = filesList;
    this.rootPath = rootPath;
  }

  @Override
  public void run() {
    try {
      WatchService service = 
          FileSystems.getDefault().newWatchService();

      rootPath.register(service,
              StandardWatchEventKinds.ENTRY_MODIFY);

      while(true){
        WatchKey key = service.take();

        for (WatchEvent event : key.pollEvents()){

          Path relativePath = (Path)event.context();

          Path absolutePath =
                    Paths.get(rootPath.toString(),
                            relativePath.toString());

          filesList.put(absolutePath);

        }

        //reset is invoked to put the key back to ready
        boolean valid = key.reset();

        //If the key is invalid, just exit.
        if ( !valid){
          break;
        }
      }

    } catch (IOException e) {

      e.printStackTrace();

    } catch (InterruptedException e) {

      e.printStackTrace();

      Thread.currentThread().interrupt();
    }

  }
}
</pre>
<p>The producer thread above watches a certain directory for file modifications and adds the absolute path of the file into the BlockingQueue collection passed to the producer thread via its constructor. </p>
<h4>Consumer Thread</h4>
<p>The consumer thread would invoke take() on the BlockingQueue instance and then use the <a href="http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/" title="A peek into the Files utility which is part of java.nio package in Java 7" target="_blank">Files</a> API to read the contents. As take() is a blocking call, if the filesList collection is empty then it would just block and wait for the data to be available in the filesList collection. </p>
<pre class="brush: java; title: ; notranslate">
class FileConsumer implements Runnable{

  BlockingQueue&lt;Path&gt; filesList;
  Path rootPath;

  public FileConsumer(BlockingQueue&lt;Path&gt; filesList, 
                      Path rootPath){
    this.filesList = filesList;
    this.rootPath = rootPath;
  }

  @Override
  public void run(){
    try {
      while(true){

        Path fileToRead = filesList.take();

        List&lt;String&gt; linesInFile = 
            Files.readAllLines(fileToRead, 
                               Charset.defaultCharset());

        System.out.println(&quot;reading file: &quot;+fileToRead);

        for ( String line : linesInFile){
          System.out.println(line);
        }

      }
    } catch (InterruptedException e) {

      e.printStackTrace();

      Thread.currentThread().interrupt();
    } catch (IOException e) {

      e.printStackTrace();

    }

  }
}
</pre>
<p>Note: If you are writing to a file using Vim or some other editors which creates temporary files then you have to make sure you exclude such files being added to the queue. </p>
<h4>Invoking the Producer and consumer</h4>
<pre class="brush: java; title: ; notranslate">
public class ProducerConsumerSample {

  public static void main(String[] args) {
 
    BlockingQueue&lt;Path&gt; filesList = 
        new LinkedBlockingQueue&lt;&gt;(10);
 
    Path rootPath = Paths.get(&quot;/tmp/nio&quot;);
    
    Thread producerThread = 
        new Thread(new FileProducer(filesList, rootPath));
    Thread consumerThread = 
        new Thread(new FileConsumer(filesList, rootPath));
 
    producerThread.start();
    consumerThread.start();
  }

}
</pre>
<p>Pretty straight forward- create instances of both the threads and then launch them. You can create multiple consumer threads as well! In the above example we make use of the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html" title="LinkedBlockingQueue" target="_blank">LinkedBlockingQueue</a> which is one of the implementations of the BlockingQueue. </p>
<p>You have to make sure you import corresponding classes in your source code. You can have all the three classes defined in the same file and name the file as ProducerConsumerSample.java and compile and run the code. Once you have the code running, then go to your terminal and type:</p>
<pre class="brush: bash; title: ; notranslate">
/tmp/nio$ touch file1
/tmp/nio$ echo &quot;this is file1&quot; &gt;&gt; file1
/tmp/nio$ touch file2
/tmp/nio$ echo &quot;this is file2&quot; &gt;&gt; file2
</pre>
<p>and the output you see on the terminal of your java program is:</p>
<pre class="brush: bash; title: ; notranslate">
reading file: /tmp/nio/file1
reading file: /tmp/nio/file1
this is file1
reading file: /tmp/nio/file2
reading file: /tmp/nio/file2
this is file2
</pre>
<p>Note: This code was compiled and tested on a Linux platform, please find similar ways of creating files on Windows when you run your code. </p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/implementing-producer-consumer-scenario-using-blockingqueue-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New features in JDBC 3.0</title>
		<link>http://www.javabeat.net/2012/06/new-features-jdbc-3-0/</link>
		<comments>http://www.javabeat.net/2012/06/new-features-jdbc-3-0/#comments</comments>
		<pubDate>Mon, 18 Jun 2012 23:59:46 +0000</pubDate>
		<dc:creator>sraja</dc:creator>
				<category><![CDATA[JDBC]]></category>
		<category><![CDATA[JDBC 3.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4363</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article provides an introduction to the array of core new features available in JDBC 3.0. More specifically, the features &#8216;supporting save points&#8217;, &#8216;using parameter metadata&#8217;, &#8216;updating large objects&#8217; and &#8216;auto generated keys&#8217; are discussed. Wherever possible, to get a hang of it, relevant code samples have been provided in the respective sections. Download Source [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>This article provides an introduction to the array of core new features available in <strong><em>JDBC 3.0</em></strong>. More specifically, the features &#8216;supporting save points&#8217;, &#8216;using parameter metadata&#8217;, &#8216;updating large objects&#8217; and &#8216;auto generated keys&#8217; are discussed. Wherever possible, to get a hang of it, relevant code samples have been provided in the respective sections.</p>
<blockquote><p><strong>Download Source Code:</strong> <a class="downloadlink" href="http://www.javabeat.net/downloads/Jdbc3-NewFeatures.zip" title=" downloaded 70 times" >New Features in JDBC 3.0 (70)</a></p></blockquote>
<h2>Defining savepoints</h2>
<p>It is possible to programmatically control the creation and releasing of <strong><em>save points</em></strong> through <strong>JDBC 3.0</strong>. But before doing it, one must check whether the underlying database supports the concepts of <strong>savepoints</strong>. Save points provide multiple-level-control of database commit or rollback operations within a single transaction. For example, if two unrelated database operations have to happen with a single transaction, these two save points can be created for the very purpose. Then based on various business conditions, commit/rollback can be done to any of these save points within the same transaction. To illustrate the usage, consider the following example,</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.jdbc3.newfeatures.savepoint;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.Savepoint;

import net.javabeat.jdbc3.newfeatures.CommonUtils;

public class SavepointTest {
 public static void main(String[] args) throws Exception{
	Connection connection = CommonUtils.getConnection();
	DatabaseMetaData databaseMetadata = connection.getMetaData();
	if (databaseMetadata.supportsSavepoints()){
		System.out.println(&quot;Savepoints supported by
		       the target database&quot;);
		processTable(connection);
	}
	}

	private static void processTable(Connection connection)
		throws Exception{
		PreparedStatement pStatement = connection.prepareStatement(&quot;
		          INSERT INTO CUSTOMER VALUES (?, ?)&quot;);
		pStatement.setInt(1, 1);
		pStatement.setString(2, &quot;New Customer&quot;);
		pStatement.execute();
		Savepoint countrySavepoint =
			connection.setSavepoint(&quot;country&quot;);
		pStatement = connection.prepareStatement(&quot;
		          INSERT INTO COUNTRY VALUES (?, ?)&quot;);
		pStatement.setInt(1, 1);
		pStatement.setString(2, &quot;India&quot;);
		// Make this transaction to fail deliberately
		connection.rollback(countrySavepoint);
		connection.commit();
	}
}
</pre>
<p>As seen from the above example, the program checks whether save points are supported by the target database by querying methods available in DatabaseMetadata. Note for save points are created by calling the method setSavePoint() defined on the Connection object. A save point can be given a name so that at a later point of time, a transaction can be made to commit or rollback based on the name. In the example code, to illustrate the usage of save point, we deliberately rollback the operation related to customer table, whereas, the changes made to country table are committed.</p>
<h2>Parameter Metadata</h2>
<p>Construction of queries for statements such as prepared statements might involve specifying dynamic values through &#8216;?&#8217;. Previously, there was no support for the tools or for the applications to identify the parameter information embedded in the queries. Now, support has been added to retrieve the parameter information that is passed to prepared statements. Please refer the below code that illustrates the usage,</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.jdbc3.newfeatures.pmd;

import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;

import net.javabeat.jdbc3.newfeatures.CommonUtils;

public class PMDTest {
	public static void main(String[] args) throws Exception{
		Connection connection = CommonUtils.getConnection();
		PreparedStatement pStatement = connection.prepareStatement(
			&quot;INSERT INTO CUSTOMER VALUES (?, ?)&quot;);
		pStatement.setInt(1, 1);
		pStatement.setString(2, &quot;New Customer&quot;);
		ParameterMetaData parameterMetadata = pStatement.getParameterMetaData();
		int parameterCount = parameterMetadata.getParameterCount();
		for (int index = 1; index &lt;= parameterCount; index ++){
			String parameterClassName = parameterMetadata.getParameterClassName(index);
			int parameterMode = parameterMetadata.getParameterMode(index);
			String paramterTypeName = parameterMetadata.getParameterTypeName(index);
			System.out.println(parameterClassName + &quot;/&quot; + parameterMode + &quot;/&quot;
				+ &quot;/&quot; + paramterTypeName);
		}
	}
}
</pre>
<h2>Auto Generated Keys</h2>
<p>Execution of queries sometimes results in the automatic generation of fields or values for tables. The behavior is entirely dependent on the underlying database implementation. Previously, there was no standard mechanism for retrieving such information once the query is executed. Application developers are forced to use non-standard mechanisms for fetching information that happens outside the scope of query execution. For example, consider a table column containing a particular column, say &#8216;name&#8217;, and an equivalent upper column, let&#8217;s say &#8216;upper_name&#8217;. The value for the &#8216;upper_name&#8217; will be automatically populated as soon as the value is populated for the &#8216;name&#8217; column. This is one of the examples of <strong><em>auto generation feature</em></strong> and the newer specification supports this feature. Refer the code sample below,</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.jdbc3.newfeatures.autogenkey;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.Statement;

import net.javabeat.jdbc3.newfeatures.CommonUtils;

public class AutoGeneratedKeyTest {
	public static void main(String[] args) throws Exception{
		Connection connection = CommonUtils.getConnection();
		DatabaseMetaData databaseMetadata = connection.getMetaData();
		if (databaseMetadata.supportsGetGeneratedKeys()){
			processAutoGeneratedKeys(connection);
		}
	}

	private static void processAutoGeneratedKeys(Connection connection)
		throws Exception{
		System.out.println(&quot;Auto generated keys can be retrived&quot;);
		Statement statement = connection.createStatement();
		statement.execute(&quot;INSERT INTO ADDRESSINFORMATION (ADDRESSDATA ) &quot; +
			&quot;VALUES ('Address Text')&quot;, Statement.RETURN_GENERATED_KEYS);
		ResultSet resultSet = statement.getGeneratedKeys();
		java.sql.ResultSetMetaData rsMetadata = resultSet.getMetaData();
		for (int index = 1; index &lt;= rsMetadata.getColumnCount(); index ++){
			while (resultSet.next()){
				String columnLabel = rsMetadata.getColumnName(index);
				System.out.println(resultSet.getObject(columnLabel));
			}
		}
	}

}
</pre>
<p>Note that, while executing the statement, the application has to provide indication to the underlying engine that, if any auto generation columns are applicable once the query is executed, those information have to be made available in the equivalent statement object. This is done through the method Statement.execute() where the second parameter specifies this option. Next, the method getGeneratedKeys() is added to the Statement object which returns a ResultSet containing the desired values. Because, this feature may or may not be supported by the database engine, the API supportsGeteGeneratedKeys() can be used to check the feature availability.</p>
<h2>Updating clob/blob objects</h2>
<p>The support to update clob objects is directly available on the Clob/Blob objects. The method <em>updateClob()</em> is added to the <em>ResultSet</em> object. Previously, there is no standard way to update large data objects. Note to ensure that this works and because the operation is defined on the ResultSet, the underlying ResultSet object should support updating the record. This is possible if the <em>ResultSet</em> is a flavor of <em>CONCUR_UPDATABLE</em>. Please refer the below code,</p>
<pre class="brush: java; title: ; notranslate">
package net.javabeat.jdbc3.newfeatures.clblupdate;

import java.io.StringReader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import net.javabeat.jdbc3.newfeatures.CommonUtils;

public class ClobTest {

	public static void main(String[] args) throws Exception{
		Connection connection = CommonUtils.getConnection();
		int key = 1;
		insertClob(connection, key);
		readAndUpdateClob(connection, key);
	}

	private static void insertClob(Connection connection, int key)
		throws Exception{
		String sql = &quot;INSERT INTO CLOBTEST VALUES (?, ?)&quot;;
		PreparedStatement pStatement = connection.prepareStatement(sql);
		pStatement.setInt(1, key);
		StringReader reader = new StringReader(&quot;som big data&quot;);
		pStatement.setClob(2, reader);
		pStatement.execute();
	}

	private static void readAndUpdateClob(Connection connection, int key)
		throws Exception{
		String sql =  &quot;SELECT DATA FROM CLOBTEST WHERE ID = ?&quot;;
		PreparedStatement pStatement = connection.prepareStatement(
			sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
		pStatement.setInt(1, key);
		ResultSet resultSet = pStatement.executeQuery();
		if (resultSet.next()){
			Clob clobObject = resultSet.getClob(1);
			clobObject.setString(1, &quot;new big data&quot;);
			resultSet.updateClob(1, clobObject);
		}
	}
}
</pre>
<h2>Conclusion</h2>
<blockquote><p><strong>Download Source Code:</strong> <a class="downloadlink" href="http://www.javabeat.net/downloads/Jdbc3-NewFeatures.zip" title=" downloaded 70 times" >New Features in JDBC 3.0 (70)</a></p></blockquote>
<p>The new features in JDBC 3.0 have addressed most of the common problems that tools or developer community is encountering, thereby providing a unified way of solution. There are other minor updates done to JDBC 3.0, such as &#8216;configuring connection pools&#8217;, &#8216;adding of new data types as Boolean, Datalink, URL&#8217; etc.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/new-features-jdbc-3-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JavaBeat Newsletter-2: New and noteworthy in Java Ecosystem</title>
		<link>http://www.javabeat.net/2012/06/javabeat-newsletter-2-new-noteworthy-java-ecosystem/</link>
		<comments>http://www.javabeat.net/2012/06/javabeat-newsletter-2-new-noteworthy-java-ecosystem/#comments</comments>
		<pubDate>Mon, 18 Jun 2012 16:25:33 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[JavaBeat Newsletter]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4357</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Interesting blog posts from JavaBeat: Exploring the enhancements to the java.nio package as part of Java 7 we wrote about watching a directory for changes and also looked at few methods in the Files class. Writing agents in Java to instrument the class files/byte code. Using Fork-Join framework introduced as part of Java 7. Getting [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h3>Interesting blog posts from JavaBeat:</h3>
<ul>
<li>Exploring the enhancements to the java.nio package as part of Java 7 we wrote about <a title="Watching a directory for changes using File NIO in Java 7" href="http://www.javabeat.net/2012/06/watching-a-directory-for-changes-using-file-nio-in-java-7/">watching a directory for changes</a> and also looked at <a title="A peek into the Files utility which is part of java.nio package in Java 7" href="http://www.javabeat.net/2012/06/a-peek-files-utility-part-java-nio-package-java-7/">few methods in the Files class</a>.</li>
<li><a title="Introduction to Java Agents" href="http://www.javabeat.net/2012/06/introduction-to-java-agents/">Writing agents in Java to instrument</a> the class files/byte code.</li>
<li><a href="http://www.javabeat.net/tag/fork-join/" target="_blank">Using Fork-Join framework</a> introduced as part of Java 7.</li>
<li><a title="Java HelloWorld vs Scala HelloWorld" href="http://www.javabeat.net/2012/06/java-helloworld-vs-scala-helloworld/" target="_blank">Getting started with Scala</a>.</li>
</ul>
<h3>News and updates:</h3>
<h4>Languages</h4>
<ul>
<li>The JFXtras project has been enhanced to support JavaFX 2.0 and they have <a href="http://learnjavafx.typepad.com/weblog/2012/06/jfxtras-project-theres-an-app-for-that.html" target="_blank">released an application named JFXTras Ensemble.</a> Do check out the <a href="http://jfxtras.org/" target="_blank">project</a> to start using components which are not provided out of the box by JavaFX.</li>
<li><a href="http://griffon.codehaus.org/" target="_blank">Griffon 1.0 is out</a>. Griffon is a framework for building Desktop applications which run on JVM using Groovy language. Think it of as Grails for desktop.</li>
<li><a href="http://forums.gradle.org/gradle/topics/gradle_1_0_released" target="_blank">Gradle 1.0 is released</a>. Gradle is build automation tool which can automate the building, testing, publishing, deployment and more of software packages. Think of it as Ant and Maven on steroids.</li>
<li>Scala 2.10.0 Milestone 4 is now <a href="http://www.scala-lang.org/node/12702" target="_blank">available</a>.</li>
</ul>
<h4>Cloud:</h4>
<ul>
<li>Free Tomcat application hosting now supported by OpenShift, read <a href="https://openshift.redhat.com/community/blogs/free-apache-tomcat-hosting-in-the-cloud-for-java-applications-its-called-openshift" target="_blank">here</a> to know how.</li>
<li>New OpenShift release and the features have been documented <a href="https://openshift.redhat.com/community/blogs/new-openshift-release-june-7-2012-instant-apps-new-windows-client-and-more" target="_blank">here</a>.</li>
</ul>
<h3>Events:</h3>
<ul>
<li><a href="http://openjdk.java.net/projects/mlvm/jvmlangsummit/" target="_blank">JVM Language Summit</a> July 30–August 1, 2012 at Oracle Corporation: Santa Clara campus.</li>
<li>Dustin <a href="http://marxsoftware.blogspot.in/2012/06/javaone-2012-content-catalog-available.html?utm_source=feedburner&amp;utm_medium=feed&amp;utm_campaign=Feed:+InspiredByActualEvents+%28Inspired+by+Actual+Events:+Cogitations+and+Speculations%29&amp;utm_content=Google+Reader" target="_blank">writes</a> about the availability of JavaOne 2012 content catalog.</li>
<li><a href="https://developers.google.com/events/io/" target="_blank">Google IO 2012</a>- June 27-29, 2012 Moscone Center, San Francisco.</li>
</ul>
<h3>Podcasts:</h3>
<ul>
<li><a href="https://blogs.oracle.com/javaspotlight/entry/java_spotlight_episode_86_tony" target="_blank">Java Spotlight Episode 86: Tony Printezis on Garbage Collection First</a></li>
<li><a href="https://blogs.oracle.com/javaspotlight/entry/java_spotlight_episode_85_migrating" target="_blank">Java Spotlight Episode 85: Migrating from Spring to JavaEE 6</a></li>
<li><a href="http://javaposse.com/java-posse-387-roundup-12-no-sql" target="_blank">Java Posse #387 &#8211; Roundup &#8217;12 &#8211; NoSQL</a></li>
<li><a href="http://javaposse.com/java-posse-386-newscast-for-may-31st-2012" target="_blank">Java Posse #386 &#8211; Newscast for May 31st 2012</a>- Interesting discussion on handling of Nulls in various languages with special focus on Scala. Discussion about Play framework as well.</li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/06/javabeat-newsletter-2-new-noteworthy-java-ecosystem/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deploying a ZK based Java EE application to Red Hat Open Shift Cloud</title>
		<link>http://www.javabeat.net/2012/05/deploying-zk-javaee-to-openshift/</link>
		<comments>http://www.javabeat.net/2012/05/deploying-zk-javaee-to-openshift/#comments</comments>
		<pubDate>Tue, 29 May 2012 16:46:38 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java EE 6.0]]></category>
		<category><![CDATA[Web Frameworks]]></category>
		<category><![CDATA[JavaEE]]></category>
		<category><![CDATA[OpenShift]]></category>
		<category><![CDATA[ZK]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=4013</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>OpenShift is a Platform As A Service (Paas) offering from Red Hat joining the likes of Heroku, GAE, Jelastic and others. OpenShift supports Java EE, PHP, Node.js, Ruby, Python and Perl applications. I tried out deploying a simple Java EE application based on ZK Framework, interested people can have a look at the application running [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><a href="https://openshift.redhat.com/app/" title="OpenShift" target="_blank">OpenShift</a> is a Platform As A Service (Paas) offering from Red Hat joining the likes of Heroku, GAE, Jelastic and others. OpenShift supports Java EE, PHP, Node.js, Ruby, Python and Perl applications. I tried out deploying a simple Java EE application based on <a href="http://www.zkoss.org/" title="ZK Framework" target="_blank">ZK Framework</a>, interested people can have a look at the application running live <a href="http://marathons-mylearning.rhcloud.com/marathonHome.zul" target="_blank">here</a>. </p>
<p>This article would cover:</p>
<ul>
<li>Setting up of OpenShift account, Maven and creating an application on cloud</li>
<li>Developing and deploying the application on cloud</li>
</ul>
<h3>Setting up OpenShift Account, Creating application</h3>
<p>First step to setting up of application is to create an account on the OpenShift website <a href="https://openshift.redhat.com/app" title="OpenShift" target="_blank">here</a>. Once you have registered, you have to download and install the Command line tool for OpenShift cloud control which is <a href="https://openshift.redhat.com/app/getting_started" title="RedHat Console" target="_blank">Redhat Console(rhc)</a>. I used the Ruby gems to install the RHC tool which is as simple as:</p>
<pre class="brush: bash; title: ; notranslate">$ sudo gem install rhc</pre>
<h4>Creating a domain and application</h4>
<p>All the applications deployed on OpenShift are in a namespace which is nothing but the domain you create. Domain names have to be unique and are part of the URL to access the application. </p>
<pre class="brush: bash; title: ; notranslate">
#Creating a domain
$ rhc domain create -l &lt;login&gt; -n &lt;domain name&gt;
Password: &lt;password&gt;
</pre>
<p>Once the domain has been successfully created, the next step is to create an application: </p>
<pre class="brush: bash; title: ; notranslate">
#Creating an application
$rhc app create -a &lt;application_name&gt; -l &lt;loginname&gt; -t jbossas-7.0
</pre>
<p>-t option is used to specify the type of the application, which can be any one of the following:<br />
php-5.3 — for PHP applications<br />
wsgi-3.2 — for Web Server Gateway Interface applications<br />
rack-1.1 — for Ruby Webserver Interface applications<br />
perl-5.10 — for Perl applications<br />
jbossas-7.0 — for JBoss AS applications (used for ZK project)<br />
raw-0.1 — a raw cartridge type used to create applications of no specific type</p>
<p>A Cartridge is the other infrastructure elements that your application would use and these can be added using the same rhc app command. In our application we would not be using any of those and hence not being added.</p>
<p>The same operations can be performed from their web console as well. An advantage of using the command line is that once you create an domain using rhc command line, it adds the necessary ssh-keys, and also while creating the application it sets up the git repository as well. Deploying to OpenShift is as simple and pushing the application to the remote git repository, this is similar to the approach in <a href="http://www.heroku.com/" title="Heroku" target="_blank">Heroku</a>. </p>
<h4>Setting up Maven</h4>
<p>The application is nothing but an Maven project. So if you are interested to run the application locally then you need to setup Maven as well. Download the Maven package from <a href="http://maven.apache.org/download.html" title="Maven" target="_blank">here</a>, and setup the M2_HOME environment variable to the Maven home i.e the folder where the Maven package was extracted and also update the PATH variable to the M2_HOME/bin. </p>
<pre class="brush: bash; title: ; notranslate">
$mvn -version
Apache Maven 3.0.4 (r1232337; 2012-01-17 14:14:56+0530)
Maven home: /home/mohamed/maven
Java version: 1.7.0, vendor: Oracle Corporation
Java home: /home/mohamed/jdk1.7.0/jre
</pre>
<h3>Developing and Deploying the Application</h3>
<p>We would be using <a href="http://www.zkoss.org/" target="_blank">ZK framework</a> for our sample application. The application reads from a JSON source about the Marathon Events in India and plots them on a Google Map. For reading the JSON source we would be using the <a href="http://www.javabeat.net/2012/04/parsing-json-using-java-and-gson-library/" title="Parsing JSON using Java and GSON library" target="_blank">GSON library</a>.<br />
We have to update the contents of <a href="https://github.com/sanaulla123/Marathons/blob/7cbd8c0199d4b17c2001ca9c92727dfe02d02a77/pom.xml" target="_blank">pom.xml</a> to reflect the ZK, GSON and other dependencies. One can even use Eclipse to develop the application and that is exactly what I did:</p>
<pre class="brush: bash; title: ; notranslate">
$ mvn eclipse:eclipse
</pre>
<p>and then load the project in eclipse. Also Eclipse should be able to resolve the libraries used in the application i.e all the ZK jars and the GSON jar. If you find any issue where eclipse complains about not finding the jars, then you must add a variable M2_REPO to Eclipse environment variables which would point to the directory where Maven downloads all the jars.<br />
The <a href="https://github.com/sanaulla123/Marathons/blob/7cbd8c0199d4b17c2001ca9c92727dfe02d02a77/src/main/resources/net/javabeat/marathon_events.json" title="JSON Source" target="_blank">JSON source</a> for the marathon events is constructed from the details available on <a href="http://runinfinity.com/calendar/india-marathon-calendar" title="Marathon Calendar" target="_blank">RunInfinity website</a>.</p>
<p>There are few things to be done to plot the above data on a map:<br />
1. Construct <a href="http://www.zkoss.org/javadoc/zkforge/gmapsz/org/zkoss/gmaps/Gmarker.html" title="Gmarker" target="_blank">Gmarker</a> data from the above data.<br />
2. Obtain the Latitude and Longitude data from the location information. For this we make use of the <a href="https://developers.google.com/maps/documentation/geocoding/" target="_blank">Google Geocoding API</a>.</p>
<p>The Model which holds the Marathon event information is:</p>
<pre class="brush: java; title: ; notranslate">
public class MarathonEvent {
  @SerializedName(&quot;event_url&quot;)
  String url;
  String name;
  String date;
  String location;
  Location geoLocation;
  String formattedContent;
  @Override
  public String toString(){
    if ( formattedContent == null ){
      StringBuilder builder = new StringBuilder();
      builder.append(&quot;Date: &quot;+date);
      builder.append(&quot;&lt;br/&gt;&quot;);
      builder.append(&quot;&lt;a href=\&quot;&quot;+url+&quot;\&quot;&gt;&quot;+name+&quot;&lt;/a&gt;&quot;);
      builder.append(&quot;&lt;br/&gt;&quot;);
      builder.append(geoLocation.name);
      formattedContent = builder.toString();  
    }
    return formattedContent;
  }
}
</pre>
<p>Parsing the JSON source for Marathon Events list where the JSON source is marathon_events.json:</p>
<pre class="brush: java; title: ; notranslate">
InputStream marathonEvenJsonSource = 
    getClass().getResourceAsStream(&quot;marathon_events.json&quot;);

Gson gson = new Gson();

JsonReader jsonReader = new JsonReader(
    new InputStreamReader(marathonEvenJsonSource));

JsonParser jsonParser = new JsonParser();

JsonArray jsonArray = jsonParser.parse(jsonReader).getAsJsonArray();

for ( JsonElement element : jsonArray){
  MarathonEvent marathonEvent = 
      gson.fromJson(element, MarathonEvent.class);
  marathonEvent.geoLocation = getGeoCode(marathonEvent.location);

  Gmarker gmarker = new Gmarker(marathonEvent.location,
      marathonEvent.geoLocation.latitude,
      marathonEvent.geoLocation.longitude);
  gmarker.setContent(marathonEvent.toString());
  
  marathonEvents.add(gmarker);
}
</pre>
<p>if you are not able to follow the JSON parsing code, please read our previous article regarding the same <a href="http://www.javabeat.net/2012/04/parsing-json-using-java-and-gson-library/" title="Parsing JSON using Java and GSON library" target="_blank">here</a>.</p>
<p>The interesting part here is the <code>getGeoCode(marathonEvent.location)</code> call which is defined as:</p>
<pre class="brush: java; title: ; notranslate">
public Location getGeoCode(String location) 
    throws MalformedURLException, IOException{
  String url = 
    &quot;http://maps.googleapis.com/maps/api/geocode/json?address=&quot;+URLEncoder.encode(location, &quot;UTF-8&quot;)+&quot;&amp;sensor=false&quot;;
  Location geoLocation = new Location(location);
  Gson gson = new Gson();
  InputStream in = new URL(url).openStream();
  JsonReader reader = new JsonReader(new InputStreamReader(in));
  JsonParser parser = new JsonParser();
  JsonObject jsonObject = parser.parse(reader).getAsJsonObject();
  //Fetch all the possible latitude/longitude results for this place
  JsonArray resultsArray = jsonObject.getAsJsonArray(&quot;results&quot;);
  
  if ( resultsArray.size() &gt; 0 ){
    //Generally there's only one result, so pick the first. 
    JsonObject geoInformation = 
        resultsArray.get(0).getAsJsonObject();
    String formattedAddress = 
        geoInformation.get(&quot;formatted_address&quot;).getAsString();
    JsonObject locationJsonObj= 
      geoInformation.get(&quot;geometry&quot;)
                    .getAsJsonObject()
                    .get(&quot;location&quot;)
                    .getAsJsonObject();
    String latitude  = locationJsonObj.get(&quot;lat&quot;).getAsString();
    String longitude = locationJsonObj.get(&quot;lng&quot;).getAsString();
    geoLocation.latitude = Double.parseDouble(latitude);
    geoLocation.longitude = Double.parseDouble(longitude);
    geoLocation.name = formattedAddress;
  }
  return geoLocation;
}
</pre>
<p>The above code parses the JSON response obtained from the Google Places API and retrieves the formatted_address field and the latitude(lat) and longitude(lng) values. Here as well the GSON Library is used for parsing. The above two code snippets are part of the MarathonEventsSource class which is our source for model information to the views.</p>
<p>Now lets create a ZK based View and Controller/View Model class.</p>
<h4>ZK Based View</h4>
<pre class="brush: xml; title: ; notranslate">
&lt;zk&gt;
  &lt;script type=&quot;text/javascript&quot; 
  content=&quot;zk.googleAPIkey='AIzaSyAgYZVjw15TQWGxAMFv0ayA8OlAtVFkyx0'&quot; /&gt;
  &lt;window id=&quot;main&quot; width=&quot;100%&quot; height=&quot;100%&quot; apply=&quot;net.javabeat.MarathonHomeComposer&quot;&gt;
    &lt;borderlayout&gt;
      &lt;north size=&quot;70px&quot;&gt;
        &lt;div&gt;
        &lt;html&gt;&lt;![CDATA[
        &lt;h2 style=&quot;color:#0C7A9A;margin-left:10px&quot;&gt;Marathon Events in India&lt;/h2&gt;
        ]]&gt;&lt;/html&gt;
        &lt;/div&gt;
      &lt;/north&gt;
      &lt;center flex=&quot;true&quot;&gt;
        &lt;div id=&quot;contentDiv&quot; &gt;
          &lt;gmaps id=&quot;eventsMap&quot; width=&quot;100%&quot; height=&quot;100%&quot; showSmallCtrl=&quot;true&quot;&gt;
          &lt;attribute name=&quot;onMapClick&quot;&gt;&lt;![CDATA[
          org.zkoss.gmaps.Gmarker gmarker = event.getGmarker();
          if (gmarker != null)
            gmarker.setOpen(true);
          ]]&gt;&lt;/attribute&gt;
          &lt;/gmaps&gt;
        &lt;/div&gt;
      &lt;/center&gt;
      &lt;south size=&quot;20px&quot;&gt;
        &lt;hbox pack=&quot;center&quot; width=&quot;100%&quot;&gt;
        &lt;html&gt;&lt;![CDATA[
        &lt;span style=&quot;color:#0C7A9A&quot;&gt;Developed by Mohamed Sanaulla&lt;/span&gt;
        ]]&gt;&lt;/html&gt;
        &lt;/hbox&gt;
      &lt;/south&gt;
    &lt;/borderlayout&gt;
  &lt;/window&gt;
&lt;/zk&gt;
</pre>
<p>Interesting pieces from the above code:<br />
1. ZK provides different layouts for organising the contents and BorderLayout is one such layout. In this the content can be organized into 4 regions (exactly similar supported by Swing).<br />
2. Gmaps is the component for embedding the Google Maps.<br />
3. Each view can be backed a View Model class by using the apply attribute of window component <code>apply="net.javabeat.MarathonHomeComposer"</code></p>
<p>Lets have a look at the MarathonHomeComposer class which is the View Model/Controller class.</p>
<pre class="brush: java; title: ; notranslate">
public class MarathonHomeComposer extends GenericForwardComposer{

  MapModel mapModel;
  Gmaps eventsMap;
  Div contentDiv;

  public MarathonHomeComposer() 
      throws MalformedURLException, IOException{
    String marathonEventScheduleSource = 
      &quot;http://runinfinity.com/calendar/india-marathon-calendar&quot;;
    MarathonEventsSource marathonEventsSource = 
        new MarathonEventsSource();
    List&lt;Gmarker&gt; marathonEvents = 
        marathonEventsSource.getMarathonEvents();	
    mapModel = new MapModelList(marathonEvents);

  }
  public void doAfterCompose(Component comp) throws Exception {
    super.doAfterCompose(comp);		
    eventsMap.setModel(mapModel);
    eventsMap.setZoom(9);
  }
}
</pre>
<p>Few observations from the View Model class:<br />
1. It extends the GenericForwardComposer class which supports binding of the components between the View and the View Model based on the ids. For example- gmaps component has an id=&#8221;eventsMap&#8221; and the View Model MarathonHomeComposer class has an instance field by name: eventsMap. This is an easier way of binding the UI element to the Java layer, the other ways can be by using Annotations.<br />
2. The model for the Gmaps is MapModel which is constructed using the MapModelList and the List obtained from the JSON parser (MarathonEventsSource class)<br />
3. doAfterCompose method would have all the components (read Gmaps) initialized and hence we set the model in this method.</p>
<p>If you are interested in the source of this application, you can get it from the git repo <a href="https://github.com/sanaulla123/Marathons" title="Git Repo">here</a>.</p>
<h4>Deploying the application to OpenShift</h4>
<p>As I said earlier, deploying the application is as simple as running git push command. If you run:</p>
<pre class="brush: bash; title: ; notranslate">
$ git remote -v
origin	ssh://ad221d298243438491c77f9cd9a83206@marathons-mylearning.rhcloud.com/~/git/marathons.git/ (fetch)
origin	ssh://ad221d298243438491c77f9cd9a83206@marathons-mylearning.rhcloud.com/~/git/marathons.git/ (push)
</pre>
<p>The remote named origin points to the git repo in the cloud. Deploying the application to OpenShift platform:</p>
<pre class="brush: bash; title: ; notranslate">
$ git push origin
# other output
remote: [INFO] BUILD SUCCESS
remote: [INFO] -------------------------------------------------
remote: [INFO] Total time: 30.888s
remote: [INFO] Finished at: Tue May 29 12:24:43 EDT 2012
remote: [INFO] Final Memory: 11M/111M
remote: [INFO] -------------------------------------------------
#other output
</pre>
<p>Once you have deployed the application, you can access the application by visting: http://-.rhcloud.com/marathonHome.zul</p>
<p>Let me summarize this huge post into:<br />
1. Constructing the Model source for the Map- this involves reading the JSON source, obtaining the latitude and longitude information and then constructing the Gmarker objects.<br />
2. Construct the view- marathonHome.zul which has the gmaps component.<br />
3. Wire the View with the View Model class and also wire up the gmaps component with the model. </p>
<p>This sample application can be accessed <a href="http://marathons-mylearning.rhcloud.com/marathonHome.zul">here</a>.</p>
<p>Some of the useful resources for this sample:<br />
1. <a href="http://www.zkoss.org/javadoc/zkforge/gmapsz/index.html?org/zkoss/gmaps/Gmaps.html" target="_blank">Gmaps Java documentation</a>.<br />
2. <a href="http://www.zkoss.org/javadoc/6.0.1/zk/" target="_blank">ZK Components Java Documentation</a>.<br />
3. <a href="http://www.zkoss.org/zkdemo/reporting/google_map" target="_blank">ZK Live Demo</a>.<br />
4. <a href="https://developers.google.com/maps/documentation/geocoding/" title="Google Geocoding" target="_blank">Google Geocoding API</a><br />
5. <a href="https://openshift.redhat.com/app/getting_started" target="_blank">OpenShift Developer Resources</a>.<br />
6. Git Repository in <a href="https://github.com/sanaulla123/Marathons/" target="_blank">GitHub</a>.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/deploying-zk-javaee-to-openshift/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Implementing RESTful API for obtaining the book details for an ISBN</title>
		<link>http://www.javabeat.net/2012/05/implementing-restful-api-for-obtaining-the-book-details-for-an-isbn/</link>
		<comments>http://www.javabeat.net/2012/05/implementing-restful-api-for-obtaining-the-book-details-for-an-isbn/#comments</comments>
		<pubDate>Tue, 08 May 2012 06:00:57 +0000</pubDate>
		<dc:creator>Mohamed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Java / J2EE]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3620</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Lot of developers out there at some point in time would want to know about an API to get the book details and I was in such a situation sometime back and I managed to find out about ISBNDb. But when I looked for the apis sometime later, I landed here where there are 53 APIs [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p style="text-align: justify">Lot of developers out there at some point in time would want to know about an API to get the book details and I was in such a situation sometime back and I managed to find out about <a title="ISBNDb" href="https://isbndb.com/docs/api/51-books.html" target="_blank">ISBNDb</a>. But when I looked for the apis sometime later, I landed <a title="Books API" href="http://blog.programmableweb.com/2012/03/13/53-books-apis-google-books-goodreads-and-sharedbook/" target="_blank">here</a> where there are 53 APIs are listed. I am not sure how easy are others to use, but I found ISBNDb was just enough for my needs.</p>
<p style="text-align: justify">The base URL for the API is: <strong>https://isbndb.com/api/books.xml</strong>. It supports querying on lot of attributes like isbn, title, book_id, publisher_id (which are ISBNdb specific). In this example we are interested in using ISBN to query for the book details. But before proceeding further, you have to sign up to get access to the <a href="https://isbndb.com/account/dev/keys/" target="_blank">developer key</a>. Once you have the developer key, to get the book details given the ISBN the URL would be: <strong>https://isbndb.com/api/books.xml?access_key=[KEY]&amp;index1=isbn&amp;value1=[ISBN].</strong> The <strong>access_key</strong> query param would be assigned the key which you have obtained. <strong>index1</strong>, <strong>value1</strong> are the params which are used to pass filter data for obtaining the book details.  We could even filter on book title wherein we add index2=title and value2=any_book_title.</p>
<p style="text-align: justify">Lets use this API to obtain the book details and this would be implemented in Groovy.</p>
<p>Our Model class for the holding a book details would be:</p>
<pre class="brush: java; title: ; notranslate">
class Book {
  def isbn
  def title
  def authors
  def publisher
  def String toString(){
    &quot;Title: ${title}\nISBN: ${isbn}\n&quot;+
    &quot;Authors: ${authors}\n&quot;+
    &quot;Publisher: ${publisher}&quot;
  }
}
</pre>
<p>Building the URL for the API invocation:</p>
<pre class="brush: java; title: ; notranslate">

def  baseURL = &quot;https://isbndb.com/api/books.xml&quot;
def  ACCESS_KEY = &quot;YOUR_KEY&quot;

def scanner = new Scanner(System.in);
println &quot;Enter the ISBN&quot;
def isbnInput = scanner.nextLine()
def queryParams = []
queryParams &lt;&lt; &quot;access_key=${ACCESS_KEY}&quot;
queryParams &lt;&lt; &quot;index1=isbn&quot;
queryParams &lt;&lt; &quot;value1=${isbnInput}&quot;
def queryString = queryParams.join(&quot;&amp;&quot;)
def completeApiURl = &quot;${baseURL}?${queryString}&quot;

</pre>
<p>The above code accepts the ISBN from the User and then prepares the required URL for invoking. One can see that we have made use of Java class in Groovy. The operator &#8220;&lt;&lt;&#8221; when used with an array appends the values to the array. And the join(&#8220;&amp;&#8221;) would concatenate all the elements of the array using the &#8220;&amp;&#8221; character. Once we have the complete URL, we make use of the java.net.URL class to obtain the XML Response and then use <a title="XmlSlurper" href="http://groovy.codehaus.org/api/groovy/util/XmlSlurper.html" target="_blank">XmlSlurper</a> (remember <a title="Using JsonSlurper Groovy API from Java to parse JSON" href="http://www.javabeat.net/2012/05/using-jsonslurper-groovy-api-from-java-to-parse-json/" target="_blank">JsonSlurper</a>?) to parse the XML to get the required information:</p>
<pre class="brush: java; title: ; notranslate">
def apiResponse = new URL(completeApiURl).text
def xmlSlurper = new XmlSlurper()
def parsedXml = xmlSlurper.parseText(apiResponse)

def newBook =
  new Book(title:parsedXml.BookList.BookData.Title,
           isbn: parsedXml.BookList.BookData.@isbn,
           authors: parsedXml.BookList.BookData.AuthorsText,
           publisher: parsedXml.BookList.BookData.PublisherText)

println newBook
</pre>
<p>The complete code is:</p>
<pre class="brush: java; title: ; notranslate">
def  baseURL = &quot;https://isbndb.com/api/books.xml&quot;
def  ACCESS_KEY = &quot;MKKGCUMQ&quot;

def scanner = new Scanner(System.in);
println &quot;Enter the ISBN&quot;
def isbnInput = scanner.nextLine()
def queryParams = []
queryParams &lt;&lt; &quot;access_key=${ACCESS_KEY}&quot;
queryParams &lt;&lt; &quot;index1=isbn&quot;
queryParams &lt;&lt; &quot;value1=${isbnInput}&quot;
def queryString = queryParams.join(&quot;&amp;&quot;)
def completeApiURl = &quot;${baseURL}?${queryString}&quot;
def apiResponse = new URL(completeApiURl).text
def xmlSlurper = new XmlSlurper()
def parsedXml = xmlSlurper.parseText(apiResponse)

def newBook = new Book(title:parsedXml.BookList.BookData.Title,
isbn: parsedXml.BookList.BookData.@isbn,
authors: parsedXml.BookList.BookData.AuthorsText,
publisher: parsedXml.BookList.BookData.PublisherText)
println newBook

class Book {
  def isbn
  def title
  def authors
  def publisher

  def String toString(){
    &quot;Title: ${title}\n&quot;+
    &quot;ISBN: ${isbn}\n&quot;+
    &quot;Authors: ${authors}\n&quot;+
    &quot;Publisher: ${publisher}&quot;
  }
}
</pre>
<p>The execution and output of the above code:</p>
<pre class="brush: bash; title: ; notranslate">
$ groovy BookManager.groovy
Enter the ISBN
098478280X
Title: Cracking the Coding Interview
ISBN: 098478280X
Authors: Gayle Laakmann McDowell,
Publisher: CareerCup
</pre>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2012/05/implementing-restful-api-for-obtaining-the-book-details-for-an-isbn/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Core Tags in JSTL</title>
		<link>http://www.javabeat.net/2011/05/core-tags-in-jstl/</link>
		<comments>http://www.javabeat.net/2011/05/core-tags-in-jstl/#comments</comments>
		<pubDate>Sun, 22 May 2011 00:39:47 +0000</pubDate>
		<dc:creator>JavaBeat</dc:creator>
				<category><![CDATA[JSP]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=322</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>[ In the second part of this tutorial on JSTL, the author explains how the tags in the core-group can be used in JSP pages, with a number of simpleexamples.] We are now ready toexperiment with all the tags in the ‘core’ library. The core tags have the following uniform‘uri’. ‘http://java.sun.com/jstl/core&#039; =============================== ( However, in [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p class="MsoNormal"><span class="GramE"><span>[</span><span> In</span></span><span> the second part of this<br />
tutorial on JSTL, the author explains how the tags in the core-group can be<br />
used in JSP pages, with a number of simple<span></span>examples.]</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>We are now ready <span class="GramE">to<span></span>experiment</span> with all the tags in the<br />
‘core’ library. The core tags have the following <span class="GramE">uniform<span></span>‘<span class="SpellE">uri</span>’</span>.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>‘<span class="GramE"><b>http</b></span><b>://<span class="SpellE">java.sun.com/jstl/core</span>&#039;</b></span></p>
<p class="MsoNormal"><b><span>===============================</span></b></p>
<p class="MsoNormal"><span class="GramE"><span>( However</span></span><span>, in the book by Hans<br />
Bergsten<span></span><span class="SpellE">titled,&quot;Java</span><br />
Server Pages&quot; ( third edition), (<span class="SpellE">OReilly</span> pub)the<br />
<span class="SpellE">uri</span> is consistently given as :</span></p>
<p class="MsoNormal"><span>&#039;<span class="GramE">http</span>://<span class="SpellE">java.sun.com/<b>jsp/</b>jstl/core&#039;.It</span></span><span> looks as if there has been some<br />
change in specification and grammar, after it was published.</span></p>
<p class="MsoNormal"><span>This<br />
appears to be wrong <span class="GramE">as<span></span>the</span> server threw<span></span><span class="SpellE">exception.The</span> correct <span class="SpellE">uri</span> is :</span></p>
<div>
<p class="MsoNormal" style="border: medium none;padding: 0in;text-align: justify"><span>&#039;<span class="GramE"><b>http</b></span><b>://<span class="SpellE">java.sun.com/jstl/core</span>&#039;</b>.)</span></p>
</div>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>The<br />
prefix <span class="GramE">is<span></span>‘c</span>:’</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>The following tags are available in the<br />
‘core’ library.</span></p>
<p class="MsoNormal"><span class="GramE"><span>( Remember</span></span><span> them as a dozen!).</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><b><span></span>&lt;<span class="SpellE">c<span class="GramE">:set</span></span></b></span></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span></span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:if</span></span><span></span>test= “<span></span></span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:choose</span></span><span></span>,<span></span>&lt;<span class="SpellE">c:when</span> ,<span></span>&lt;<span class="SpellE">c:otherwise</span></span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:forEach</span></span></span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:forTokens</span></span></span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:import</span></span></span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:url</span></span></span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:redirect</span></span></span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:param</span></span></span></b></p>
<p class="MsoNormal"><span><span></span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></p>
<p class="MsoNormal"><span>We<br />
will now see simplest illustrations for the above <span class="SpellE">tags.There</span><br />
are a dozen demos, to bring out the features of each of these tags.</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;<span></span></span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span class="GramE"><b><span>demo1.jsp<span></span></span></b><span>uses</span></span><span><span></span><b>&lt;<span class="SpellE">c:set</span></b>&amp;<br />
<b><span></span>&lt;<span class="SpellE">c:out</span><span></span></b>tags.</span></p>
<p class="MsoNormal"><span class="GramE"><span>:We</span></span><span> create demo1.jsp<span></span>as:</span></p>
<p class="MsoNormal"><span>e:tomcat5webappsrootdemo1.jsp</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></p>
<p class="MsoNormal"><span>//<span></span><b>demo1.jsp</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;%@<br />
page <span class="SpellE">contentType</span>=&quot;text/html&quot; %&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;%@<br />
<span class="SpellE">taglib</span><span></span>prefix=&quot;c&quot;<span></span><span class="SpellE"><b>uri</b></span><b>=&quot;http://java.sun.com/jstl/core<span class="GramE">&quot;<span></span>%</span>&gt;</b></span></p>
<p class="MsoNormal"><b><span></span></b></p>
<p class="MsoNormal"><span>&lt;<span class="GramE">html</span>&gt;</span></p>
<p class="MsoNormal"><span>&lt;body<span></span><span class="SpellE">bgcolor</span>=<span class="SpellE">lightblue</span>&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>&lt;form<span></span>method=<span class="GramE">post<span></span>action</span>=&quot;demo1.jsp&quot;&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>NAME &lt;<span class="GramE">input<span></span>type</span>=text<span></span>name=&quot;text1&quot;&gt;&lt;<span class="SpellE">br</span>&gt;</span></p>
<p class="MsoNormal"><span><span></span>PLACE&lt;<span class="GramE">input<span></span>type</span>=text<span></span>name=&quot;text2&quot;&gt;&lt;<span class="SpellE">br</span>&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;input type=submit&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;/form&gt; </span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">NAME<b>:</b></span><b>&lt;<span class="SpellE">c:out</span></b><span></span>value<b>=&quot;${param.text1}&quot;</b><span></span>/&gt;&lt;<span class="SpellE">br</span>&gt;</span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">PLACE<b>:</b></span><b>&lt;<span class="SpellE">c:out</span><span></span></b>value<b>=&quot;${param.text2}&quot;<span></span></b>/&gt;</span></p>
<p class="MsoNormal"><span>&lt;/body&gt;</span></p>
<div>
<div style="border-style: none none double;border-color: -moz-use-text-color -moz-use-text-color windowtext;border-width: medium medium 2.25pt;padding: 0in 0in 1pt">
<p class="MsoNormal" style="border: medium none;padding: 0in;text-align: justify"><span>&lt;/html&gt;</span></p>
<p class="MsoNormal" style="border: medium none;padding: 0in;text-align: justify"><span></span></p>
</div>
</div>
<p class="MsoNormal"><span>In all the<br />
previous examples, we invoked the JSP file through a <span class="GramE">html<span></span>file</span>. But, in demo1.jsp, we <span class="GramE">are<span></span>posting</span> the page<br />
to itself.( in asp.net style!).<span class="GramE">( but</span> there is no<br />
&#039;retention of data&#039; , unlike asp.net).</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>We start<br />
Tomcat5, and type the <span class="SpellE">url</span><span class="GramE">as :</span></span></p>
<p class="MsoNormal"><span><span></span>‘<span class="GramE">http</span>://localhost:8080/demo1.jsp’.<span></span><span class="GramE">in</span> the <span class="SpellE">browser.We</span> get a form with two text boxes and a submit<br />
button. We fill up the textboxes with ‘name’ and ‘place’ and <span class="SpellE">submit.The</span> demo1.jsp executes and displays <span class="GramE">the<span></span>values</span> entered by<br />
the <span class="SpellE">user.due</span> to the JSTL tags </span></p>
<p class="MsoNormal"><b><span>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span><span></span>value=”${param.text1}</span></b><span><span></span>/&gt;<span></span>etc.</span></p>
<p class="MsoNormal"><span>That is<br />
about our first and introductory example.</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8211;<br />
&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span><span></span>The second example is very important. When<br />
the user enters data in a number of fields, it is tedious to collect the data<br />
and transfer it to <span class="SpellE">jsp</span> page for processing. In our<br />
example, we are collecting data about a player<span class="GramE">,<span></span>such</span> as his name, place and game. We<br />
can have much more but we are restricting for space considerations. JSP has an<br />
action <span class="GramE">tag ,</span> known as &#039;<span class="SpellE"><b>jsp:setProperty</b></span><b>&#039;</b>.<br />
Using this along with a standard <span class="SpellE">javabean</span>, we can<br />
extract data and transfer it to our program in a single step.</span></p>
<p class="MsoNormal"><span>The syntax<br />
is</span></p>
<p class="MsoNormal"><b><span>&lt;<span class="SpellE">jsp<span class="GramE">:useBean</span></span></span></b><span></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">id</span>=&quot;bean1&quot;<span></span>class=&quot;<span class="SpellE">ourbeans.player</span>&quot;<span></span>&gt;</span></p>
<p class="MsoNormal"><span><span></span><b>&lt;<span class="SpellE">jsp<span class="GramE">:setProperty</span></span></b></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">name</span>=&quot;bean1&quot;<span></span>property=&quot;*&quot;<span></span>/&gt;</span></p>
<p class="MsoNormal"><span>&lt;/<span class="SpellE">jsp<span class="GramE">:useBean</span></span>&gt;</span></p>
<p class="MsoNormal"><span> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_sad.gif' alt=':(' class='wp-smiley' /><br />
the * sign denotes &#039;all&#039;).</span></p>
<p class="MsoNormal"><span>&#8212;&#8211;</span></p>
<p class="MsoNormal"><span><span></span>But, we should first create the &#039;player &#039; bean<br />
with all the attributes and<b> getter &amp; setter methods</b>, as shown.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><b><span>/<span class="GramE">/<span></span><span class="SpellE">player.java</span></span></span></b></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span class="GramE"><b><span>package</span></b></span><b><span><span class="SpellE">ourbeans</span>;</span></b></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span class="GramE"><span>public</span></span><span> class player</span></p>
<p class="MsoNormal"><span>{</span></p>
<p class="MsoNormal"><span><span></span>String<span></span>name;</span></p>
<p class="MsoNormal"><span><span></span>String<span></span>place;</span></p>
<p class="MsoNormal"><span><span></span>String<span></span>game;</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">public</span> player()</span></p>
<p class="MsoNormal"><span><span></span>{</span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">name</span>=&quot;<span></span>&quot;;</span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">place</span>=&quot;<br />
&quot;;</span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">game</span>=&quot;<br />
&quot;;<span></span></span></p>
<p class="MsoNormal"><span><span></span>}</span></p>
<p class="MsoNormal"><span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">public</span> void<b><span class="SpellE">setName</span></b>(String a)</span></p>
<p class="MsoNormal"><span><span></span>{<span></span><span class="GramE">name=</span>a; }</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">public</span> void <span class="SpellE"><b>setPlace</b></span>(String b)</span></p>
<p class="MsoNormal"><span><span></span>{<span></span><span class="GramE">place=</span>b; }</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">public</span> void <span class="SpellE"><b>setGame</b></span><b>(</b>String c)</span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">{<span></span>game</span>=c;<span></span>}</span></p>
<p class="MsoNormal"><span>//&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">public</span> String<span></span><span class="SpellE"><b>getName</b></span>()</span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">{ return</span><span></span>name; }</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">public</span> String<span></span><span class="SpellE"><b>getPlace</b></span><b>()</b></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">{ return</span><span></span>place; }</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">public</span> String<span></span><b><span></span><span class="SpellE">getGame</span>()</b></span></p>
<p class="MsoNormal"><span><span></span><span class="GramE">{ return</span><span></span>game; }</span></p>
<p class="MsoNormal"><span>}</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;</span></p>
<p class="MsoNormal"><span><span></span>In demo2.jsp, we collect the data and then <span class="GramE">display<span></span>the</span> data<br />
entered by the user.</span></p>
<p class="MsoNormal"><span>Note that<br />
instead of {param.text1}, we are using {bean1.name}. We should carefully name<br />
the html form controls with the corresponding attribute names given in the<br />
bean. We cannot name the controls as &#039;text1&#039; etc, now!</span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span><span></span>value<b>=&quot;${bean1.name}&quot;<span></span></b>/&gt;</span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span><span></span>value=&quot;${bean1.place}&quot;<span></span>/&gt;</span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span><span></span>value=&quot;${bean1.game}&quot;<span></span>/&gt;</span></p>
<p class="MsoNormal"><span>&#8212;</span></p>
<p class="MsoNormal"><span><span></span>We get correct result.</span></p>
<p class="MsoNormal"><span>=============================================</span></p>
<p class="MsoNormal"><b><span>//<span></span>demo2.jsp</span></b><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;%@<br />
page <span class="SpellE">contentType</span>=&quot;text/html&quot; %&gt;</span></p>
<p class="MsoNormal"><span>&lt;%@<br />
<span class="SpellE">taglib</span> prefix=&quot;c&quot; </span></p>
<p class="MsoNormal"><span class="SpellE"><span>uri</span></span><span>=&quot;http://java.sun.com/jstl/core<span class="GramE">&quot;<span></span>%</span>&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;<span class="GramE">html</span>&gt;</span></p>
<p class="MsoNormal"><span>&lt;<span class="GramE">body</span>&gt;</span></p>
<p class="MsoNormal"><span>&lt;form<br />
method=post<span></span><span></span>action=&quot;demo2.jsp&quot;&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE">jsp<span class="GramE">:useBean</span></span> id=&quot;bean1&quot;<br />
class=&quot;<span class="SpellE">ourbeans.player</span>&quot;&gt;</span></p>
<p class="MsoNormal"><b><span>&lt;<span class="SpellE">jsp<span class="GramE">:setProperty</span></span></span></b><span>name=&quot;bean1&quot;<b><br />
property=&quot;*&quot;<span></span></b>/&gt;</span></p>
<p class="MsoNormal"><span>&lt;/<span class="SpellE">jsp<span class="GramE">:useBean</span></span>&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>Name<br />
&lt;input<span></span>type=text<span></span><b><span></span>name=&quot;name</b>&quot;&gt;&lt;<span class="SpellE">br</span>&gt;</span></p>
<p class="MsoNormal"><span>Place&lt;<span class="GramE">input<span></span>type</span>=text<span></span><b>name=&quot;place&quot;</b>&gt;&lt;<span class="SpellE">br</span>&gt;</span></p>
<p class="MsoNormal"><span>Game&lt;input<span></span>type=text<span></span><b>name=&quot;game&quot;</b>&gt;&lt;<span class="SpellE">br</span>&gt;</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span>&lt;input<br />
type=submit&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;/form&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>Name:<br />
<b>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span></b>value=<b>&quot;${bean1.name}&quot;</b><span></span>/&gt;&lt;<span class="SpellE">br</span>&gt;</span></p>
<p class="MsoNormal"><span>Place:<br />
&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span><br />
value=&quot;${bean1.place}&quot;<span></span>/&gt;&lt;<span class="SpellE">br</span>&gt;</span></p>
<p class="MsoNormal"><span>Game:<br />
&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span><br />
value=&quot;${bean1.game}&quot;<span></span>/&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;/body&gt;</span></p>
<p class="MsoNormal"><span>&lt;/html&gt;</span></p>
<p class="MsoNormal"><span>=============================================</span></p>
<p class="MsoNormal"><span>Once<br />
again, it will be noticed that there is no java code in this example, as<br />
everything is being done by tags, only<span class="GramE">..</span></span></p>
<p class="MsoNormal"><span>***********************************************</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>We<br />
are now ready to take up examples for <span class="GramE">&#039;condition&#039;<span></span>tags</span>.</span></p>
<p class="MsoNormal"><span><span></span>There are two types of &#039;condition tags&#039;.</span></p>
<p class="MsoNormal"><span class="GramE"><span>namely</span></span><span>, <b>&lt;<span class="SpellE">c:if</span>&gt;<span></span></b>&amp;<span></span><b>&lt;<span class="SpellE">c:choose</span></b>&gt;.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><b><span>In the<br />
third demo, we learn how to use the &lt;<span class="SpellE">c<span class="GramE">:if</span></span><span></span>tag</span></b><span>.</span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-</span></p>
<p class="MsoNormal"><span>/<b>/demo3.jsp</b></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;%@<br />
page <span class="SpellE">contentType</span>=&quot;text/html&quot; %&gt;</span></p>
<p class="MsoNormal"><span>&lt;%@<br />
<span class="SpellE">taglib</span> prefix=&quot;c&quot; <span class="SpellE">uri</span>=&quot;http://java.sun.com/jstl/core<span class="GramE">&quot;<span></span>%</span>&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;<span class="GramE">html</span>&gt;</span></p>
<p class="MsoNormal"><span>&lt;body<span></span><span class="SpellE">bgcolor</span>=<span class="SpellE">lightblue</span>&gt;</span></p>
<p class="MsoNormal"><span>&lt;form<span></span>method=post<span></span>action=demo3.jsp&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;select<span></span>name=&quot;combo1&quot;&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;option<span></span>value=&quot;<span class="SpellE">sam</span>&quot;&gt;<span class="SpellE">sam</span></span></p>
<p class="MsoNormal"><span><span></span>&lt;option<span></span><span></span>value=&quot;tom&quot;&gt;tom</span></p>
<p class="MsoNormal"><span>&lt;/select&gt;</span></p>
<p class="MsoNormal"><span>&lt;input<span></span>type=submit&gt;</span></p>
<p class="MsoNormal"><span>&lt;/form&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><b><span>&lt;<span class="SpellE">c<span class="GramE">:set</span></span><span></span></span></b><span class="SpellE"><span>var</span></span><span>=&quot;s&quot;<span></span>value<b>=&quot;${param.combo1}&quot;<span></span></b>/&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE"><b>c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></b></span><br />
value=&quot;${s}&quot;<span></span>/&gt;</span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE"><span class="GramE">br</span></span>&gt;</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><b><span>&lt;<span class="SpellE">c<span class="GramE">:if</span></span><span></span>test=&quot;${s<span></span><span class="SpellE">eq</span><span></span></span></b><span>&#039;<span class="SpellE">sam</span>&#039;<span></span><b>}&quot;<span></span>&gt; </b></span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span><span></span>value=&quot;Good<br />
Morning&#8230;SAM!&quot;<span></span>/&gt;</span></p>
<p class="MsoNormal"><b><span>&lt;/<span class="SpellE">c<span class="GramE">:if</span></span>&gt;</span></b></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><b><span>&lt;<span class="SpellE">c<span class="GramE">:if</span></span><span></span>test=&quot;${s<span></span></span></b><b><span><span></span>=<br />
=<span></span></span></b><span><span></span></span><span>&#039;tom&#039;<b>}&quot;<span></span></b>&gt;</span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> ut</span></span><span></span>value=&quot; How Are<br />
You?&#8230;.TOM!&quot;<span></span>/&gt;</span></p>
<p class="MsoNormal"><b><span>&lt;/<span class="SpellE">c<span class="GramE">:if</span></span>&gt;</span></b><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;/body&gt;</span></p>
<div>
<div style="border-style: none none solid;border-color: -moz-use-text-color -moz-use-text-color windowtext;border-width: medium medium 1pt;padding: 0in 0in 1pt">
<p class="MsoNormal" style="border: medium none;padding: 0in;text-align: justify"><span>&lt;/html&gt;</span></p>
<p class="MsoNormal" style="border: medium none;padding: 0in;text-align: justify"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></p>
<p class="MsoNormal" style="border: medium none;padding: 0in;text-align: justify"><span><span></span></span><span><span></span>There is a combo with two options, namely </span></p>
<p class="MsoNormal" style="border: medium none;padding: 0in;text-align: justify"><span>&#039;<span class="SpellE"><span class="GramE">sam</span></span>&#039; and &#039;tom&#039;. If the user<br />
selects &#039;<span class="SpellE">sam</span>&#039; and submits the form, he gets &#039;<span class="SpellE">GoodMorning</span> &#8230;SAM!&quot;. If he selects &#039;tom&#039; instead, he<br />
gets </span></p>
<p class="MsoNormal" style="border: medium none;padding: 0in;text-align: justify"><span>&#039;How<br />
are <span class="SpellE">you<span class="GramE">..</span>TOM</span>?<span class="GramE">&#039;.</span></span></p>
</div>
</div>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>The above code is no ‘Rocket-Science’ as<br />
American<span></span>authors <span class="SpellE">say!But</span><br />
, if we are careless<span></span>in typing the names<br />
‘<span class="SpellE">sam</span>’ or ‘tom’ in the test condition, we could spend<br />
hours together , trying to coax this code into functioning! We should not leave<br />
space after the single <span class="GramE">quote<span></span>in</span> the &#039;test expression&#039;. Second point worth noting in the above<br />
example is that we can use either <b>==</b><span class="GramE">( double</span> equal to) or <span class="SpellE"><b>eq</b></span><span></span>to test equality.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>***********************************************</span></p>
<p class="MsoNormal"><span>In<br />
the <b>fourth</b> example which follows, we take up &lt;<span class="SpellE">c<span class="GramE">:choose</span></span>&gt; tag.</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>The<br />
syntax is: </span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE"><span class="GramE">c:</span>choose</span> &gt; </span></p>
<p class="MsoNormal"><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:when</span></span><span></span>test=&quot;<span></span>&quot;<span></span>&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;<span class="SpellE">c<span class="GramE"> <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> therwise</span></span>&gt;<span></span>something<span></span>&lt;/<span class="SpellE">c:otherwise</span>&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;/<span class="SpellE">c<span class="GramE">:choose</span></span>&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>The<br />
peculiarity to be noted here is that<span></span>unlike &lt;<span class="SpellE">c<span class="GramE">:if</span></span> ,<br />
where we had to explicitly<span></span>use &lt;<span class="SpellE">c:out</span> for printing , </span><span>no such &lt;<span class="SpellE">c:out</span><br />
has been used here., and yet the result is displayed,</span></p>
<p class="MsoNormal"><span class="GramE"><span>because</span></span><span> &#039;choose&#039; includes &#039;displaying&#039;..</span></p>
<p class="MsoNormal"><span>When<br />
we choose &#039;7&#039;, &quot;<b>select between 1 &amp; <span class="GramE">5 <span style="font-weight: normal">&quot;</span></span></b> will be displayed!</span></p>
<p class="MsoNormal"><span><span></span></span></p>
<p class="MsoNormal"><span>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8211;</span></p>
<p class="MsoNormal"><b><span>/<span class="GramE">/<span></span>demo4.jsp</span></span></b></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;%@<br />
page <span class="SpellE">contentType</span>=&quot;text/html&quot; %&gt;</span></p>
<p class="MsoNormal"><span>&lt;%@<br />
<span class="SpellE">taglib</span> prefix=&quot;c&quot; <span class="SpellE">uri</span>=&quot;http://java.sun.com/jstl/core<span class="GramE">&quot;<span></span>%</span>&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span>&lt;<span class="GramE">html</span>&gt;</span></p>
<p class="MsoNormal"><span>&lt;body<span></span><span></span><span class="SpellE">bgcolor</span>=<span class="SpellE">lightblue</span>&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>&lt;form<span></span>method=<span class="GramE">post<span></span>action</span>=&quot;demo3.jsp&quot;&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>&lt;select name=&quot;combo1&quot;&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;option value=&quot;1&quot;&gt;1<span></span>&lt;/option&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;option value=&quot;2&quot;&gt;2<span></span>&lt;/option&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;option value=&quot;3&quot;&gt;3<span></span>&lt;/option&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;option value=&quot;4&quot;&gt;4<span></span>&lt;/option&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;option value=&quot;5&quot;&gt;5<span></span>&lt;/option&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;option value=&quot;7&quot;&gt;7<span></span>&lt;/option&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;/select&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>&lt;<span class="GramE">input<span></span>type</span>=submit&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p class="MsoNormal"><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:set</span></span><span class="SpellE">var</span>=&quot;s&quot;<span></span>value<b>=&quot;${param.combo1</b>}&quot;<span></span>/&gt;</span></p>
<p class="MsoNormal"><span>Today<br />
is</span></p>
<p class="MsoNormal"><span>&lt;<span class="SpellE"><span class="GramE">br</span></span>&gt;</span></p>
<p class="MsoNormal"><span>&lt;font<br />
size=24 color=red&gt;</span></p>
<p class="MsoNormal"><b><span>&lt;<span class="SpellE"><span class="GramE">c:</span>choose</span>&gt;</span></b></p>
<p class="MsoNormal"><b><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:when</span></span><span></span>test=&quot;${</span></b><span>s==1}&quot;&gt;Sunday<br />
<b><span></span>&lt;/<span class="SpellE">c:when</span>&gt;</b></span></p>
<p class="MsoNormal"><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:when</span></span><span></span>test=&quot;${s==2}&quot;&gt;Monday&lt;/<span class="SpellE">c:when</span>&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:when</span></span><span></span>test=&quot;${s==3}&quot;&gt;Tuesday&lt;/<span class="SpellE">c:when</span>&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:when</span></span><span></span>test=&quot;${s==4}&quot;&gt;Wednesday&lt;/<span class="SpellE">c:when</span>&gt;</span></p>
<p class="MsoNormal"><span><span></span>&lt;<span class="SpellE">c<span class="GramE">:when</span></span><span></span>test=&quot;${s==5}&quot;&gt;Thursday&lt;/<span class="SpellE">c:when</span>&gt;</span></p>
<p class="MsoNormal"><span></span></p>
<p>&lt;p class=&quot;MsoN</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/05/core-tags-in-jstl/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Accessing Portlet-specific Objects in JSP Pages</title>
		<link>http://www.javabeat.net/2011/04/accessing-portlet-specific-objects-in-jsp-pages/</link>
		<comments>http://www.javabeat.net/2011/04/accessing-portlet-specific-objects-in-jsp-pages/#comments</comments>
		<pubDate>Sat, 30 Apr 2011 00:18:09 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[JSP]]></category>
		<category><![CDATA[Portlets]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=697</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on Portlets in Action, to be published June 2011. I t is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><em>This article is based on <a href="http://www.manning.com/sarin/">Portlets in Action</a>, to be published June 2011. I t is being reproduced here by permission from <a href="http://www.manning.com">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) ebooks and pbooks. MEAPs are sold exclusively through Manning.com. All print book purchases include an ebook free of charge. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information.</em></p>
<p><center>Accessing Portlet-specific Objects Using defineObjects Tag</center></p>
<h2>Introduction</h2>
<div style="float: left;"></div>
<p>In a lot of cases, JavaServer Pages (<strong>JSP</strong>s) may rely on <strong>JSP</strong> implicit objects to achieve their functionality. It is perfectly fine to use <strong>JSP</strong> implicit variables in your <strong>JSP</strong> pages, but, on the downside, your <strong>JSP</strong> is dealing with servlet-specific objects (like HttpServletRequest and HttpSession) and not portlet-specific objects (like RenderRequest and PortletSession).</p>
<p>If we add an attribute to RenderRequest, it’s mirrored by HttpServletRequest and vice versa. The same applies to HttpSession and PortletSession. So what difference does it make if we use portlet-specific objects in <strong>JSP</strong>s? Subtle differences between servlet and portlet API can answer this question. For instance, in your <strong>JSP</strong> page, you can’t use HttpServletResponse to create a portlet URL (only a RenderResponse object provides methods to create portlet URLs). HttpServletRequest can’t provide the information about the portlet mode and the window state (PortletRequest provides methods to obtain the portlet mode and the window state). This is like rain and freezing rain—both are forms of precipitation with the only difference in what happens when raindrops hit the ground.</p>
<p>In general, your <strong>JSP</strong> pages will use a combination of portlet and servlet objects to generate content. For instance, if you want to set the expiration time for the content in the <strong>JSP</strong> page, you will use the RenderResponse portlet object. If you need to obtain the value of an APPLICATION_SCOPE portlet session attribute, you may prefer to use session (which refers to HttpSession object) or sessionScope (which is a java.util.Map of session attributes stored in HttpSession object) for a <strong>JSP</strong> implicit object to obtain its value.</p>
<h3><span style="color: red;">NOTE</span></h3>
<p><em><strong>JSP</strong>s included by <strong>portlets</strong> have access to <strong>JSP</strong> implicit objects because portlet application is also a web application.</em></p>
<p>The name <em>defineObjects</em> gives the impression that it can be used by <strong>JSP</strong> developers to define custom objects in their <strong>JSP</strong> pages, but that’s not the case. The defineObjects tag of portlet tag library provides <strong>JSP</strong>s with access to portlet objects like RenderRequest, RenderResponse, PortletSession, and so on. Table 1 lists the scripting variables (and their type) that are available to <strong>JSP</strong> pages that use defineObjects tag.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/125.jpg"><img class="aligncenter size-medium wp-image-1234" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/04/125-294x300.jpg" alt="" width="294" height="300" /></a>Table 1 shows the scripting variables defined by the defineObject tag. As you can see, defineObjects provides <strong>JSP</strong> pages with all Portlet 2.0 API objects they’ll ever need to use portlet-specific features. In <strong>JSP</strong> pages, you’ll usually use a combination of <strong>JSP</strong> implicit objects and the implicit objects made available by defineObjects tag. You&#8217;ll probably never use actionRequest, actionResponse, eventRequest, and eventResponse objects in your <strong>JSP</strong> pages because the portlet container ignores the content written out to the response in action and event processing phases.</p>
<h3><span style="color: red;">NOTE</span></h3>
<p><em>defineObjects tag doesn’t define any attributes.</em></p>
<p>The sample Book Catalog portlet in this article uses scripting variables introduced by defineObjects tag to show the debugging information, as shown earlier in figure 1.</p>
<p>Listing 1 shows debug.jsp page and is included by all JSP pages in the Book Catalog portlet. The debug.jsp page prints the information about the portlet mode, the window state, the value of myaction attribute from request, the content expiration time, and so on, most of which is obtained using scripting variables introduced by defineObjects tag.</p>
<p><strong><span style="color: red;">Listing 1 debug.jsp—Using variables introduced by defineObjects tag</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;%@ taglib prefix=&quot;portlet&quot; 						#1
		uri=&quot;http://java.sun.com/portlet_2_0&quot;%&gt; 			#1
	&lt;%@ page contentType=&quot;text/html&quot; isELIgnored=&quot;false&quot;
		import=&quot;javax.portlet.PortletSession&quot;%&gt;
	&lt;portlet:defineObjects /&gt; 						#2
	....
	Value of myaction request attribute:
		${requestScope.myaction} 					#3
	Portlet mode of request:
		&lt;%=renderRequest.getPortletMode()%&gt; 				#4
	Window state of request:
		&lt;%=renderRequest.getWindowState()%&gt; 				#5
	Content Expiration time:
		&lt;%=renderResponse.getCacheControl().getExpirationTime()%&gt; 	#6
	seconds
	uploadFolder init parameter value:
		&lt;%=portletConfig.getInitParameter(&quot;uploadFolder&quot;)%&gt; 		#7
	myaction attribute value in PortletSession:
		${portletSessionScope.myaction} 				#8
	Search criteria stored in PortletSession:
		Book name –
		&lt;%=portletSession.getAttribute(&quot;bookNameSearchField&quot;, 		#9
		PortletSession.APPLICATION_SCOPE)%&gt; 				#9
		Author name –
		&lt;%=session.getAttribute(&quot;authorNameSearchField&quot;)%&gt; 		#10
&nbsp;
		#1 Declare portlet tab library
		#2 defineObjects tag
		#3 myaction HttpRequest attribute
		#4 Portlet mode from RenderRequest
		#5 Window state from RenderRequest
		#6 Cache expiration time from RenderResponse
		#7 uploadFolder portlet initialization parameter
		#8 myaction PortletSession attribute
		#9 bookNameSearchField PortletSession attribute
		#10 authorNameSearchField HttpSession attribute</pre></td></tr></table></div>

<p>At #1, the JSP page declares the portlet tag library using the taglib directory. The value of the uri attribute is <a href="http://java.sun.com/portlet_2_0" target="_blank">http://java.sun.com/portlet_2_0</a> if you want to use Portlet 2.0 tag library. If you are using Portlet 1.0 tag library, specify the value of uri as <a href="http://java.sun.com/portlet" target="_blank">http://java.sun.com/portlet</a>. The defineObjects tag in Portlet 2.0 introduced additional variables like <strong>portletSessionScope</strong>, <strong>portletSession</strong>, and so on, which makes it easy to develop portlets using JSP as the view technology. At #2, the defineObjects tag is used to introduce scripting variables in the JSP page. At #3, the requestScope JSP implicit variable is used to obtain the value of the myaction attribute. At #4, the renderRequest variable is used to obtain the current portlet mode. At #5, the renderRequest variable is used to obtain the window state information. At #6, the renderResponse variable is used to obtain CacheControl object, which, in turn, is used to obtain the expiration time for the generated content. At #7, the portletConfig object is used to obtain the uploadFolder portlet initialization parameter. At #8, the <strong>portletSessionScope</strong> variable is used to obtain the value of the myaction attribute from PortletSession. At #9, the portletSession variable is used to obtain the value of the bookNameSearchField attribute from APPLICATION_SCOPE of PortletSession. At #10, the session <strong>JSP</strong> implicit variable is used to obtain the value of the authorNameSearchField attribute from HttpSession. We see here that using the session <strong>JSP</strong> implicit variable makes it easy to retrieve the APPLICATION_SCOPE attribute stored in PortletSession.</p>
<p>Listing 1 shows that we’ll usually use <strong>JSP</strong> implicit variables and variables introduced by the defineObjects tag to create <strong>JSP</strong> pages. If you browse through the pages of the Book Catalog portlet, the debugging information will change to reflect the current value of various attributes displayed by the debug.jsp page.</p>
<h2>Summary</h2>
<p>In this article, we saw how the portlet tag library tags can be used to simplify development of <strong>JSP</strong> pages used by portlets. Specifically, we learned how to use <strong>JSP</strong> implicit variables and variables introduced by the defineObjects tag to create <strong>JSP</strong> pages.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/04/accessing-portlet-specific-objects-in-jsp-pages/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
