<?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 6.0</title>
	<atom:link href="http://www.javabeat.net/category/java-j2ee/java-6-0/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Mon, 13 May 2013 20:10:23 +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>Mapping Java Objects and XML Documents using JAXB in Java 6.0</title>
		<link>http://www.javabeat.net/2007/06/mapping-java-objects-and-xml-documents-using-jaxb-in-java-6-0/</link>
		<comments>http://www.javabeat.net/2007/06/mapping-java-objects-and-xml-documents-using-jaxb-in-java-6-0/#comments</comments>
		<pubDate>Fri, 08 Jun 2007 02:11:23 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java 6.0]]></category>
		<category><![CDATA[JAXB]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3870</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>1) Introduction JAXB (Java API for XML Binding) technology which was included as part of JWSDP (Java Web Services Developer Pack) before, is now included with the Mustang Distribution. Simply put, it is a Mapping Technology for Java and XML Documents. Using JAXB, one can Generate XML Documents from Java Objects and also they can [...]</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><h2>1) Introduction</h2>
<p align="justify"><strong><em>JAXB (Java API for XML Binding)</em></strong> technology which was included as part of <strong><em>JWSDP (Java Web Services Developer Pack)</em></strong> before, is now included with the Mustang Distribution. Simply put, it is a <strong><em>Mapping Technology</em></strong> for Java and XML Documents. Using JAXB, one can <strong><em>Generate XML Documents</em></strong> from Java Objects and also they can <strong><em>Construct Java Objects</em></strong> from one or more XML Documents. In JAXB terms, <strong><em>Marshalling</em></strong> refers to the process of converting a Java Object to a XML Document and <strong><em>Un-Marshalling</em></strong> is the reverse of Marshalling which is simply getting a Java Object from one or more XML Documents.</p>
<p align="justify">Let us see along with Samples how to work with Marshalling and Un-Marshalling with JAXB.</p>
<blockquote>
<p align="justify"><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a href="http://www.javabeat.net/2007/06/java-6-0-features-part-2-pluggable-annotation-processing-api/">Introduction to Java 6.0 New Features, Part–2</a></li>
<li><a href="http://www.javabeat.net/category/java-j2ee/java-8-0/">What is new in Java 8.0?</a></li>
</ul>
</blockquote>
<h2>2) Generating XML Documents from Java Objects</h2>
<p align="justify">Assume that you want to have a XML Representation of a Java object. Using JAXB Marshalling you can do with much ease and the following Sample Application illustrates the same,</p>
<p><strong>Person.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.jaxb;

import java.util.Date;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement()
public class Person {

    private String name;
    private int age;
    private Date dateOfBirth;
    private String type;

    public Person(){
    }

    public Person(String name, int age, Date dateOfBirth, String type) {
        this.name = name;
        this.age = age;
        this.dateOfBirth = dateOfBirth;
        this.setType(type);
    }

    @XmlElement()
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlElement()
    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @XmlElement()
    public Date getDateOfBirth() {
         return dateOfBirth;
    }

    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }

    @XmlAttribute()
    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}</pre>
<p align="justify">The above Person class has various properties namely <strong><em>&#8216;name&#8217;</em></strong>, <strong><em>&#8216;age&#8217;</em></strong>, <strong><em>&#8216;dateOfBirth&#8217;</em></strong> and <strong><em>&#8216;type&#8217;</em></strong> and objects of this Class are the targets we wish to Marshal. The Person class is annotated with @XmlRootElement since we want the name of the Class to be the Root Node. We want <strong><em>&#8216;name&#8217;</em></strong>, <strong><em>&#8216;age&#8217;</em></strong>, and <strong><em>&#8216;dateOfBirth&#8217;</em></strong> as Child Elements so it has been tagged with @XmlElement. Since we want <strong><em>&#8216;type&#8217;</em></strong> to appear as an Attribute we had tagged that as @XmlAttribute.</p>
<p><strong>Java2XML.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.jaxb;

import java.io.FileWriter;
import java.util.*;
import javax.xml.bind.*;

public class Java2XML {

    public Java2XML() {
    }

    public static void main(String args[]) throws Exception{
        JAXBContext context = JAXBContext.newInstance(Person.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Person person = new Person(
            &quot;Anonymous&quot;, 32, new Date(1970, 1, 10), &quot;employee&quot;);
        marshaller.marshal(person, new FileWriter(&quot;.\\src\\Person.xml&quot;));
    }
}</pre>
<p align="justify">JAXBContext serves as the <strong><em>Entry Point</em></strong> for making use of the JAXB API. It is initiated by the list of Class objects whose objects want to be represented as XML Documents. Then an instance of Marshaller is created by calling JAXBContext.createMarshaller() method. The Java object of type Person is marshalled into the XML Document by calling the Marshaller.marshall() method. Since we want the XML Document to look <strong><em>Well-indented</em></strong>, we have set the property Marshaller.JAXB_FORMATTED_OUTPUT to true.</p>
<p align="justify">A file named Person.xml would have got generated and following is the listing of that file,</p>
<p><strong>Person.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot; standalone=&quot;yes&quot;?&gt;
&lt;person type=&quot;employee&quot;&gt;
    &lt;age&gt;32&lt;/age&gt;
    &lt;dateOfBirth&gt;1970-01-10 T00:00:00+05:30&lt;/dateOfBirth&gt;
    &lt;name&gt;Anonymous&lt;/name&gt;
&lt;/person&gt;</pre>
<h2>3) Representing Java Objects from XML Documents</h2>
<p align="justify">In the previous section, we saw how to generate an XML Document from a Java Object. Now, let us see the <strong><em>Unmarshalling</em></strong> process here. As mentioned, <strong><em>Unmarshalling</em></strong> is the process of representing Java Objects from a XML Document. The process of Unmarshalling is a bit complicated as so many steps are involved. Let us break the steps one by one in greater detail.</p>
<h3>3.1) Creating the XML Schema Definition File</h3>
<p align="justify">If <strong><em>Java Classes</em></strong> represent the templates wherein objects can be created for a particular type, then in XML World, it is the <strong><em>XML Schema Definition File</em></strong> through which XML Document Instances can be instantiated. The first thing before creating a XML Document is to create a <strong><em>XML Schema</em></strong> and then to attach the Schema to a XML Document Instance. Let us look into a sample XML Schema File called Items, which will contain a list of <strong><em>&#8216;Item&#8217;</em></strong> Elements along with its <strong><em>&#8216;Name&#8217;</em></strong> and <strong><em>&#8216;Price&#8217;</em></strong>. Following is the listing of that File.</p>
<p><strong>Items.xsd</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;xs:schema xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot; elementFormDefault=&quot;qualified&quot;&gt;

&lt;xs:element name=&quot;Items&quot;&gt;
    &lt;xs:complexType&gt;
        &lt;xs:sequence&gt;
            &lt;xs:element maxOccurs=&quot;unbounded&quot; ref=&quot;Item&quot;/&gt;
        &lt;/xs:sequence&gt;
    &lt;/xs:complexType&gt;
&lt;/xs:element&gt;

&lt;xs:element name=&quot;Item&quot;&gt;
    &lt;xs:complexType&gt;
        &lt;xs:sequence&gt;
            &lt;xs:element ref=&quot;Name&quot;/&gt;
            &lt;xs:element ref=&quot;Price&quot;/&gt;
        &lt;/xs:sequence&gt;

        &lt;xs:attribute name=&quot;id&quot; use=&quot;required&quot; type=&quot;xs:NCName&quot;/&gt;
    &lt;/xs:complexType&gt;

&lt;/xs:element&gt;
    &lt;xs:element name=&quot;Name&quot; type=&quot;xs:string&quot;/&gt;
    &lt;xs:element name=&quot;Price&quot; type=&quot;xs:string&quot;/&gt;
&lt;/xs:schema&gt;</pre>
<p align="justify">The above is the XML Schema Definition File which represents a list of Items. Since <strong><em>&#8216;Items&#8217;</em></strong> element contain a list of Item elements and <strong><em>&#8216;Item&#8217;</em></strong> element in turn contains both <strong><em>&#8216;Name&#8217;</em></strong> and <strong><em>&#8216;Price&#8217; </em></strong> Element, both these elements are Composite Elements and the same is represented by <strong><em>complexType</em></strong> elements.</p>
<h3>3.2) Generating Java Files from the Schema Definition Files</h3>
<p align="justify">Now, its time to generate the Java Source Files from this XML Schema Definition File. Mustang comes with a Utility called <strong><em>xjc (which stands for XML to Java Compiler)</em></strong> which generates Java Source Files when given a XML Schema File. Xjc is nothing but a bat file location in the bin directory of the Java 6 Installation Path. Run the following command to generate the Java Source Files.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">xjc –p net.javabeat.articles.java6.newfeatures.jaxb Items.xsd</pre>
<p align="justify">The only argument to xjc is the name of the <strong><em>XML Schema File</em></strong> which is represented by Items.xsd and the ‘-p’ option specifies the package to which the generated Java Files have to be associated. This results is the generation of the following source files.</p>
<p><strong>Item.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.jaxb;

import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.*;
import net.javabeat.articles.java6.newfeatures.jaxb.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = &quot;&quot;, propOrder = {
    &quot;name&quot;,
    &quot;price&quot;
})
@XmlRootElement(name = &quot;Item&quot;)
public class Item {

    @XmlElement(name = &quot;Name&quot;)
    protected String name;
    @XmlElement(name = &quot;Price&quot;)
    protected String price;
    @XmlAttribute(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String id;

    public String getName() {
        return name;
    }

    public void setName(String value) {
        this.name = value;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String value) {
        this.price = value;
    }

    public String getId() {
        return id;
    }

    public void setId(String value) {
        this.id = value;
    }
}</pre>
<p align="justify">This file is just a Data file for the corresponding <strong><em>&#8216;Item&#8217;</em></strong> element which contains getter and setter methods with properly instructed Annotations. Note that the two sub-elements namely <strong><em>‘name’</em></strong> and <strong><em>‘type’</em></strong> has been tagged with @XmlElement Annotation and the attribute <strong><em>‘id’</em></strong> has been tagged with @XmlAttribute Annotation.</p>
<p><strong>Items.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.jaxb;

import java.util.*;
import javax.xml.bind.annotation.*;
import net.javabeat.articles.java6.newfeatures.jaxb.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = &quot;&quot;, propOrder = {
    &quot;item&quot;
})
@XmlRootElement(name = &quot;Items&quot;)
public class Items {

    @XmlElement(name = &quot;Item&quot;)
    protected List&lt;Item&gt; item;

    public List&lt;Item&gt; getItem() {
        if (item == null) {
            item = new ArrayList&lt;Item&gt;();
        }
        return this.item;
    }
}</pre>
<p align="justify">This is the <strong><em>Container Class</em></strong> for the Item element and it just contains a getter for the Item object. Note how the list of <strong><em>&#8216;Item&#8217;</em></strong> elements in the Schema Document has been mapped to List of Item (List&lt;Item&gt;) elements. This is the <strong><em>Default Mapping</em></strong> given by the Sun&#8217;s Reference Implementation for JAXB.</p>
<p><strong>ObjectFactory.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.jaxb;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import net.javabeat.articles.java6.newfeatures.jaxb.Item;
import net.javabeat.articles.java6.newfeatures.jaxb.Items;
import net.javabeat.articles.java6.newfeatures.jaxb.ObjectFactory;

@XmlRegistry
public class ObjectFactory {

    private final static QName _Price_QNAME = new QName(&quot;&quot;, &quot;Price&quot;);
    private final static QName _Name_QNAME = new QName(&quot;&quot;, &quot;Name&quot;);

    public ObjectFactory() {
    }

    public Item createItem() {
        return new Item();
    }

    public Items createItems() {
        return new Items();
    }

    @XmlElementDecl(namespace = &quot;&quot;, name = &quot;Price&quot;)
    public JAXBElement&lt;String&gt; createPrice(String value) {
        return new JAXBElement&lt;String&gt;(_Price_QNAME, String.class, null, value);
    }

    @XmlElementDecl(namespace = &quot;&quot;, name = &quot;Name&quot;)
    public JAXBElement&lt;String&gt; createName(String value) {
        return new JAXBElement&lt;String&gt;(_Name_QNAME, String.class, null, value);
    }

}</pre>
<p align="justify">As guessed from its name, this is the <strong><em>Factory Class</em></strong> for creating various elements like <strong><em>&#8216;Items&#8217;</em></strong>, <strong><em>&#8216;Item&#8217;</em></strong>, <strong><em>&#8216;Name&#8217;</em></strong> and <strong><em>Price&#8217;</em></strong>. Appropriate methods are available for creating <strong><em>&#8216;Items&#8217;</em></strong>, <strong><em>&#8216;Item&#8217;</em></strong>, <strong><em>&#8216;Name&#8217;</em></strong> and <strong><em>&#8216;Price&#8217;</em></strong> in the form of ObjectFactory.createItems(), ObjectFactory.createItem(), ObjectFactory.createName() and ObjectFactory.createPrice() respectively.</p>
<h3>3.3) Creating a Sample XML Document</h3>
<p align="justify">Now let us create a Sample XML Document against the Schema Definition File Items.xsd. Following is the sample XML file called Items.xml. Note how the XML Document Instance is related with the XML Schema Definition File with the help of <strong><em>‘xsi:noNamespaceSchemaLocation’</em></strong> attribute.</p>
<p><strong>Items.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;Items xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
  xsi:noNamespaceSchemaLocation='file:C:/Items.xsd'&gt;

    &lt;Item id=&quot;LAP001&quot;&gt;
        &lt;Name&gt;Laptop&lt;/Name&gt;
        &lt;Price&gt;4343$&lt;/Price&gt;
    &lt;/Item&gt;

    &lt;Item id=&quot;TV001&quot;&gt;
        &lt;Name&gt;Television&lt;/Name&gt;
        &lt;Price&gt;433$&lt;/Price&gt;
    &lt;/Item&gt;

    &lt;Item id=&quot;DVD001&quot;&gt;
        &lt;Name&gt;DVD Player&lt;/Name&gt;
        &lt;Price&gt;763$&lt;/Price&gt;
    &lt;/Item&gt;

&lt;/Items&gt;
	</pre>
<h3>3.4) Unmarshalling the XML Document to construct the Java object</h3>
<p align="justify">The code to Unmarshall the XML Document is given below. The code first represents a JAXBContext object by passing in a <strong><em>Context Path</em></strong> which is usually the package name where the compiled Java Class files are located. Then an Unmarshaller object is created by calling JAXBContext.createUnmarshaller() which does the unmarshalling operation by calling the Unmarshaller.unmarshall() method passing in the XML File. Then the object is iterated over the get the actual data contents from the XML File.</p>
<p><strong>XML2Java.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.jaxb;

import java.io.*;
import javax.xml.bind.*;

public class XML2Java {

    public static void main(String args[]) throws Exception{

        JAXBContext context = JAXBContext.newInstance(
            &quot;net.javabeat.articles.java6.newfeatures.jaxb&quot;);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        Items items = (Items)unmarshaller.unmarshal(
            new FileReader(&quot;.\\src\\Items.xml&quot;));
        List listOfItems = items.getItem();
        for(Item item : listOfItems){
            System.out.println(&quot;Name = &quot; + item.getName() +
                &quot;, Price = &quot; + item.getPrice() + &quot;, Id = &quot; + item.getId());
       }
    }
}</pre>
<p>Following is the output of the above program</p>
<pre class="brush: java; title: ; notranslate">Name = Laptop, Price = 4343$, Id = LAP001
Name = Television, Price = 433$, Id = TV001
Name = DVD Player, Price = 763$, Id = DVD001 </pre>
<h2>4) Conclusion</h2>
<p align="justify">This article covered the leftover features of the <a href="http://www.javabeat.net/2007/06/introduction-to-java-6-0-new-features-part-i/">Part I New features of Java 6</a>. Starting with <strong><em>Pluggable Annotation Processing API</em></strong>, it covered what Annotations are, then guided us how to write <strong><em>Custom Annotations</em></strong> and <strong><em>Custom Annotation Processor</em></strong>. Then it traversed over the <strong><em>Cursor API</em></strong> and the <strong><em>Event Iterator API</em></strong> of StaX such as how to read XML Documents along with well-defined samples. Finally through <strong><em>Java API for XML Binding</em></strong>, it details how to map Java and XML Documents with some sample applications.</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%2Fjava-6-0%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/java-6-0/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/java-6-0/feed/" data-count="vertical" data-text="Java 6.0" 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/2007/06/mapping-java-objects-and-xml-documents-using-jaxb-in-java-6-0/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>JDBC 4.0 API in Java 6.0</title>
		<link>http://www.javabeat.net/2007/06/new-features-in-jdbc-api-java-6-0/</link>
		<comments>http://www.javabeat.net/2007/06/new-features-in-jdbc-api-java-6-0/#comments</comments>
		<pubDate>Thu, 07 Jun 2007 01:50:44 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java 6.0]]></category>
		<category><![CDATA[JDBC 4.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=3863</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>1) Introduction Java Database Connectivity allows Application Programs to interact with the Database to access the Relational Data. JDBC provides the Pluggable Architecture wherein any type of Java Compliant Drivers can be plugged-in even during the run-time. The JDBC API provides functionality to establish Connection to the back-end Database session which can execute the Queries [...]</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><h2>1) Introduction</h2>
<p align="justify"><strong><em>Java Database Connectivity</em></strong> allows Application Programs to interact with the Database to access the <strong><em>Relational Data</em></strong>. <strong><em>JDBC</em></strong> provides the <strong><em>Pluggable Architecture</em></strong> wherein any type of <strong><em>Java Compliant Drivers</em></strong> can be plugged-in even during the run-time. The <strong>JDBC API</strong> provides functionality to establish Connection to the back-end Database session which can execute the <strong><em>Queries</em></strong> to get the <strong><em>Results</em></strong>. The new version of JDBC that comes along with Mustang (Java 6.0) is <strong><em>JDBC 4.0</em></strong>. JDBC 4.0 is one of the areas that were great affected with the new set of features. Let us look into the major features one by one. The specification of the JDBC 4.0 is maintained under <a href="http://jcp.org/en/jsr/detail?id=221" target="_blank">JSR 221</a>.</p>
<p align="justify">There about twenty features are introduced in the <strong>JDBC 4.0</strong>. The overall features can be categorize under the following four topics:</p>
<ol>
<li>Driver and connection management</li>
<li>Exception handling</li>
<li>Data type support</li>
<li>API changes</li>
</ol>
<p>In this article we explore some of the features mostly used by the programmers. If you have any questions, please post it in the comments section.</p>
<blockquote>
<ul>
<li><a href="http://www.javabeat.net/2007/06/introduction-to-java-6-0-new-features-part-i/">Introduction to Java 6.0 New Features, Part–1</a></li>
<li><a href="http://www.javabeat.net/2007/06/java-6-0-features-part-2-pluggable-annotation-processing-api/">Introduction to Java 6.0 New Features, Part–2</a></li>
<li><a href="http://www.javabeat.net/category/java-j2ee/java-8-0/">What is new in Java 8.0?</a></li>
</ul>
</blockquote>
<h2>2) No need for Class.forName(&#8220;DriverName&#8221;)</h2>
<p align="justify">Before the advent of <strong>JDBC 4.0</strong>, Application Programmers have to manually load the <strong><em>Database Driver</em></strong> before making any <strong><em>Database Calls</em></strong>. The following code shows how to load a Database Driver before <strong>JDBC 4.0</strong></p>
<pre class="brush: java; title: ; notranslate">Class.forName(&quot;FullyQualifiedNameOfTheDriverClass&quot;);</pre>
<p align="justify">This has one major dis-advantage. Suppose if the Database Driver Vendor wishes to change the class name of the Driver, then it will result in Code change. But with the help of <strong><em>Service Provider Mechanism</em></strong> (which is available from Java 5), there is no need for the programmers to manually load the Driver. The Driver will be <strong><em>Loaded Automatically</em></strong> by the JVM if the Jar files that correspond to the Driver Class are in the appropriate class path.</p>
<p align="justify">Let us explain how the <strong><em>Service Provider Mechanism</em></strong> works. Two entities are of much interest in the Service Provider Mechanism. One is the <strong><em>Service</em></strong> itself which mostly contains a set of interfaces that deals with what the Service is all about and the other one is the <strong><em>Provider</em></strong> who will give a concrete and a well-defined Implementation for the Service. This Mechanism forces the Provider to package the service as a Jar which has to maintain a <strong><em>Directory Structure</em></strong> like this,</p>
<pre class="brush: java; title: ; notranslate">\\META-INF\\services\\FullNameOfTheService</pre>
<p align="justify">Suppose if the JDBC Driver Provider wishes to make his implementation as a Service, then the Vendor should maintain a Directory Structure along with the file name like this,</p>
<pre class="brush: java; title: ; notranslate">\\META-INF\\services\\java.sql.Driver</pre>
<p align="justify">Note that java.sql.Driver is the name of the File, and the file should contain only one entry which is the <strong><em>Name of the Provider Class</em></strong> that implements the Driver. For example, in the case of My SQL, the content of the file will be looking like the following,</p>
<p><strong>File &#8211; Java.sql.Driver</strong></p>
<pre class="brush: java; title: ; notranslate">com.mysql.jdbc.Driver           # Class name of the Driver</pre>
<p align="justify">Through this mechanism, the JDBC Drivers will get <strong><em>Automatically Loaded by the Java Program</em></strong>. If there are <strong><em>Multiple Drivers</em></strong> in the Application’s class-path, then the first matching Driver will be taken into consideration and the rest of them will just be ignored.</p>
<h2>3) Changes in Connection and Statement Interface</h2>
<p align="justify">Certain new useful methods are added to the Connection interface. The following sections list down the commonly used methods. To check whether an Connection object is still valid/active or not, then the following method can be used,</p>
<pre class="brush: java; title: ; notranslate">int tenSeconds = 10;
Connection.isValid(tenSeconds);</pre>
<p align="justify">The argument to Connection.isValid(int) is the <strong><em>Timeout value</em></strong>, which specifies the time duration the API should take to find out whether the Connection is valid. If the timeout interval exceeds, then false will be returned. A value of 0 for the time-out interval specifies an <strong><em>Infinite Time-out Duration</em></strong>.</p>
<p align="justify">Also there are methods for populating and retrieving the <strong><em>Client Information</em></strong> that a particular Driver supports with the help of Connection.getClientInfo() and Connection.setClientInfo(Properties) methods. Client information can also be set and retrieved individually using Connection.setClientInfo(String,String) and Connection.getClientInfo(String) methods.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
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 align="justify">The following methods are added into the Statement interface, Statement.isClosed(), Statement.setPoolable(boolean) and Statement.isPoolable(). Statement.isClosed() will return true if the Statement Object is closed by calling the Statement.close() method. By default, only PreparedStatement and CallableStatement are pooled by the Implementation. The call to Statement.setPoolable(true) will only act as a request to the Implementation to pool this Statement Object for better performance. Not all the implementations may support this feature and hence Applications should not depend on this feature always.</p>
<h2>4) Enhanced SQL Exception Handling</h2>
<p align="justify">Exception handling in JDBC has been enhanced a lot in JDBC 4.0. The following are the major areas where the enhancements are done.</p>
<ul>
<li>Iterable SQL Exception</li>
<li>Concreate Sub Classes for specific SQL Exception</li>
</ul>
<h3>4.1) Iterable SQL Exception</h3>
<p align="justify">The java.sql.SQLException now implements the Iterable&lt;Throwable&gt; interface which means that it can be iterated over to get the <strong><em>Next Set of Exceptions</em></strong> and can also be used in <strong><em>Enhanced For-Loops</em></strong> (available from Java 5.0). Consider the following piece of code,</p>
<pre class="brush: java; title: ; notranslate">try{

     // Some Database Access Code

}catch(SQLException exception){

    for(Throwable throwable: exception){
        System.out.println(throwable.getMessage());

    }
}</pre>
<p align="justify">Before JDBC 4.0, Applications depended on SQLException.getNextException() to get the next Exception and looped over until the returned exception is not null.</p>
<pre class="brush: java; title: ; notranslate">try{

     // Some Database Access Code

}catch(SQLException exception){

    System.out.println(exception.getMessage());
    SQLException nextException = exception.getNextException();

    while (nextException != null){
        System.out.println(nextException.getMessage());
        nextException = nextException.getNextException();
    }
}</pre>
<h3>4.2) Concreate Sub Class for specific SQL Exception</h3>
<p align="justify">More number of <strong><em>SQL Exception related Sub-Classes</em></strong> are added to the API which encapsulates the <strong><em>State of the SQL Error</em></strong>. In general, these Exceptions fall into 3 categories namely <strong><em>Transient</em></strong>, <strong><em>Recoverable</em></strong> and <strong><em>Non-Transient</em></strong>.</p>
<p align="justify">Assume that some kind of SQL Exception has occurred during the Program run-time. If again when a try is made and if there is a possibility such that the program can recover from the Exception without making any application specific change, then it is a kind of <strong><em>Transient Exception</em></strong>. This exception is represented by the java.sql.TransientException class and the following are the identified Transient Exceptions in the JDBC 4.0 API.</p>
<ul>
<li>SQLTimeoutException</li>
<li>SQLTransactionRollbackException</li>
<li>SQLTransientConnectionException</li>
</ul>
<p align="justify">Minute variation of this Transient Exception is the <strong><em>Recoverable Exception</em></strong> which is represented by java.sql.SQLRecoverableException. Here the exception that has happened can be recovered by performing some <strong><em>Application Specific Recovery</em></strong>.</p>
<p align="justify">The last flavour of SQL Exception is the <strong><em>Non-Transient Exception</em></strong> and it is represented by java.sql.TransientException. It tells that an exception can never be recovered even though <strong><em>Infinite Number of Tries</em></strong> is performed by the Application Program. The following are the Exceptions available in this Category,</p>
<ul>
<li>SQLDataException</li>
<li>SQLFeatureNotSupportedException</li>
<li>SQLIntegrityConstraintViolationException</li>
<li>SQLInvalidAuthorizationSpecException</li>
<li>SQLNonTransientConnectionException</li>
<li>SQLSyntaxErrorException</li>
</ul>
<h3>4.3) Support for SQL RowId</h3>
<p align="justify">Most of the popular Databases support the concept of a <strong><em>Row Id</em></strong>. A Row Id is an unique Identifier which is used to identify a Row. Support for Retrieving and setting the Row Id for a row is made available from JDBC 4.0 version. For example, consider the following piece of code, which will retrieve the value of the Row Id for a particular Row.</p>
<pre class="brush: java; title: ; notranslate">String selectQuery = &quot; select rowid from Employees where id ='123' &quot;;
ResultSet resultSet = statement.executeQuery(&quot;selectQuery&quot;);
java.sql.Rowid rowId = resultSet.getRowId();</pre>
<p align="justify">The <strong><em>Row Id</em></strong> is represented by java.sql.RowId class. Before doing any kind of manipulation on the Row Id, it is wise to check whether the under-lying Database implementation provides <strong><em>Support for Row Id(s)</em></strong>, as well as the <strong><em>Lifetime of the Row Id</em></strong> objects. The life-time of the Row Id determines how long the Row Id is valid, whether the Row Id exists only for a particluar <strong><em>Session</em></strong> or for a <strong><em>Set of Transactions</em></strong> within a Session or <strong><em>Outside the Database Session</em></strong> etc. This availability can be known with the help of DatabaseMetaData like the following,</p>
<pre class="brush: java; title: ; notranslate">RowIdLifeTime rowIdLifeTime = DatabaseMetaData.getRowIdLifetime();

if (rowIdLifeTime != ROWID_UNSUPPORTED){
    // Row Id support is there for this Data source.
}</pre>
<p align="justify">The returned RowIdLifeTime is an <strong><em>Enum</em></strong> which tells about the <strong><em>Life-Time of the Row Id</em></strong> object. Possible values are ROWID_UNSUPPORTED, ROWID_VALID_FOREVER, ROWID_VALID_OTHER, ROWID_VALID_SESSION, ROWID_VALID_TRANSACTION and ROWID_VALID_FOREVER.</p>
<h2>5) Conclusion</h2>
<p align="justify">The new existing features of <strong><em>JDBC 4.0</em></strong> like the <strong><em>Automatic Driver Loading</em></strong>, various new methods added to <strong><em>Connection/Statement</em></strong> interface and <strong><em>Enhanced SQL Exception Handling</em></strong> are also explained.</p>
<p align="justify">If you are interested in buying a good book for learning JDBC API, <a href="http://www.flipkart.com/database-programming-jdbc-java-8173662894/p/itmdyjf2vdxzfggj?pid=9788173662898&amp;affid=suthukrish" target="_blank">database programming with JSDBC and Java</a> is one of the popular book for JDBC, if you need more options, please refer our recommended <strong><a href="http://www.javabeat.net/java-books/" target="_blank">java books</a></strong> section for the complete list of books. Hope this helps. <strong>If you are interested in receiving our future Java articles, please subscribe <a href="http://www.javabeat.net/subscribe/">here</a>.</strong></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/2007/06/new-features-in-jdbc-api-java-6-0/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java 6.0 Features Part &#8211; 2 : Pluggable Annotation Processing API</title>
		<link>http://www.javabeat.net/2007/06/java-6-0-features-part-2-pluggable-annotation-processing-api/</link>
		<comments>http://www.javabeat.net/2007/06/java-6-0-features-part-2-pluggable-annotation-processing-api/#comments</comments>
		<pubDate>Wed, 06 Jun 2007 12:28:39 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java / J2EE]]></category>
		<category><![CDATA[Java 6.0]]></category>
		<category><![CDATA[JAXB]]></category>
		<category><![CDATA[JAXB Binding]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=33</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>1) Introduction The first part of this article listed out the major new features of Java 6 (Mustang) related to areas like Common Annotations (JSR 250), Scripting Language for the Java Platform (JSR 223) and JDBC 4.0. This article assumed that Readers have got sufficiently fair bit of knowledge in the various concepts of Java [...]</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><h2>1) Introduction</h2>
<p align="justify">The first part of this article listed out the major new features of <strong><em>Java 6 (Mustang)</em></strong> related to areas like <strong><em>Common Annotations (JSR 250)</em></strong>, <strong><em>Scripting Language for the Java Platform (JSR 223)</em></strong> and <strong><em>JDBC 4.0</em></strong>. This article assumed that Readers have got sufficiently fair bit of knowledge in the various concepts of Java 5.0. First-time Readers of Java 6 are strongly encouraged to read the first part of this article titled <a href="http://www.javabeat.net/2007/06/introduction-to-java-6-0-new-features-part-i/">&#8220;Introduction to Java 6.0 New Features, Part–I&#8221;</a>. This article covers the left-over features of Part-I. More specifically, it will cover the <strong><em>Pluggabable Annotation Processing API (JSR 269)</em></strong>, <strong><em>Java API for XML Binding (JSR 222)</em></strong> and <strong><em>Streaming API for XML (JSR 173)</em></strong>.</p>
<h2>2) Pluggable Annotation Processing API</h2>
<h3>2.1) Introduction to Annotation</h3>
<p align="justify"><strong><em>Annotations</em></strong> have been there in the Java World from Java 5.0. Java Annotations are a result of the <strong><em>JSR 175</em></strong> which aimed in providing a <strong><em>Meta-Data Facility</em></strong> to the <strong><em>Java Programming Language</em></strong>. It can be greatly used by the Build-time Tools and Run-time Environments to do a bunch of useful tasks like <strong><em>Code Generation</em></strong>, <strong><em>Validation</em></strong> and other valuable stuffs. Java 6 has introduced a new JSR called <strong><em>JSR 269</em></strong>, which is the <strong><em>Pluggable Annotation Processing API</em></strong>. With this API, now it is possible for the Application Developers to write a <strong><em>Customized Annotation Processor</em></strong> which can be plugged-in to the code to operate on the set of Annotations that appear in a Source File.</p>
<p align="justify">Let us see in the subsequent sections how to write a Java File which will make use of Custom Annotations along with a Custom Annotation Processor to process them.</p>
<h3>2.2) Writing Custom Annotations</h3>
<p align="justify">This section provides two <strong><em>Custom Annotations</em></strong> which will be used by a Sample Java File and a <strong><em>Custom Annotation Processor</em></strong>. One is the <strong><em>Class Level Annotation</em></strong> and the other is the <strong><em>Method Level Annotation</em></strong>. Following is the listing for both the Annotation Declarations. See how the <strong><em>Targets</em></strong> for the Annotations ClassLevelAnnotation.java and MethodLevelAnnotation.java are set to ElementType.TYPE and ElementType.METHOD respectively.</p>
<p><strong>ClassLevelAnnotation.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.customannotations;

import java.lang.annotation.*;

@Target(value = {ElementType.TYPE})
public @interface ClassLevelAnnotation {
}
</pre>
<p><strong>MethodLevelAnnotation.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.customannotations;

import java.lang.annotation.*;

@Target(value = {ElementType.METHOD})
public @interface MethodLevelAnnotation {
}
</pre>
<p><strong>AnnotatedJavaFile.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.customannotations;

@ClassLevelAnnotation()
public class AnnotatedJavaFile {

    @MethodLevelAnnotation
    public void annotatedMethod(){
    }
}</pre>
<p align="justify">The above is a Sample Java File that makes use of the Class Level and the Method Level Annotations. Note that @ClassLevelAnnotation is applied at the Class Level and the @MethodLevelAnnotation is applied at the method Level. This is because both the Annotation Types have been defined to be tagged to these respective Elements only with the help of @Target Annotation.</p>
<h3>2.3) Writing a Simple Custom Annotation Processor</h3>
<p><strong>TestAnnotationProcessor.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.customannotations;

import java.util.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;

@SupportedAnnotationTypes(value= {&quot;*&quot;})
@SupportedSourceVersion(SourceVersion.RELEASE_6)

public class TestAnnotationProcessor extends AbstractProcessor  {

    @Override
    public boolean process(
        Set&lt;?&gt; extends TypeElement&gt; annotations, RoundEnvironment roundEnv){

        for (TypeElement element : annotations){
            System.out.println(element.getQualifiedName());
        }
        return true;
    }
}</pre>
<p align="justify">Let us discuss the core points in writing a <strong><em>Custom Annotation Processor</em></strong> in Java 6. The first notable thing is that Test Annotation Processor class extends AbstractProcessor class which encapsulates an Abstract Annotation Processor. We have to inform what Annotation Types our Test Annotation Processor Supports. This is manifested through the Class-Level Annotation called @SupportedAnnotationTypes(). A value of &#8220;*&#8221; indicates that all types of Annotations will be processed by this Annotation Processor. Which version of <strong><em>Source Files</em></strong> this Annotation Processor supports is mentioned through @SupportedSourceVersion Annotation.</p>
<p align="justify">The javac compiler of Mustang has an option called &#8216;-processor&#8217; where we can specify the <strong><em>Name of the Annotation Processor</em></strong> along with a Set of <strong><em>Java Source Files</em></strong> containing the Annotations. For example, in our case, the command syntax would be something like the following,</p>
<pre class="brush: java; title: ; notranslate">javac -processor
    net.javabeat.articles.java6.newfeatures.customannotations.TestAnnotationProcessor
        AnnotatedJavaFile.java</pre>
<p align="left">The above command tells that the name of the Annotation Processor is net.javabeat.articles.java6.newfeatures.customannotations.TestAnnotationProcessor and it is going to process the AnnotatedJavaFile.java. As soon as this command is issued in the console, the TestAnnotationProcessor.process() method will be called by passing the <strong><em>Set of Annotations</em></strong> that are found in the Source Files along with the <strong><em>Annotation Processing Information</em></strong> as represented by RoundEnvironment. This TestAnnotationProcessor just list the various Annotations present in the Sample Java File (AnnotatedJavaFile.java) by iterating over it.</p>
<p align="justify">Following is the output of the above program</p>
<pre class="brush: java; title: ; notranslate">net.javabeat.articles.java6.newfeatures.customannotations.ClassLevelAnnotation
net.javabeat.articles.java6.newfeatures.customannotations.MethodLevelAnnotation</pre>
<h2>3) Streaming API for XML</h2>
<h3>3.1) Introduction</h3>
<p align="justify"><strong><em>Streaming API for XML</em></strong>, simply called <strong><em>StaX</em></strong>, is an API for reading and writing XML Documents. Why need another XML Parsing API when we already have <strong><em>SAX</em></strong> (Simple API for XML Parsing) and <strong><em>DOM</em></strong> (Document Object Model)? Both SAX and DOM parsers have their own advantages and disadvantages and StaX provides a solution for the disadvantages that are found in both SAX and DOM. It is not that StaX replaces SAX and DOM.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
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 align="justify">SAX, which provides an <strong><em>Event-Driven XML Processing</em></strong>, follows the <strong><em>Push-Parsing</em></strong> Model. What this model means is that in SAX, Applications will register <strong><em>Listeners</em></strong> in the form of Handlers to the Parser and will get notified through <strong><em>Call-back methods</em></strong>. Here the SAX Parser takes the control over Application thread by <strong><em>Pushing Events</em></strong> to the Application. So SAX is a <strong><em>Push-Parsing</em></strong> model. Whereas StaX is a <strong><em>Pull-Parsing</em></strong> model meaning that Application can take the control over parsing the XML Documents by pulling (taking) the Events from the Parser.</p>
<p align="justify">The disadvantage of DOM Parser is, it will keep the whole <strong><em>XML Document Tree in memory</em></strong> and certainly this would be problematic if the size of the Document is large. StaX doesn’t follow this type of model and it also has options for <strong><em>Skipping a Portion</em></strong> of a large Document during Reading.</p>
<p align="justify">The core StaX API falls into two categories and they are listed below. They are</p>
<ol>
<li>Cursor API</li>
<li>Event Iterator API</li>
</ol>
<p align="justify">Applications can any of these two API for parsing XML Documents. Let us see what these APIs’ are in detail in the following sections.</p>
<h3>3.2) Cursor API</h3>
<p align="justify">The <strong><em>Cursor API</em></strong> is used to traverse over the XML Document. Think of a Cursor as some kind of <strong><em>Pointer</em></strong> pointing at the start of the XML Document and then <strong><em>Forwarding the Document</em></strong> upon properly instructed. The working model of this Cursor API is very simple. When given a XML Document and asked to parse, the Parser will start reading the XML Document, and if any of the <strong><em>Nodes</em></strong> (like Start Element, Attribute, Text, End Element) are found it will stop and will give information about the Nodes to the Processing Application if requested. This cursor is a <strong><em>Forward only Cursor</em></strong>, it can never go backwards. Both Reading and Writing operations is possible in this cursor API.</p>
<h3>3.3) Sample Application</h3>
<p align="justify">Let us consider a sample Application which will read data from and to the XML Document with the help of the Cursor API. Following is the sample XML Document. The below XML File contains a list of Events for a person in his/her Calendar.</p>
<p><strong>myCalendar.xml</strong></p>
<pre class="brush: java; title: ; notranslate">&lt;calendar&gt;

    &lt;event type = &quot;meeting&quot;&gt;
        &lt;whom&gt;With my Manager&lt;/whom&gt;
        &lt;where&gt;At the Conference Hall&lt;/where&gt;
        &lt;date&gt;June 09 2007&lt;/date&gt;
        &lt;time&gt;10.30AM&lt;/time&gt;
    &lt;/event&gt;

    &lt;event type = &quot;birthday&quot;&gt;
        &lt;whom&gt;For my Girl Friend&lt;/whom&gt;
        &lt;date&gt;01 December&lt;/date&gt;
    &lt;/event&gt;

&lt;/calendar&gt;</pre>
<p><strong>ReadingUsingCursorApi.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.stax;

import java.io.*;
import javax.xml.stream.*;
import javax.xml.stream.events.*;

public class ReadingUsingCurorApi {

    private XMLInputFactory inputFactory = null;
    private XMLStreamReader xmlReader = null;

    public ReadingUsingCurorApi() {
        inputFactory = XMLInputFactory.newInstance();
    }

    public void read() throws Exception{

        xmlReader = inputFactory.createXMLStreamReader(
            new FileReader(&quot;.\\src\\myCalendar.xml&quot;));

        while (xmlReader.hasNext()){

            Integer eventType = xmlReader.next();
            if (eventType.equals(XMLEvent.START_ELEMENT)){
                System.out.print(&quot; &quot; + xmlReader.getName() + &quot; &quot;);
            }else if (eventType.equals(XMLEvent.CHARACTERS)){
                System.out.print(&quot; &quot; + xmlReader.getText() + &quot; &quot;);
            }else if (eventType.equals(XMLEvent.ATTRIBUTE)){
                System.out.print(&quot; &quot; + xmlReader.getName() + &quot; &quot;);
            }else if (eventType.equals(XMLEvent.END_ELEMENT)){
                System.out.print(&quot; &quot; + xmlReader.getName() + &quot; &quot;);
            }
        }
        xmlReader.close();
    }

    public static void main(String args[]){
        try{
            ReadingUsingCurorApi obj = new ReadingUsingCurorApi();
            obj.read();
        }catch(Exception exception){
            exception.printStackTrace();
        }
    }
}</pre>
<p align="justify">XMLInputFactory is the <strong><em>Factory Class</em></strong> for creating Input Stream objects which is represented by XMLStreamReader. An instance of type XMLStreamReader is created by calling XMLInputFactory.createXMLStreamReader() by passing the XML File to be parsed. At this stage, the Parser is ready to read the XML Contents if a combination call to XMLStreamReader.hasNext() and XMLStreamReader.next() is made. The entire Document is traversed in the while loop and the appropriate node&#8217;s value is taken by checking the various Element Types.</p>
<h3>3.4) Event Iterator API</h3>
<p align="justify">The Working Model of this <strong><em>Event Iterator API</em></strong> is no more different from the Cursor API. As the Parser starts traversing over the XML Document and if any of the <strong><em>Nodes</em></strong> are found, it will provide this information to the Application that is processing in the form of <strong><em>XML Events</em></strong>. Applications can loop over the entire Document, by requesting for the Next Event. This Event Iterator API is implemented on top of Cursor API.</p>
<h3>3.5) Sample Application</h3>
<p align="justify">Now let us take over a Sample Application using the Event Iterator API which is parsing on the XML Document myCalendar.xml.</p>
<p><strong>ReadingUsingEventIterator.java</strong></p>
<pre class="brush: java; title: ; notranslate">package net.javabeat.articles.java6.newfeatures.stax;

import java.io.*;
import javax.xml.stream.*;
import javax.xml.stream.events.*;

public class ReadingUsingEventIteratorApi {

    private XMLInputFactory inputFactory = null;
    private XMLEventReader xmlEventReader = null;

    public ReadingUsingEventIteratorApi() {
        inputFactory = XMLInputFactory.newInstance();
    }

    public void read() throws Exception{

        xmlEventReader = inputFactory.createXMLEventReader(
            new FileReader(&quot;.\\src\\myCalendar.xml&quot;));

        while (xmlEventReader.hasNext()){

            XMLEvent xmlEvent = xmlEventReader.nextEvent();
            if (xmlEvent.isStartElement()){
                System.out.print(&quot; &quot; + xmlEvent.asStartElement().getName() + &quot; &quot;);
            }else if (xmlEvent.isCharacters()){
                System.out.print(&quot; &quot; + xmlEvent.asCharacters().getData() + &quot; &quot;);
            }else if (xmlEvent.isEndElement()){
                System.out.print(&quot; &quot; + xmlEvent.asEndElement().getName() + &quot; &quot;);
            }
        }

        xmlEventReader.close();
    }

    public static void main(String args[]){
        try{
            ReadingUsingEventIteratorApi obj = new ReadingUsingEventIteratorApi();
            obj.read();
        }catch(Exception exception){
            exception.printStackTrace();
        }
    }
}</pre>
<p align="justify">If XMLStreamReader class represents the Reader for stream reading the XML Contents, then XMLEventReader represents the class for reading the XML Document as <strong><em>XML Events</em></strong> (represented by javax.xml.stream.events.XMLEvent). The rest of the reading logic is the same as that of the ReadingUsingCurorApi.java.</p>
<h2>4) Conclusion</h2>
<p align="justify">This article covered the leftover features of the <a href="http://www.javabeat.net/2007/06/introduction-to-java-6-0-new-features-part-i/">Part I New features of Java 6</a>. Starting with <strong><em>Pluggable Annotation Processing API</em></strong>, it covered what Annotations are, then guided us how to write <strong><em>Custom Annotations</em></strong> and <strong><em>Custom Annotation Processor</em></strong>. Then it traversed over the <strong><em>Cursor API</em></strong> and the <strong><em>Event Iterator API</em></strong> of StaX such as how to read XML Documents along with well-defined samples. Finally through <a href="http://www.javabeat.net/2007/06/mapping-java-objects-and-xml-documents-using-jaxb-in-java-6-0/"><strong><em>Java API for XML Binding</em></strong></a>, it details how to map Java and XML Documents with some sample applications.</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/2007/06/java-6-0-features-part-2-pluggable-annotation-processing-api/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Introduction to Java 6.0 New Features, Part–1</title>
		<link>http://www.javabeat.net/2007/06/introduction-to-java-6-0-new-features-part-i/</link>
		<comments>http://www.javabeat.net/2007/06/introduction-to-java-6-0-new-features-part-i/#comments</comments>
		<pubDate>Wed, 06 Jun 2007 12:26:49 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java 6.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=31</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>1) Introduction This article covers the various new features of Java 6, also known as Mustang. This article assumes that readers have sufficient knowledge over the concepts and terminologies in Java 5.0. For more information on Java 5.0, readers can vist the resources available in javabeat here. Though there is no significant changes at the [...]</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><h2>1) Introduction</h2>
<p align="justify">This article covers the various new features of <strong><em>Java 6</em></strong>, also known as <strong><em>Mustang</em></strong>. This article assumes that readers have sufficient knowledge over the concepts and terminologies in <strong><em>Java 5.0</em></strong>. For more information on Java 5.0, readers can vist the resources available in javabeat <a href="http://www.javabeat.net/category/java-j2ee/java-5-0/">here</a>. Though there is no significant changes at the <strong><em>Language Level</em></strong>, though Mustang comes with a bunch of enhancements in the other areas like <strong><em>Core</em></strong>, <strong><em>XML</em></strong> and <strong><em>Desktop</em></strong>. Most of the features are applicable both to J2SE and J2EE Platforms.</p>
<h2>2) Java 6 Features</h2>
<blockquote>
<ul>
<li><a href="http://www.javabeat.net/2007/06/java-6-0-features-part-2-pluggable-annotation-processing-api/">Introduction to Java 6.0 New Features, Part–2</a></li>
<li><a href="http://www.javabeat.net/category/java-j2ee/java-8-0/">What is new in Java 8.0?</a></li>
</ul>
</blockquote>
<p align="justify">A feature or an enhancement in Java is encapsulated in the form of a <strong><em>JSR</em></strong>. JSR, which stands for <strong><em>Java Specification Request</em></strong> is nothing but a formal proposal which details the need for a specific functionality to be available in the Java Platform that can be used by Applications. These JSR’s will be reviewed and released by a committee called <strong><em>Java Expert Groups (JEG)</em></strong>. This article covers the following list of features (or JSRs&#8217;) that comes along with the Java 6 Platform.</p>
<ul>
<li>Pluggable Annotation Processing API (JSR 269)</li>
<li>Common Annotations (JSR 250)</li>
<li>Java API for XML Based Web Services &#8211; 2.0 (JSR 224)</li>
<li>JAXB 2.0 (JSR 222)</li>
<li>Web Services Metadata (JSR 181)</li>
<li>Streaming API for XML (JSR 173)</li>
<li>XML Digital Signature (JSR 105)</li>
<li>Java Class File Specification Update (JSR 202)</li>
<li>Java Compiler API (JSR 199)</li>
<li>JDBC 4.0 (JSR 221)</li>
<li>Scripting in the Java Platform (JSR 223)</li>
</ul>
<p align="justify">The JSRs&#8217; that are covered in this article are Common Annotations, JDBC 4.0 and Scripting in the Java Platform. Rest of the JSRs&#8217; will be covered in the subsequent article.</p>
<h2>3) Common Annotations</h2>
<p align="justify">The aim of having <strong><em>Common Annotations API</em></strong> in the Java Platform is to avoid applications defining their own Annotations which will result in having larger number of Duplicates. This JSR is targeted to cover Annotations both in the <strong><em>Standard</em></strong> as well the <strong><em>Enterprise Environments</em></strong>. The packages that contain the annotations are javax.annotation and javax.annotation.security . Let us discuss in brief the commonly used Annotations that are available in this JSR in the next subsequent sections.</p>
<h3>3.1) @Generated Annotation</h3>
<p align="justify">Not all the source files or the source code in an application is hand-written by Developers. With the increasing number of <strong><em>Tools and Frameworks</em></strong>, most of the common <strong><em>Boiler-Plate Code</em></strong> is generated by the Tools or the Frameworks itself if they have been properly instructed. Such Tool Generated Code can be marked with @Generated Annotation. Consider the following sample code snippet,</p>
<p><strong>MyClass.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class MyClass{

    public void developerCode(){
    }

    @Generated(
        value = &quot;ClassNameThatGeneratedThisCode&quot;,
        comments = &quot;This is Tool Generated Code&quot;,
        date = &quot;5 June 2007&quot;
    )
    public void toolGeneratedCode(){
    }

}</pre>
<p align="justify">The value for the @Generated Annotation would be usually the class name that generated this code. Optionally, comments and date can be given to add more clarity to the generated code. Note this @Generated Annotation is not limited to a method definition, it can also be defined for <strong><em>Package Declaration</em></strong>, <strong><em>Class Declaration</em></strong>, <strong><em>Interface Declaration</em></strong>, <strong><em>Local Variable Declaration</em></strong>, <strong><em>Field Declaration</em></strong>, <strong><em>Parameter Declaration</em></strong> etc.</p>
<h3>3.2) @Resource and @Resources Annotation</h3>
<p align="justify">Any Class or <strong><em>Component</em></strong> that provides some useful functionality to an Application can be thought of as a <strong><em>Resource</em></strong> and the same can be marked with @Resource Annotation. This kind of Annotation can be seen normally in J2EE Components such as <strong><em>Servlets</em></strong>, <strong><em>EJB</em></strong> or <strong><em>JMS</em></strong>. For example consider the following code snippet,</p>
<pre class="brush: java; title: ; notranslate">@Resource(name = &quot;MyQueue&quot;, type = javax.jms.Queue,
    shareable = false,
    authenticationType = Resource.AuthenticationType.CONTAINER,
    description = &quot;A Test Queue&quot;
)
private javax.jms.Queue myQueue;</pre>
<p align="justify">Queue is a class available as part of <strong><em>JMS API</em></strong> and it serves as a target for <strong><em>Asynchronous Messages</em></strong> being sent by Applications. The various properties to note in @Resource Annotation are: &#8216;name&#8217; which is the <strong><em>JNDI Name</em></strong> of this resource, &#8216;type&#8217; which is the type of the resource which usually points to the <strong><em>Fully Qualified Class Name</em></strong>, &#8216;shareable&#8217; which tells whether this resource can be shared by other components in the Application or not, &#8216;authenticationType&#8217; which indicates the type of authentication to be performed either by the Container or by the Application and the Possible values are AuthenticationType.CONTAINER and<br />
AuthenticationType.APPLICATION and &#8216;description&#8217; which is a string that describes the purpose of this resource.</p>
<p align="justify">When the Application containing the @Resource Annotations are deployed to a Server, the Container will scan for all the Resource references during the time of Application loading and then will populate the @Resource References by assigning new instances.</p>
<p align="justify">@Resources is nothing but a collection of @Resource entries. Following is a sample code that defines @Resources Annotation,</p>
<p>@Resources is nothing but a collection of @Resource entries. Following is a sample code that defines<br />
@Resources Annotation,</p>
<pre class="brush: java; title: ; notranslate">
@Resources({
    @Resource(name = &quot;myQueue&quot; type = javax.jms.Queue),
    @Resource(name = &quot;myTopic&quot; type = javax.jms.Topic),
})
					</pre>
<h3>3.3) @PostConstruct and @PreDestroy</h3>
<p align="justify">J2EE Components are usually created by the Container or the Framework on which they are deployed. Container creates new components by calling the <strong><em>Default</em></strong> or the <strong><em>No Argument</em></strong> Constructor. It is a very common need that a component needs to get initialized with some default values after it has been created. @PostConstruct Annotation serves that purpose. It is a Method-Level Annotation, meaning that this Annotation can be applied only to a Method and it will be fired immediately as soon the Component is created by invoking the Constructor.</p>
<p align="justify">Consider the following set of code,</p>
<p><strong>MyDbConnectionComponent.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class MyDbConnectionComponent{

    public MyDbConnectionComponent(){
    }

    @PostConstruct()
    public void loadDefaults(){

        // Load the Driver Class.
        // Get the Connection and Do other stuffs.

    }
}</pre>
<p align="justify">We can see that @PostConstruct Annotation is normally used to <strong><em>Initialize the Resources</em></strong> that are Context specific. The loadDefaults() method which is marked with @PostConstruct Annotation will be called immediately by the Container as soon as an instance of MyDbConnectionComponent is created. There are certain guidelines to be followed while defining the PostConstruct method such as: the method should not be marked as static, return type should be void, it cannot throw any CheckedExceptions etc.</p>
<p align="justify">The counterpart to @PostConstruct Annotation is the @PreDestroy Annotation. From the name of the Annotation itself, we can infer that the method that is marked with this Annotation will be called before an object is about to be removed or destroyed by the Container. Like the @PostConstruct Annotation, this is also a <strong><em>Method-Level Annotation</em></strong> and the following code snippet proves this,</p>
<p><strong>MyDbConnectionComponent.java</strong></p>
<pre class="brush: java; title: ; notranslate">public class MyDbConnectionComponent{

    public MyDbConnectionComponent(){
    }

    @PreDestroy()
    public void releaseResources(){

        // Close the Connection.
        // Unload the Class Driver from the System

    }
}
</pre>
<p align="justify">The method releaseResources() will be called by the Container before the object is about to be Destroyed. Resource releasing code are ideal candidates to be placed in the @PreDestroy Annotation method.</p>
<h3>3.4) Role Based Annotations</h3>
<p align="justify">The following sections discuss the various <strong><em>Role-based Annotations</em></strong> that are very common in Applications that are very concerned about Security. A Typical Application is accessed by a wide range of Users and Users themselves fall into Several Roles. Considering an IT Organization, all Employees fall into the General Category of Roles namely Admin, Director, Manager, Engineer, Programmer etc. It is very common to see Applications following <strong><em>Role-Based Security Model</em></strong>. The Annotations @DeclareRoles, @RolesAllowed, @PermitAll, @DenyAll and @RunAs are Role-Based Annotations and are covered here.</p>
<h5>3.4.1) @DeclareRoles Annotations</h5>
<p align="justify">This is a <strong><em>Class-Level Annotation</em></strong> meaning that this Annotation is applicable only to a Class Declaration. If applied to a Class or a Component, it essentially declares the valid <strong><em>Set of Roles</em></strong> that are available for this Component. Consider the following code which will clarify this,</p>
<p><strong>LeaveService.java</strong></p>
<pre class="brush: java; title: ; notranslate">@DeclareRoles(value = {&quot;Director&quot;, &quot;Manager&quot;, &quot;Others&quot; })
public class LeaveService{

    @Resource
    private Context context;

    public void applyLeave(){

        // Any employee can apply for leave. So no need for any
        // conditional check.
    }

    public void grantLeave(){
        if(checkUserInRole()){
            // Grant Leave.
        }
    }

    public void cancelLeave(){
        if(checkUserInRole()){
            // Cancel Leave.
        }
    }

    private boolean checkUserInRole(){
        if( (context.isCallerInRole(&quot;Director&quot;) )
            || (context.isCallerinRole(&quot;Manager&quot;)) ){
            return true;
        }

        return false;
    }
}</pre>
<p align="justify">In the above example, the component LeaveService has been marked with @DeclareRoles Annotations with Role Name values namely Director and Manager. It has three services namely: applying for leave (applyLeave()), granting for leave (grantLeave()) and cancellation of leave (cancelLeave()). It is acceptable that only Employees in the Superior Role (Director or Manager) can grant or deny leaves to their sub-ordinates. So additional conditional checks are done to ensure that whether the User who is accessing the grantLeave() or the cancelLeave() service belongs to either of the defined Roles(Director or Manager). Since any employee in a company can apply for a leave, (whose Role Name is given as Others), no conditional checks are done in applyLeave() method.</p>
<h5>3.4.2) @RolesAllowed Annotation</h5>
<p align="justify">This is a <strong><em>Class/Method Level Annotation</em></strong> which is used to grant access to some Service(s) to the defined set of Users who are mentioned by their Role Names in the Annotation. Let us get into the following example straightaway,</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
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><strong>LeaveService.java</strong></p>
<pre class="brush: java; title: ; notranslate">@DeclareRoles(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;)
@RolesAllowed(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;)
public class MyServiceComponent{

    @RolesAllowed(value = {&quot;A&quot;, &quot;X&quot;, &quot;Y&quot;} )
    public void myService1(){
    }

    @RolesAllowed(value = {&quot;B&quot;, &quot;Y&quot;, &quot;Z&quot;} )
    public void myService2(){
    }

    @RolesAllowed(value = {&quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;} )
    public void myService3(){
    }

    public void myService4(){
    }
}</pre>
<p align="justify">The above code declares various roles namely &#8220;A&#8221;, &#8220;B&#8221;, &#8220;C&#8221;, &#8220;X&#8221;, &#8220;Y&#8221; and &#8220;Z&#8221; for the component MyServiceComponent. The @RolesAllowed Annotation when applied to a method grant Access to Users who are in that Roles only. For example, only Users with Roles &#8220;A&#8221; or &#8220;X&#8221; or &#8220;Y&#8221; are allowed to access the method myService1(). In the case of myService2(), &#8220;B&#8221;, &#8220;Y&#8221; or &#8220;Z&#8221; role Users are allowed to access it and so on.</p>
<p align="justify">What happens in the case of myService4()??</p>
<p align="justify">No @RolesAllowed is specified for this method. The fact is that, if a method doesn’t have @RolesAllowed Annotation attached to it, then it will inherit this property from the class where it has been defined. So, in our case, Users in the Role &#8220;A&#8221;, &#8220;B&#8221; or &#8220;C&#8221; can access the method myService4() becuase these set of Roles have been defined at the Class Level. What if the Class Declaration itself doesn’t have the @RolesAllowed Annotation declared? The answer is simple: it will take all the Roles that are defined in @DeclareRoles.</p>
<h5>3.4.3) @PermitAll and @DenyAll Annotation</h5>
<p align="justify">These are<strong><em> Class/Method Level Annotations</em></strong> and if applied to a Class Declaration will affect all the methods in the class, and when applied to a method will affect that method only.</p>
<p align="justify">Consider the following sample,</p>
<p><strong>MyClass.java</strong></p>
<pre class="brush: java; title: ; notranslate">@DeclareRoles(value = {&quot;A&quot;, &quot;B&quot;, &quot;C&quot;} )
class MyClass{

    @PermitAll()
    public void commonService(){
    }

    @DenyAll
    public void confidentialService(){
    }
}</pre>
<p align="justify">From the above code, it is inferred that commonService() method can be accessible by all Users irrespective of their Roles as it is marked with @PermitAll() annotation and no one can access the confidentialService() because it has been marked with @DenyAll() annotation.</p>
<h2>4) Scripting Language for the Java Platform</h2>
<h3>4.1) Introduction</h3>
<p align="justify">Java 6 provides the <strong><em>Common Scripting Language Framework</em></strong> for integrating various <strong><em>Scripting Languages</em></strong> into the Java Platform. Most of the popular Scripting Languages like <strong><em>Java Script</em></strong>, <strong><em>PHP Script</em></strong>, <strong><em>Bean Shell Script</em></strong> and <strong><em>PNuts Script</em></strong> etc., can be seamlessly integrated with the Java Platform. Support for <strong><em>Intercommunication</em></strong> between <strong><em>Scripting Languages</em></strong> and <strong><em>Java Programs</em></strong> is possible now because of this. It means that Scripting Language Code can access the Set of Java Libraries and Java Programs can directly embed Scripting Code. Java Applications can also have options for <strong><em>Compiling and Executing Scripts</em></strong> which will lead to good performance, provided the Scripting Engine supports this feature. Let us have a high-level overview of this JSR before going in detail.</p>
<p align="justify">Following sections provide the two core components of the Scripting engine namely,</p>
<ul>
<li><strong>Language Bindings</strong></li>
<li><strong>The Scripting API</strong></li>
</ul>
<h3>4.2) Language Bindings</h3>
<p align="justify">The Language Bindings provides mechanisms for establishing communications between the <strong><em>Java Code</em></strong> and the <strong><em>Script Code</em></strong>. More specifically, it deals with how actually a Java Object creating by a Script Code is stored and maintained by the Scripting Engine, how the <strong><em>Script Arguments</em></strong> are converted back and forth, how the Calls that are made to the Java Methods from within the <strong><em>Scripting Code</em></strong> got translated and how the return values from the Java Code are made available to the Scripting code. To illustrate on this further, consider the JavaScript Code,</p>
<pre class="brush: java; title: ; notranslate">var aJavaString = new String(&quot;A Test String&quot;);</pre>
<p align="justify">This piece of code essentially creates a new Java String object and assigns it to a JavaScript object called aJavaString which is of var type. As soon as the <strong><em>Rhino Script Engine</em></strong> (which is the Scripting Engine name for JavaScript) parses this Script Code, it has to create a new instance of String object and should store it somewhere. The place where Java Objects and Script objects are stored are referred to as <strong><em>Bindings</em></strong> in Java Scripting Terminology. Here, aJavaString acts as a <strong><em>Proxy Object</em></strong> for the real java.lang.String object.</p>
<p align="justify">Again consider the following code,</p>
<pre class="brush: java; title: ; notranslate">var aJavaString = new java.lang.String('A Test String');
var length = aJavaString.substring(7, 13);</pre>
<p align="justify">So many <strong><em>Micro-Level Tasks</em></strong> are involved if we analyse the above piece of code carefully. They are listed as follows,</p>
<ol>
<li>Script Arguments are Converted to Java Arguments</li>
<li>Java Method to be invoked is identified</li>
<li>Logic is performed on the invoked Java Method</li>
<li>Return Values, if any, are sent back to the Scripting Code</li>
</ol>
<p align="justify">The first line indicates that a new instance of java.lang.String object is created and it is stored in a Java Script object called aJavaString. Here aJavaString acts as a <strong><em>Proxy Object</em></strong> for the original java.lang.String object. After that we can see that the arguments 7 and 13 are passed from the Script Code to the method String.substring(int,int). The Engine will now convert the arguments that are to be sent to the Java method by using the <strong><em>Default Script-Java Mappings</em></strong> which is very specific to every Script Engine. After that, the Scripting Engine must ensure the availability of the method String.substring(int,int) at the run-time by abundantly depending on the <strong><em>Java Reflection API</em></strong>. Now the method is invoked and the logic gets executed. The return values are then converted using the <strong><em>Java-Script Mappings</em></strong> as defined by the Script Engine and will get populated in the length JavaScript object.</p>
<h3>4.3) Scripting API</h3>
<p align="justify">This API allows Java Programs to take the full advantage of <strong><em>Directing Embedding Scripting Code</em></strong> into the Applications. It also provides a framework wherein <strong><em>New Scripting Engines</em></strong> can be easily plugged-in. The entire API is available in the javax.script package.</p>
<p align="justify">ScriptEngineManager class provides mechanisms for <strong><em>Searching and Adding Scripting Engines</em></strong> into the Java Platform. Convenient methods are available for <strong><em>Discovering Existing Scripting Engines</em></strong>. For example, the following code will iterate and will list down all the Script Engines that are available in the Java 6 Distribution.</p>
<pre class="brush: java; title: ; notranslate">List allFactories = ScriptEngineManager.getEngineFactories();

for(ScriptEngineFactory engineFactory : allFactories){
    System.out.println(&quot;Engine Name&quot; + engineFactory.getEngineName());
}
</pre>
<p align="justify">The ScriptEngineFactory is the Factory Class for creating ScriptEngine objects. As such, two different ways are there to get instances of ScriptEngine classes. One way is to call the method ScriptEngineFactory.getScriptEngine(). The other direct way is to depend on the ScriptEngineManager itself to call getEngineByName().</p>
<pre class="brush: java; title: ; notranslate">// First Way
ScriptEngineFactory rhinoFactory = getScriptEngineFactory();
ScriptEngine rhinoEngine = rhinoFactory.getScriptEngine();

// Second Way
String name  = &quot;javascript&quot;;
ScriptEngine rhinoEngine = ScriptEngineManager.getEngineByName(engineName);
					</pre>
<p align="justify">Execution of scripts can be done by calling the ScriptEngine.eval(String) method.</p>
<p align="justify"><strong><em>Bindings</em></strong> as represented by javax.script.Bindings, provide key/name information to ScriptEngines. Two types of Binding Scopes are available, one is the <strong><em>Global Scope</em></strong> and the other is the <strong><em>Engine Scope</em></strong>. By default, the ScriptEngineManager manages some set of Default bindings, which can be obtained by making a call to ScriptManager.getBindings(). The Bindings that are obtained in this manner (i.e from ScriptEngineManager) are called <strong><em>Global Bindings</em></strong>. Following is the code to get a reference to the Global-Bindings object and to populate it with application-specific values.</p>
<pre class="brush: java; title: ; notranslate">Bindings globalBindings = scriptEngineManager.getBindings();
globalBindings.put(&quot;key1&quot;, &quot;value1&quot;);
globalBindings.put(&quot;key2&quot;, &quot;value2&quot;);</pre>
<p>It is also possible to customize the Binding information on <strong><em>Engine-by-Engine</em></strong> basis. For example, to obtain Bindings that is very specific to a particular Engine, a call to ScriptEngine.getBindings() can be made. These Bindings that are obtained in this way are called <strong><em>Engine Bindings</em></strong>.</p>
<h3>4.4) Sample Code</h3>
<p align="justify">This following Sample Application demonstrates how to directly embed Scripting Code in Java Applications. Argument passing between the Java Code and the Script Code are illustrated in this Sample.</p>
<pre class="brush: java; title: ; notranslate">package test;

import javax.script.*;

public class ScriptTest{

    public static void main(String[] args){

        try{
            // Create an instance of the Scripting manager.
            ScriptEngineManager manager = new ScriptEngineManager();

            // Get the reference to the rhino scripting engine.
            ScriptEngine rhinoEngine = manager.getEngineByName(&quot;javascript&quot;);

            // Get the Binding object for this Engine.
            Bindings bindings =	rhinoEngine.getBindings(ScriptContext.ENGINE_SCOPE);

            // Put the input value to the Binding.
            bindings.put(&quot;strValue&quot;, &quot;A Test String&quot;);

            // Populate the script code to be executed.
            StringBuilder scriptCode = new StringBuilder();
            scriptCode.append(&quot;var javaString = new java.lang.String(strValue);&quot;);
            scriptCode.append(&quot;var result = javaString.length();&quot;);

            // Evaluate the Script code.
            rhinoEngine.eval(scriptCode.toString());

            // Take the output value from the script, i.e from the Bindings.
            int strLength = (Integer)bindings.get(&quot;result&quot;);

            System.out.println(&quot;Length is &quot; + strLength);
        }catch(Exception exception){
            exception.printStackTrace();
        }
    }
}
</pre>
<p align="justify">In the above code, a new instance of ScriptEngineManager is created in the very first line. Then, the Scripting Engine<br />
that comes shipped with the Mustang, (i.e, Rhino Java Script Engine) is obtained by calling ScriptEngineManager.getEngineByName(&#8220;javascript&#8221;). Arguments are passed from and to the Java Code with the help of <strong><em>Bindings</em></strong>. The input string to be processed is added to the Bindings with the call to Bindings.put(&#8220;strValue&#8221;, &#8220;A Test String&#8221;). Notice how the input string is populated within the script code at run-time, var javaString = new java.lang.String(strValue). It means that at run-time the Script code becomes var javaString = new java.lang.String(&#8216;A Test String&#8217;). Then the script is executed by calling the ScriptEngine.eval(String) method. The output which is the length of the input string is now in the Script variable called result. And as mentioned previously, since all the Script and the Java Objects will be maintained and controlled by the Bindings, it is possible to get the value of the Script object result directly by calling Bindings.get(&#8220;result&#8221;).</p>
<h2>6) Conclusion</h2>
<p align="justify">This article covered some of the new features available in Java 6. It started off with the JSR that aimed in defining the <strong><em>Common Set of Annotations</em></strong> that can be used by Application Programs. Each and every Annotation in this package is briefly explained and examples were given to make it more understandable. Then, the <strong><em>Common Scripting Language Framework</em></strong> for the Java Platform is given in depth discussion along with the concept of <strong><em>Bindings</em></strong>, <strong><em>Scripting API</em></strong> and with a Sample Program.</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/2007/06/introduction-to-java-6-0-new-features-part-i/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>The Java 6.0 Compiler API</title>
		<link>http://www.javabeat.net/2007/04/the-java-6-0-compiler-api/</link>
		<comments>http://www.javabeat.net/2007/04/the-java-6-0-compiler-api/#comments</comments>
		<pubDate>Sun, 01 Apr 2007 13:00:47 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java 6.0]]></category>
		<category><![CDATA[Java Compiler]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=193</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>Introduction One of the cool features available in Java 6.0 (Mustang) is the ‘Java Compiler API’. This API is a result of the JSR (Java Specification Request) 199 which proposes that there must be a standard way to compile java source files. The result of the JSR is the new ‘Java Compiler API’ and one [...]</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><h2>Introduction</h2>
<p>One of the cool features available in Java 6.0 (Mustang) is the ‘Java Compiler API’. This API is a result of the JSR (Java Specification Request) 199 which proposes that there must be a standard way to compile java source files. The result of the JSR is the new ‘Java Compiler API’ and one can use this new feature to compile java source files from within java files. Previously developers were depending on the low-level issues like starting a process representing the javac.exe. Though this feature is not intended to every one, Editors or IDE (Integrated Development Environment) can make much use of this new feature for compiling Java source files in a better manner.</p>
<h2>Compiler API</h2>
<p>All the API (the client interfaces and the classes) needed by the developers for playing with the Java compiler API is available in the new javax.tools package. Not only this package represents classes and methods for invoking a java compiler, but it provides a common interface for representing any kind of Tool. A tool is generally a command line program (like javac.exe, javadoc.exe or javah.exe).</p>
<blockquote><p><span style="text-decoration: underline;"><strong>also read:</strong></span></p>
<ul>
<li><a href="http://www.javabeat.net/2007/06/introduction-to-java-6-0-new-features-part-i/">New Features in Java 6.0 &#8211; Part 1</a></li>
<li><a href="http://www.javabeat.net/2007/06/java-6-0-features-part-2-pluggable-annotation-processing-api/">New Features in Java 6.0 &#8211; Part 2</a></li>
<li><a title="Permanent Link to New Features in JDBC API (Java 6.0)" href="http://www.javabeat.net/2007/06/new-features-in-jdbc-api-java-6-0/" rel="bookmark">New Features in JDBC API (Java 6.0)</a></li>
<li><a href="http://www.javabeat.net/category/java-j2ee/java-8-0/">What is New in Java 8.0</a></li>
</ul>
</blockquote>
<p>Instead of looking into all the classes and interfaces that are available in the javax.tools package, it makes more sense to go through some sample programs, then examining what the classes and the methods are doing.</p>
<h2>Compiling a java source file from another Java source</h2>
<p>Following is the small sample program that will demonstrate how to compile a Java source file from another java file on the fly.</p>
<p>[All the examples given here are written and tested with Mustang build 1.6.0-b105, and it seems that more API changes and restructuring of classes and methods are occurring in the newer builds].</p>
<pre class="brush: java; title: ; notranslate">MyClass.java:

package test;
public class MyClass {
	public void myMethod(){
		System.out.println(&quot;My Method Called&quot;);
	}
}

Listing for SimpleCompileTest.java that compiles the MyClass.java file.

SimpleCompileTest.java:

package test;
import javax.tools.*;
public class SimpleCompileTest {
	public static void main(String[] args) {
String fileToCompile = &quot;test&quot; + java.io.File.separator +&quot;MyClass.java&quot;;
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult =	compiler.run(null, null, null, fileToCompile);
		if(compilationResult == 0){
			System.out.println(&quot;Compilation is successful&quot;);
		}else{
			System.out.println(&quot;Compilation Failed&quot;);
		}
	}
}</pre>
<p>The entry point for getting a compiler instance is to depend on the ToolProvider class. This class provides methods for locating a Tool object. (Remember a Tool can be anything like javac, javadoc, rmic, javah etc&#8230;) Though the only Tool available in Mustang build (1.6.0-b105) is the JavaCompiler as of now, it is expected that many more tools are to be added in the future.</p>
<p>The getSystemJavaCompiler() method in the ToolProvider class returns an object of some class that implements JavaCompiler (JavaCompiler is an interface that extends Tool interface and not a class). To be more specific, the method returns a JavaCompiler implementation that is shipped along with the Mustang Distribution. The implementation of the Java Compiler is available in the tools.jar file (which is usually available in the &lt;JDK60_INSTALLATION_DIR&gt;\lib\tools.jar).</p>
<p>After getting an instance of the JavaCompiler, compilation on a set of files (also known as compilation units) can be done by invoking the run(InputStream inputStream, OutputStream outputStream, OutputStream errorStream, String … arguments) method. To use the defaults, null can be passed for the first three parameters (which correspond to System.in, System.out and System.err), the fourth parameter which cannot be null is a variable argument that refers to the command-line arguments we usually pass to the javac compiler.</p>
<p>The file that we are going to compile is MyClass.java which is the same test package as of the SimpleCompileTest. The complete file name (along with the directory ‘test’) is passed as 4th argument to the run method. If there are no errors in the source file (MyClass.java, in this case), the method will return 0 which means that the source file was compiled successfully.</p>
<p>After compiling and running the SimpleCompileTest.java, one can see the following output message in the console.</p>
<p><strong>‘Compilation is successful’</strong></p>
<p>Let us modify the source code by introducing a small error by removing the semi-colon after the end of the println() statement and see what happens to the output.</p>
<pre class="brush: java; title: ; notranslate">MyClass.java:
package test;

public class MyClass {
	public void myMethod(){
System.out.println(&quot;My Method Called&quot;)
// Semi-colon removed here purposefully.
	}
}
Now, running the SimpleCompileTest.java leads to the following output,

test\MyClass.java:5: ';' expected
		System.out.println(&quot;My Method Called&quot;)
		                                      ^
1 error
Compilation Failed</pre>
<p>This is the error message one normally sees when compiling a java file using javac.exe in the command prompt. The above represents the error message(s) and since we have made the error output stream point to null (which defaults to System.err, which is the console) we are getting the output error messages in the console. If instead we have pointed the errorStream to something like this,</p>
<pre class="brush: java; title: ; notranslate">FileOutputStream errorStream = new FileOutputStream(&quot;Errors.txt&quot;);
int compilationResult = compiler.run(null, null, errorStream, fileToCompile);</pre>
<p>a new file called Errors.txt will be created in the current directory and the file would be populated with the error messages that we saw before.</p>
<h2>Compiling multiple files</h2>
<p>One might be tempted to think that the following code will work for compiling multiple java files (assuming that the two files that are to be compiled are One.java and Two.java).</p>
<pre class="brush: java; title: ; notranslate">
String filesToCompile = new String(&quot;One.java Two.java&quot;) ;</pre>
<p>But surprisingly, when you try this, you will get a ‘Compilation Failed’ error message in the console.</p>
<p>The answer is JavaCompiler needs to extract individual options and arguments and these options and arguments should not be separated by spaces, but should be given as individual strings.</p>
<p>So, this won’t work at all.</p>
<pre class="brush: java; title: ; notranslate">compiler.run(null, null, null, “One.java Two.java”);</pre>
<p>But, the below code will work nicely.</p>
<pre class="brush: java; title: ; notranslate">compiler.run(null, null, null, “One.java”, “Two.java”);</pre>
<p>One reason for forcing this kind of restriction is that sometimes the complete java file names (which includes directory path as well) itself can have white-spaces , in such a case it would be difficult for the parser to parse all the tokens correctly into options and arguments.</p>
<p>Following is a sample code that compiles multiple java files.</p>
<pre class="brush: java; title: ; notranslate">MyClass.java:
package test;

public class MyClass {
}

MyAnotherClass.java:
package test;

public class MyAnotherClass {
}

MultipleFilesCompileTest.java:
package test;
import javax.tools.*;

public class MultipleFilesCompileTest {
	public static void main(String[] args) throws Exception{
String file1ToCompile = &quot;test&quot; + java.io.File.separator + &quot;MyClass.java&quot;;
String file2ToCompile = &quot;test&quot; + java.io.File.separator + &quot;MyAnotherClass.java&quot;;
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult =	compiler.run(null, null, null, file1ToCompile, file2ToCompile);
		if(compilationResult == 0){
			System.out.println(&quot;Compilation is successful&quot;);
		}else{
			System.out.println(&quot;Compilation Failed&quot;);
		}
	}
}</pre>
<p>The above program compiles fine with the output message ‘Compilation is successful’.</p>
<p>Do remember, that the final argument is a variable argument and it can accept any number of arguments.</p>
<p>[Starting with Java 5.0, variable argument is a new feature where the callers (the calling method) can pass any number of arguments. To illustrate this concept, look at the sample code.</p>
<pre class="brush: java; title: ; notranslate">public int addNumbers(int …numbers){

int total = 0;
For(int temp : numbers){
	Total = total + temp;
}
return total;
}</pre>
<p>A variable argument is represented by ellipsis (…) preceding the variable name like this<br />
int … numbers. And , one can call the above method in different styles, like the below</p>
<pre class="brush: java; title: ; notranslate">addNumbers(10, 10, 30,40); // This will work.
addNumbers(10,10) // This also will work.</pre>
<p>type must be the last one. Variable arguments are internally treated as arrays. So, this is also possible now.</p>
<pre class="brush: java; title: ; notranslate">addNumbers(new int[]{10, 34, 54});</pre>
<p>So, great care should be exercised when passing multiple options along with values to the run method. As an example, the ideal way to pass options along with its option values might me,</p>
<pre class="brush: java; title: ; notranslate">compiler.run(null, null, null, ”-classpath”, ”PathToClasses”, ”-sourcepath”, ”PathToSources”, ”One.java”, ”Two.java”);</pre>
<p>Ass one can see, even the option and its option values must be treated as a separate string.</p>
<p>As you are aware of the fact, when invoking the java compiler with the ‘verbose’ option specified, the javac will output messages that will occur during the compilation life-cycle (like parsing the input, validating them, scanning for the paths for both source and class files, loading all the necessary class files, then finally creating the class files in the specified destination directory). Let us achieve the same effect through the following sample code.</p>
<pre class="brush: java; title: ; notranslate">SimpleCompileTestWithVerboseOption.java
package test;
import java.io.FileOutputStream;
import javax.tools.*;
public class SimpleCompileTestWithVerboseOption {
	public static void main(String[] args) throws Exception{
String fileToCompile = &quot;test&quot; + java.io.File.separator + &quot;MyClass.java&quot;;
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		FileOutputStream errorStream = new FileOutputStream(&quot;Errors.txt&quot;);
		int compilationResult =	compiler.run(
				null, null, errorStream, &quot;-verbose&quot;, fileToCompile);
		if(compilationResult == 0){
			System.out.println(&quot;Compilation is successful&quot;);
		}else{
			System.out.println(&quot;Compilation Failed&quot;);
		}
	}
}</pre>
<h2>May be a bug in Mustang</h2>
<p>One might see that the errorStream (3rd argument) has been pointed out to a file to collect the output messages instead of the outputStream (2nd argument).</p>
<p>The following code was tried for capturing the verbose output, but this code failed, in the sense, the output was still written to the standard console, though the code seems to re-direct the output to a file.</p>
<pre class="brush: java; title: ; notranslate">FileOutputStream outputStream = new FileOutputStream(&quot;Output.txt&quot;);
int compilationResult =	compiler.run(
null, outputStream, null, &quot;-verbose&quot;, fileToCompile);</pre>
<p>The Java Compiler API is treating the output messages (in this case, the output messages obtained by specifying the ‘verbose’ option) as error messages, and so even though the output is pointing to the file (‘Output.txt’), it is spitting all the output messages to the console.</p>
<p>Also, the documentation for the run method is unclear; it tells that any diagnostics (errors, warnings or information) may be written either to the output stream or the error messages.</p>
<h2>Advanced Compilation</h2>
<p>In the above section, we saw how to compile files using the JavaCompiler tool. For advanced compilation related stuffs, the JavaCompiler depends on two more services namely the file manager services and the diagnostics services. These services are provided by the JavaFileManager and the DiagnosticListener classes respectively.</p>
<h2>JavaFileManager</h2>
<p>The JavaFileManager (being given implementation as StandardJavaFileManager) manages all the file objects that are usually associated with tools. This JavaFileManager is not only to JavaCompiler, but instead it can work with any kinds of objects that conform to the standard Tool interface. To understand why JavaFileManager is so important, let us understand what could be the things that may happen during compilation process.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<pre class="brush: java; title: ; notranslate">javac MyClass.java</pre>
<p>When we issue this command in the command prompt, so many things will happen. The very first thing is that the compiler will parse all the options that are specified by the user, have to validate them, and them have to scan the source and class path for java source files and the jar files. It then has to deal with the input files (in this case it is MyClass.java) and output files (MyClass.class).</p>
<p>So, JavaFileManager which is associated with any kind of tool (normally all tools have some kind of input and the output files for processing), deals with managing all the input files and output files. By managing, we mean that JavaFileManager is responsible for creating output files, scanning for the input files, caching them for better performance. One such implementation given to the JavaFileManager is the StandardJavaFileManager.</p>
<p>A file being managed by JavaFileManager doesn’t mean the file is necessarily a file in the hard-disk. The contents of the file managed may come from a physical file in a hard-disk, may come from in-memory or can even come from a remote socket. That’s why JavaFileManager doesn’t deal with java.io.File objects (which usually refer to the physical files in the operating system File System). Rather, JavaFileManager manages all the files and their contents in the form of FileObject and JavaFileObject which represents the abstract representation for any kind of files by managed by the JavaFileManager.</p>
<p>FileObject and JavaFileObject refer to the abstract file representation that are being managed by the JavaFileManager and also have support related to reading and writing the contents to the right destination. The only difference between a FileObject and a JavaFileObject is that a FileObject can represent any kind of FileObject (like text file, properties file, image file etc), whereas a JavaFileObject can represent only java source file (.java) or a class file (.class). If a FileObject represents a java source file or a class file, then implementations should take care to return a JavaFileObject instead.</p>
<h2>Diagnostics</h2>
<p>The second dependent service by the JavaCompiler is the Diagnostic Service. Diagnostic usually refers to errors, warnings or informative messages that may appear in a program. For getting diagnostics messages during the compilation process, we can attach a listener to the compiler object. The listener is a DiagnosticListener object and its report() method will be called with a diagnostic method which contains many a more information like the kind of diagnostics (error, warning, information or other), the source for this diagnostics, the line number in the source code, a descriptive message etc.</p>
<h2>CompilationTask</h2>
<p>Before going into the sample code to clarify things like JavaFileManager, Diagnostic,and the DiagnosticListener classes, let us have a quick review on the class CompilationTask. From its name, obviously one can tell that it represents an object that encapsulates the actual compilation operation. We can initiate the compilation operation by calling the call() method in the CompilationTask object.</p>
<p>But how to get the CompilationTask object?</p>
<p>Since, CompilationTask is closely associated to a JavaCompiler object, one can easily say JavaCompiler.getCompilationTask( arguments ) to get the CompilationTask object. Let we now see the parameters that are needed to pass to the getCompilationTask(…) method.</p>
<p>Almost all the arguments can be null (with their defaults, which is discussed later), but the final argument represents the list of java objects to be compiled (or the compilation units) which cannot be null. The last argument is Iterable&lt;? Extends JavaFileObject&gt; javaObjects.</p>
<p>So, how can one populate this argument?</p>
<p>[Iterable is a new interface that was added with jdk 5.0 which is use to iterate (or traverse over a collection of objects. It has one method called iterator() which returns an Iterator object, and using it one can traverse over the collection by using the combinational hasNext() and the next() methods.</p>
<p>Considering type safety which started from Java 5.0, it is the role of the developer to specify what exactly is the type of object to be iterated. Iterable&lt;? Extends JavaFileObject&gt; means that this argument is an iterable that is acting on any class that implement the JavaFileObject interface].</p>
<p>JavaFileManager has 4 convenience methods like getJavaFileObject(File … files) , getJavaFileObjects(String … filenames), getJavaFileObjectsFromFiles(Iterable(? extends JavaFileObject) and getJavaFileObjectFromString(Iterable&lt;? extends String&gt; filenames) that returns javaObjects in the form of Iterable&lt;? Extends JavaFileObject&gt; type.</p>
<p>So, we can construct the 4th arguments using any of the convenience methods.</p>
<p>With more bits of theory in the last few sections, let us see a sample program that incorporates all the classes and the methods that we saw listed.</p>
<p>Purposefully we create a java file called MoreErrors.java that has some error code in it. The listing for MoreErrors.java is shown below.</p>
<pre class="brush: java; title: ; notranslate">MoreErrors.java:
package test;
public class MoreErrors {
	public void errorOne ()
		// No open braces here.  Line a
	}
	public void errorTwo(){
		System.out.println(&quot;No semicolon&quot;) // Line b
		// No semicolon at the end of the statement.
	}
	public void errorThree(){
		System.out.prntln(&quot;No method name called prntln()&quot;); // Line c
	}
}</pre>
<p>As one can see, the statement above line a, line b and line c has errors.</p>
<p>Let us look into the AdvancedCompilationTest.java that uses all the classes and the methods that we discussed above.</p>
<pre class="brush: java; title: ; notranslate">AdvancedCompilationTest.java:
package test;
import java.io.*;
import java.util.*;
import javax.tools.*;
import javax.tools.JavaCompiler.*;
public class AdvancedCompilationTest {
	public static void main(String[] args) throws Exception {
		JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
// Line 1.
		MyDiagnosticListener listener = new MyDiagnosticListener(); // Line 2.
		StandardJavaFileManager fileManager  =
		compiler.getStandardFileManager(listener, null, null); // Line 3.
String fileToCompile = &quot;test&quot; + File.separator + &quot;ManyErrors.java&quot;;
// Line 4
		Iterable fileObjects =						fileManager.getJavaFileObjectsFromStrings(
Arrays.asList(fileToCompile));  // Line 5
CompilationTask task = compiler.getTask(null, fileManager, listener, null, null, fileObjects); // Line 6
		Boolean result = task.call(); // Line 7
		if(result == true){
			System.out.println(&quot;Compilation has succeeded&quot;);
		}
	}
}
class MyDiagnosticListener implements DiagnosticListener{
	public void report(Diagnostic diagnostic) {
		System.out.println(&quot;Code-&gt;&quot; +  diagnostic.getCode());
		System.out.println(&quot;Column Number-&gt;&quot; + diagnostic.getColumnNumber());
		System.out.println(&quot;End Position-&gt;&quot; + diagnostic.getEndPosition());
		System.out.println(&quot;Kind-&gt;&quot; + diagnostic.getKind());
		System.out.println(&quot;Line Number-&gt;&quot; + diagnostic.getLineNumber());
		System.out.println(&quot;Message-&gt;&quot;+ diagnostic.getMessage(Locale.ENGLISH));
		System.out.println(&quot;Position-&gt;&quot; + diagnostic.getPosition());
		System.out.println(&quot;Source&quot; + diagnostic.getSource());
		System.out.println(&quot;Start Position-&gt;&quot; + diagnostic.getStartPosition());
		System.out.println(&quot;\n&quot;);
	}
}</pre>
<p>Let us explore the above code in greater detail.</p>
<p>Line 1 is essentially creating an object of type JavaCompiler using the ToolProvider class. This is the entry point.</p>
<pre class="brush: java; title: ; notranslate">JavaCompiler compiler = ToolProvider.getSystemJavaCompiler()</pre>
<p>Line 2 and Line 3 is making the compiler to make use of the FileManager and the Diagnostic’s Services. To rewind the theory a bit, JavaFileManager object is used to manage the input and the output files that a tool normally deals with. And Diagnostic’s objects refer the diagnostics (errors, warnings or information) that may occur during the compilation process within a program.</p>
<pre class="brush: java; title: ; notranslate">MyDiagnosticListener listener = new MyDiagnosticListener();</pre>
<p>Line 2 creates an object of Type DiagnosticListener, since we want to monitor the diagnostics that may happen during the process of compilation (diagnostics, in the form of error messages will always happen in our case, as we have purposefully done some errors in the java code). We have overridden the report(Diagnostic) method and have extracted all the possible information. Since diagnostics can happen in any kind of file object, how can we specifically tell that this Diagnostics is for a java file object?</p>
<p>The answer has become easy because of Java 5.0 generics. One can notice that MyDiagnosticListener is a typed class (having some typed parameter) meaning that it can act on any kind of object that has diagnostics properties; here we are explicitly telling that the diagnostics is for JavaFileObject and not for any other file object by mentioning the JavaFileObject in the class declaration and the method declaration (shown in bold).</p>
<pre class="brush: java; title: ; notranslate">class MyDiagnosticListener implements DiagnosticListener{
	public void report(Diagnostic diagnostic) {
		System.out.println(&quot;Code-&gt;&quot; +  diagnostic.getCode());
		System.out.println(&quot;Column Number-&gt;&quot; + diagnostic.getColumnNumber());
		….
		….
	}
}</pre>
<p>In Line 3, we are associating the Diagnostics listener object to the compiler object through the standard java file manager by making this method call.</p>
<pre class="brush: java; title: ; notranslate">StandardJavaFileManager fileManager  =
			compiler.getStandardFileManager(listener, null, null);</pre>
<p>This method tells to attach the diagnostics listener object to this compiler object, so whenever this compiler object executes a compilation operation, and if any diagnostics related errors or warnings have occurred in a program, then the diagnostics being encapsulated by the Diagnostic object will be passed back to the report() method of the DiagnosticListener interface.</p>
<p>The last 2 arguments refer the locale and charset arguments for formatting the diagnostic messages in a particular locale and by using the specified charset which can be null.</p>
<p>Line 4 and Line 5 populates the file objects to be compiled by using the convenience objects in the StandardJavaFileManager class.</p>
<pre class="brush: java; title: ; notranslate">String fileToCompile = &quot;test&quot; + File.separator + &quot;ManyErrors.java&quot;;
Iterable fileObjects =						fileManager.getJavaFileObjectsFromStrings(
Arrays.asList(fileToCompile));</pre>
<p>Line 6 gets an instance of the CompilationTask object by calling the getCompilationTask() method and by passing the fileManager, listener and the fileObjects objects. The null arguments refer to the Writer object (for getting the output from the compiler), list of options (the options that we pass to javac like –classpath classes, -sourcepath Sources…) and classes (for processing the custom annotations that are found in the source code).</p>
<p>Finally, the actual compilation operation is done by calling the call() method which returns true if all the files (compilationUnits) succeed compilation. If any of the files have errors in it , then the call() method will return false. Anyway, in our case, we have some error code in the MoreErrors.java file, so the report method will be called printing all the diagnostics information.</p>
<h2>DiagnosticCollector</h2>
<p>In the previous program, we saw that we have a customized class called MyDiagnosticListener. Its sole purpose it to collect and print all the diagnostic messages to the console. This class can be completely eliminated since Mustang already has a class called DiagnosticCollection&lt;SourceObject&gt; that does the same thing. It has a method called getDiagnostics() which returns a list , through which we can iterate and can output the diagnostic messages to the console.</p>
<p>The following code achieves the same using DiagosticCollector class.</p>
<pre class="brush: java; title: ; notranslate">AdvancedCompilationTest2.java:
package test;
import java.io.*;
import java.util.*;
import javax.tools.*;
import javax.tools.JavaCompiler.*;
public class AdvancedCompilationTest2 {
	public static void main(String[] args) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // Line 1.
		DiagnosticCollector diagnosticsCollector =
		new DiagnosticCollector();
		StandardJavaFileManager fileManager  =
compiler.getStandardFileManager(diagnosticsCollector, null, null); // Line 3.
String fileToCompile = &quot;test&quot; + File.separator + &quot;ManyErrors.java&quot;; // Line 4
Iterable fileObjects = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(fileToCompile)); // Line 5
CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects); // Line 6
		Boolean result = task.call(); // Line 7
List&gt; diagnostics = diagnosticsCollector.getDiagnostics();
		for(Diagnostic d : diagnostics){
			// Print all the information here.
		}
		if(result == true){
			System.out.println(&quot;Compilation has succeeded&quot;);
		}else{
			System.out.println(&quot;Compilation fails.&quot;);
		}
}
}</pre>
<h2>Compilation of Java Source from a String object</h2>
<p>Having discussed about the various ways of compiling java file sources, it’s now time to look at how to compile a java source that is encapsulated in a string object. As previously mentioned, it is not mandatory that the contents of a java source must reside in hard-disk, it can even reside in memory. By saying that compiling a java source from a string object, we are implicitly saying that the java source is residing in memory, more specifically, the contents are residing in RAM.</p>
<p>For this to happen, we have to encapsulate a class the represents the java source from a string. We can extend this class from the SimpleJavaFileObject (a convenient class that overrides all the methods in the JavaFileObject with some default implementation). The only method to override is the getCharContent() that will be called internally by the Java compiler to get the java source contents.</p>
<pre class="brush: java; title: ; notranslate">JavaObjectFromString.java:
package test;
import java.net.URI;
class JavaObjectFromString extends SimpleJavaFileObject{
    private String contents = null;
public JavaObjectFromString(String className, String contents) throws Exception{
    		super(new URI(className), Kind.SOURCE);
this.contents = contents;
    }
public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
    		return contents;
    }
}</pre>
<p>Since the SimpleJavaFileObject has a protected two argument constructor that accepts an URI (the URI representation of the file object) and a Kind object (a special type that tells what kind is this object, the Kind may be a Kind.SOURCE, Kind.CLASS, Kind.HTML, Kind.OTHER, in our case, it is Kind.SOURCE, since we are inferring a Java source object), we have defined a two argument constructor in JavaObjectFromString class and delegates the control back the base class. The getCharContent() method has to be overridden (since this is the method that will be called by the JavaCompiler to get the actual java source contents) to return the string (remember, String implements CharSequence) that represents the entire java source (which was previously saved in the constructor).</p>
<p>The code that uses this JavaObjectFromString object looks like this.</p>
<pre class="brush: java; title: ; notranslate">AdvancedCompilationTest3.java:
package test;
import java.io.*;
import java.util.*;
import javax.tools.*;
import javax.tools.JavaCompiler.*;
public class AdvancedCompilationTest3 {
	public static void main(String[] args) throws Exception {
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
		DiagnosticCollector diagnosticsCollector =
			new DiagnosticCollector();
		StandardJavaFileManager fileManager  =
compiler.getStandardFileManager(diagnosticsCollector, null, null);
JavaFileObject javaObjectFromString = getJavaFileContentsAsString();
Iterable fileObjects = Arrays.asList(javaObjectFromString);
CompilationTask task = compiler.getTask(null, fileManager, diagnosticsCollector, null, null, fileObjects);
		Boolean result = task.call();
List&gt; diagnostics = diagnosticsCollector.getDiagnostics();
		for(Diagnostic d : diagnostics){
			// Print all the information here.
		}
		if(result == true){
			System.out.println(&quot;Compilation has succeeded&quot;);
		}else{
			System.out.println(&quot;Compilation fails.&quot;);
		}
	}
	static SimpleJavaFileObject getJavaFileContentsAsString(){
		StringBuilder javaFileContents = new StringBuilder(&quot;&quot; +
				&quot;class TestClass{&quot; +
				&quot;	public void testMethod(){&quot; +
	&quot;		System.out.println(&quot; + &quot;\&quot;test\&quot;&quot; +           &quot;);&quot; +
				&quot;}&quot; +
				&quot;}&quot;);
		JavaObjectFromString javaFileObject = null;
		try{
javaFileObject = new JavaObjectFromString(&quot;TestClass&quot;, javaFileContents.toString());
		}catch(Exception exception){
			exception.printStackTrace();
		}
		return javaFileObject;
	}
}</pre>
<h2>Conclusion</h2>
<p>Before the release of Mustang, the compiler API related interfaces and classes were maintained in some non-standard packages (i.e inside com.sun.javac.tools.javac). But with Java 6.0, the designers of java have given great heights to compilation API by generalizing them in the javax.tools package. As already mentioned, this API is not for everyone. Web and Application servers can depend on this API exhaustively to provide compilation activities of the dynamically created Java source files. Although it is heard that more and more bugs related to Compiler API are there, they are expected to be fixed soon in the future builds.</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/2007/04/the-java-6-0-compiler-api/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What is new in Java 6.0 Collections API?</title>
		<link>http://www.javabeat.net/2007/03/what-is-new-in-java-6-0-collections-api/</link>
		<comments>http://www.javabeat.net/2007/03/what-is-new-in-java-6-0-collections-api/#comments</comments>
		<pubDate>Wed, 28 Mar 2007 07:48:00 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java 6.0]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=10</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 this article I will write about the new Collections APIs introduced in Java 6.0. Mustang has few interesting changes in the Collections APIs, one amoung them is the Deque. Deque is used for the Bi-Directional traversal. It has different implementations including BlockingDeque,ArrayDeque,etc. I will talk about the Deque and its various implementation, also few [...]</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><span style="font-size: 13px;">In this article I will write about the new Collections APIs introduced in Java 6.0. Mustang has few interesting changes in the Collections APIs, one amoung them is the Deque. Deque is used for the Bi-Directional traversal. It has different implementations including BlockingDeque,ArrayDeque,etc. I will talk about the Deque and its various implementation, also few more changes in the Collectiona API in Java 6.0.</span></p>
<h2>Java 6.0 New Collection APIs an Overview</h2>
<p>The following are the new collection APIs introduced in Java 6.0. I listes them as Interfaces and classes.</p>
<h3>New Interfaces</h3>
<ul>
<li>Deque</li>
<li>BlockingDeque</li>
<li>NavigableSet</li>
<li>NavigableMap</li>
</ul>
<h3>New Classes</h3>
<ul>
<li>ArrayDeque</li>
<li>LinkedBlockingDeque</li>
<li>ConcurrentSkipListSet</li>
<li>ConcurrentSkipListMap</li>
<li>AbstractMap.SimpleEntry</li>
<li>AbstractMap.SimpleImmutableEntry</li>
</ul>
<h3>Updated Classes in Java 6.0</h3>
<ul>
<li>LinkedList</li>
<li>TreeSet</li>
<li>TreeMap</li>
<li>Collections</li>
</ul>
<h2>Deque and ArrayDeque</h2>
<p>Deque is the abbreviation of “Double Ended Queue”. A Collection that allows us to add (or) remove elements at both ends. Deque supports total size of collection for both fixed and unspecified size limits.</p>
<p>Deque implementation can be used as Stack(Last in first out ) or Queue(First in First Out).For each insertion, retrieval and removal of elements from deque there exists methods in 2 flavours. One will throw exception if it fails in an operation and another one returns status or special value for each operation.</p>
<table summary="" width="529" border="1" cellspacing="1" cellpadding="1">
<tbody>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><strong>Operation</strong></span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><strong>Special value method</strong></span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><strong>Exception throwing method</strong></span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Insertion at head</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">offerFirst(e)</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">addFirst(e)</span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Removal at head</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">pollFirst()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">removeFirst()</span></td>
</tr>
<tr>
<td>
<p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-family: Courier New; font-size: x-small;">Retrieval at</span> <span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Head</span></p>
</td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">peekFirst()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">getFirst()</span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Insertion at Tail</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">offerLast(e)</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">addLast(e)</span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Removal at Tail</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">pollLast()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">removeLast()</span></td>
</tr>
<tr>
<td>
<p class="MsoNormal" style="margin: 0in 0in 0pt;"><span style="font-family: Courier New; font-size: x-small;">Retrieval at</span> <span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Tail</span></p>
</td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">peekLast()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">getLast()</span></td>
</tr>
</tbody>
</table>
<p>Implementation of Deque doesn’t require preventing the insertion of null, but when we are using special value method null is return to indicate that collection is empty. So it is recommendable not to allow insertion of null.</p>
<p>ArrayDeque is a class that implements Deque. It has no capacity restrictions. It will perform faster than stack when used as stack and faster than linked list when used as queue. ArrayDeque is not thread Safe. The following example explains how to write program using ArrayDeque.</p>
<p><strong> Example</strong></p>
<pre class="brush: java; title: ; notranslate">import java.util.ArrayDeque;
import java.util.Iterator;

public class DequeExample
{
	public static void main(String as[])
	{
		ArrayDeque adObj = new ArrayDeque();

		//Insertion by using various methods
		adObj.add(&amp;quot;Oracle&amp;quot;);
		adObj.addFirst(&amp;quot;DB2&amp;quot;);
		adObj.offerFirst(&amp;quot;MySQL&amp;quot;);   //returns boolean - true R false
		adObj.offerLast(&amp;quot;Postgres&amp;quot;);   //returns boolean - true R false

		//Retrievals
		System.out.println(&amp;quot;Retrieving First Element :&amp;quot; + adObj.peekFirst());
		System.out.println(&amp;quot;Retrieving Last Element  :&amp;quot;+ adObj.peekLast());

		//Removals
		System.out.println(&amp;quot;Removing First  Element  :&amp;quot;+ adObj.pollFirst());
		System.out.println(&amp;quot;Removing Last  Element   :&amp;quot;+ adObj.pollLast());

		//Reverse traversal
		System.out.println(&amp;quot;Remaining Elements :&amp;quot;);
		Iterator it = adObj.descendingIterator();
		while(it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}</pre>
<p><strong>Output:</strong></p>
<pre class="brush: java; title: ; notranslate">Retrieving First Element :MySQL
Retrieving Last Element  <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ostgres
Removing First  Element  :MySQL
Removing Last  Element   <img src='http://www.javabeat.net/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ostgres
Remaining Elements :
Oracle
DB2</pre>
<h2>BlockingDeque and LinkedBlockingDeque</h2>
<p>A BlockingDeque is similar to Deque and provides additionally functionality. When we tries to insert an element in a BlockingDeque, which is already full, it can wait till the space becomes available to insert an element. We can also specify the time limit for waiting.</p>
<p>BlockingDeque methods available in four flavours</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li>Methods throws exception</li>
<li>Methods returns special value</li>
<li>Methods that blocks(Waits indefinitely for space to available)</li>
<li>Methods that times out(Waits for a given time for space to available)</li>
</ul>
<table width="700" border="1" cellspacing="1" cellpadding="1">
<tbody>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><strong>Operation</strong></span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><strong>Special Value</strong></span></td>
<td><span style="font-size: 10pt; color: black; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><strong>Throws Exception</strong></span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><strong>Blocks</strong></span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><strong>Times out</strong></span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Insertion at head</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">addFirst(e)</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">offerFirst(e)</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">putFirst(e)</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">offerFirst(e,time,unit)</span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Removal from head</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">removefirst()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;"><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">pollFirst()</span></span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">takeFirst()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">takeFirst(time,unit)</span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Retrieval from head</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">getFirst()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">peekfirst()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">NA</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">NA</span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Insertion at tail</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">addLast(e)</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">offerLast(e)</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">putLast(e)</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">offerLast(e,time,unit)</span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Removal from tail</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">removeLast()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">pollLast()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">takeLast()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">takeLast(time,unit)</span></td>
</tr>
<tr>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">Retrieval from tail</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">getLast()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">peekLast()</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">NA</span></td>
<td><span style="font-size: 10pt; font-family: 'Courier New'; mso-fareast-font-family: 'Times New Roman'; mso-ansi-language: EN-US; mso-fareast-language: EN-US; mso-bidi-language: AR-SA;">NA</span></td>
</tr>
</tbody>
</table>
<p>A LinkedBlockingDeque is a Collection class, which implements BlockingDeque interface in which we can specify maximum capacity if we want.If we did not specify the capacity then maximum capacity will be Integer.MAX_VALUE.</p>
<pre class="brush: java; title: ; notranslate">import java.util.concurrent.*;
class BlockingDequeExample implements Runnable
{
	LinkedBlockingDeque lbd = new LinkedBlockingDeque(1);
	volatile boolean b = true;
	public void run()
	{
		try
		{
			/*First thread once enters into the block it modifies
			  instance variable b to false and prevents second
			  thread to enter into the block */
			 if(b)
			{
				b = false;
				Thread.sleep(5000);//Makes the Thread to sleep for 5 seconds
				System.out.println(&amp;quot;Removing &amp;quot;+lbd.peek());
				lbd.poll();//Removing an element from collection
			}
			else
			{
				System.out.println(&amp;quot;Waiting &amp;quot;);
				/*This method makes to wait till the first thread removes an elements*/
				lbd.put(&amp;quot;B&amp;quot;);
				System.out.println(&amp;quot;Inserted &amp;quot;+lbd.peek());
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	public static void main(String[] args) throws Exception
	{
		BlockingDequeExample bdeObj = new BlockingDequeExample();
		bdeObj.lbd.offer(&amp;quot;A&amp;quot;);
		System.out.println(&amp;quot;Inserted &amp;quot;+bdeObj.lbd.peek());
		Thread tMainObj = new Thread(bdeObj);
		tMainObj.start();
		Thread tSubObj = new Thread(bdeObj);
		tSubObj.start();
	}
}</pre>
<p><strong>Output:</strong></p>
<pre class="brush: java; title: ; notranslate">Inserted A
Waiting
Removing A
Inserted B</pre>
<h2>NavigableSet and ConcurrentSkipListSet</h2>
<p>Suppose we have a requirement, from sorted set elements [5,10,15,20]<br />
we want few things like this</p>
<ul>
<li>Retrieve the element which is immediately greater than or lower than element 15</li>
<li>Retrieve all elements greater than or lower than 10</li>
</ul>
<p>With the help of existing methods we need to take few risks to achieve them. But with NavigableSet methods it becomes just a method call.NavigableSet methods used to return the closest matches of elements for the given elements in the collection. ConcurrentSkipListSet is one of the class that implements NavigableSet.</p>
<p><strong>Example</strong></p>
<pre class="brush: java; title: ; notranslate">import java.util.concurrent.*;
import java.util.*;
class SkipListSetTest
{
	public static void main(String[] args)
	{
		ConcurrentSkipListSet csls = new ConcurrentSkipListSet();
		csls.add(15);
		csls.add(20);
		csls.add(5);
		csls.add(10);
		System.out.println(&amp;quot;Elements in the collections are&amp;quot;);
		for(Integer i: csls)
		{
			System.out.println(i);
		}
		/* Retrieve immediate element less than or equal to  the given element */
		System.out.println(&amp;quot;Floor    &amp;quot;+csls.floor(12));
		/* Retrieve immediate  element greater than or equal to the given element */
		System.out.println(&amp;quot;Ceiling  &amp;quot;+csls.ceiling(12));
		/* Retrieve immediate element less than the given element */
		System.out.println(&amp;quot;Lower    &amp;quot;+csls.lower(10));
		/* Retrieve immediate element greater than the given element */
		System.out.println(&amp;quot;heigher  &amp;quot;+csls.higher(10));
		System.out.println(&amp;quot;Head Elements &amp;quot;);
		Set cslsHeadView =  csls.headSet(10);
		//HeadSet excludes the given element
		for(Integer i: cslsHeadView)
		{
			System.out.println(i);
		}
		Set cslsTailView =  csls.tailSet(10);
		//TailSet includes the given element
		System.out.println(&amp;quot;Tail Elements&amp;quot;);
		for(Integer i: cslsTailView)
		{
			System.out.println(i);
		}
	}
}</pre>
<p><strong>Output:</strong></p>
<pre class="brush: java; title: ; notranslate">Elements in the collections are
5
10
15
20
Floor    10
Ceiling  15
Lower    5
heigher  15
Head Elements
5
Tail Elements
10
15
20</pre>
<h2>NavigableMap and ConcurrentSkipListMap</h2>
<p>NaviagableMap is similar to NaviagableSet. In NavigableSet, methods use to return values, but in NaviagableMap methods used to return the key,value pair.ConcurrentSkipListMap is the one of the class which implements NaviagableMap.</p>
<pre class="brush: java; title: ; notranslate">import java.util.*;
import java.util.concurrent.*;

class NavigableMapExample
{
	public static void main(String[] args)
	{
		NavigableMap nm = new ConcurrentSkipListMap();
		nm.put(1,&amp;quot;One&amp;quot;);
		nm.put(2,&amp;quot;Two&amp;quot;);
		nm.put(3,&amp;quot;Three&amp;quot;);
		nm.put(4,&amp;quot;Four&amp;quot;);
		nm.put(5,&amp;quot;Five&amp;quot;);
		/* Retrieves the key,value pair immediately lesser than the given key */
		Map.Entry ae = nm.lowerEntry(5);
		/* Map.Entry is a Static interface nested inside Map
		   interface,just use to hold key and value */
		System.out.println(&amp;quot;Key&amp;quot; + ae.getKey());
		System.out.println(&amp;quot;Value&amp;quot;+	ae.getValue());
		/* Retrieves key,value pairs equal to and greater then the given key */
		SortedMap mm = nm.tailMap(3);
		Set s = mm.keySet();
		System.out.println(&amp;quot;Tail elements are&amp;quot;);
		for(Integer i:s)
		{
			System.out.println(&amp;quot;Key &amp;quot;+ i + &amp;quot;Value &amp;quot;+ mm.get(i));
		}
	}
}</pre>
<p><strong>output</strong></p>
<pre class="brush: java; title: ; notranslate">Key 4
Value Four
Tail elements are
Key 3  Value Three
Key 4  Value Four
Key 5  Value Five</pre>
<p>&nbsp;</p>
<pre class="brush: java; title: ; notranslate">Notes :
floorEntry method retrieves less than or equal to the givenkey (or) null
lowerEntry method retrieves always less than the givenkey (or) null
headMap method retrieves all elements less than  the givenkey
tailMap method retrieves all elements greater than or equal to the givenkey</pre>
<h2>AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry</h2>
<p>AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry are a static classes nested inside abstractMap class.The instance of this classes use to hold the key,value pair of one single entry in a Map.The difference between these two classes is that former one allow us to set the value and later one if we try to set the value, it throws UnsupportedOperationException</p>
<h2>Modified classes</h2>
<p>Classes are modified to implement the new interfaces in the existing classes.LinkedList is modified to implement Deque. TreeSet is modified to implement NavigableSet.TreeMap is modified to implement NavigableMap.In Collections 2 new methods newSetFromMap and asLifoQueue are added.</p>
<h2>Conclusion</h2>
<p>With java6.0 collections bi- directional traversal becomes easier and retrieval of elements in our desired way also possible. Some attention is also given towards Concurrent operations in Collection.</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/2007/03/what-is-new-in-java-6-0-collections-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
