<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>JB Tips</title>
	
	<link>http://www.javabeat.net/examples</link>
	<description />
	<lastBuildDate>Sun, 06 May 2012 06:00:14 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/JavabeatTips" /><feedburner:info uri="javabeattips" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId>JavabeatTips</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><item>
		<title>Embedding HTML into Java Swing Applications</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/sl3zyP3X4bs/</link>
		<comments>http://www.javabeat.net/examples/2012/05/06/embedding-html-into-java-swing-applications/#comments</comments>
		<pubDate>Sun, 06 May 2012 06:00:14 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[javafx]]></category>
		<category><![CDATA[webview]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1391</guid>
		<description><![CDATA[HTML in Swing applications? Yes, you have read it right. Swing doesn&#8217;t provide components to embed HTML and I have seen lot of people asking how can we add html content in Swing applications. Your concerns have been addressed by the latest release of JavaFX which is JavaFX 2.0. You might wonder what this JavaFX [...]
Related posts:<ol>
<li><a href='http://www.javabeat.net/examples/2007/10/26/customizing-dragging-and-dropping-for-swing-components/' rel='bookmark' title='Customizing Dragging and Dropping for Swing Components'>Customizing Dragging and Dropping for Swing Components</a></li>
<li><a href='http://www.javabeat.net/examples/2010/09/17/struts-html-text-areatag/' rel='bookmark' title='Struts HTML Text AreaTag (  &lt; html:textarea &gt;  )'>Struts HTML Text AreaTag (  &lt; html:textarea &gt;  )</a></li>
<li><a href='http://www.javabeat.net/examples/2010/09/21/struts-html-img-tag-htmlimg/' rel='bookmark' title='Struts HTML Img Tag ( &lt; html:img &gt;)'>Struts HTML Img Tag ( &lt; html:img &gt;)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/aYz2q5ekzKG6S4p8BVTJVB-RBzY/0/da"><img src="http://feedads.g.doubleclick.net/~a/aYz2q5ekzKG6S4p8BVTJVB-RBzY/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/aYz2q5ekzKG6S4p8BVTJVB-RBzY/1/da"><img src="http://feedads.g.doubleclick.net/~a/aYz2q5ekzKG6S4p8BVTJVB-RBzY/1/di" border="0" ismap="true"></img></a></p><p style="text-align: justify">HTML in Swing applications? Yes, you have read it right. Swing doesn&#8217;t provide components to embed HTML and I have seen lot of people asking how can we add html content in Swing applications. Your concerns have been addressed by the latest release of JavaFX which is JavaFX 2.0. You might wonder what this JavaFX is, so let me just touch upon that as well.</p>
<p style="text-align: justify">JavaFX is the RIA platform envisaged by Sun Microsystems as the next UI toolkit for Java, as Swing has been around for a long time and has started to age. The initiative was good, but was not rightly implemented. The JavaFX 1, 1.2, 1.3 or in general anything before 2.0 is no longer supported. Pre JavaFX 2.0 one had to use JavaFX Script to create the applications and these could invoke the Java API. But learning a new language altogether was not appealing for a Java developer as one couldn&#8217;t easily use with existing Java code base. In 2.0 the JavaFX Script was totally removed to make way for the Java based api for creating JavaFX components. Once you have setup the JavaFX SDK, you get to use the JavaFX specific API in the javafx.* packages. There are lot of cool things underneath the JavaFX platform, but that&#8217;s out of the scope of this article.</p>
<p style="text-align: justify">Coming back to our main focus, JavaFX provides a component called <a title="WebView" href="http://docs.oracle.com/javafx/2/api/javafx/scene/web/WebView.html" target="_blank">WebView</a> which with the help of <a title="WebEngine" href="http://docs.oracle.com/javafx/2/api/javafx/scene/web/WebEngine.html" target="_blank">WebEngine</a> can be used to load web pages along with constructing the DOM and running the required JavaScript. But that&#8217;s a JavaFX component. How is it going to help us in our Swing application? Exactly, JavaFX provides another component called <a title="JFXPanel" href="http://docs.oracle.com/javafx/2/api/javafx/embed/swing/JFXPanel.html" target="_blank">JFXPanel</a> which can be used to embed JavaFX components into Swing applications and in turn the JFXPanel is added to our JFrame or other Swing containers.</p>
<pre class="brush: java; title: ; notranslate">
JFrame myFrame = new JFrame();
JFXPanel myFXPanel = new JFXPanel():
myFrame.add(myFXPanel);
</pre>
<p>Now the required JavaFX components would be added to the JFXPanel. The JavaFX components are to be created only in the JavaFX Application thread and not in the main thread or the thread created using SwingUtilities.invokeLater. Before that lets just get familiar with a few JavaFX components which we would be using in this example:</p>
<ul>
<li><a title="JavaFX Scene" href="http://docs.oracle.com/javafx/2/api/javafx/scene/Scene.html" target="_blank">javafx.scene.Scene</a>: All components in the JavaFX application are represented as a scene graph &#8211; a collection of parent and child components. The Scene component is the container for the scene graph or the components, and we define the root for all these containers when we instantiate the Scene component.</li>
<li><a title="JavaFX BorderPane" href="http://docs.oracle.com/javafx/2/api/javafx/scene/layout/BorderPane.html" target="_blank">javafx.scene.layout.BorderPane</a>: Its the JavaFX&#8217;s version of all familiar Swing BorderLayout.</li>
</ul>
<p>So lets try to add a WebView component to the JFXPanel.</p>
<pre class="brush: java; title: ; notranslate">
Platform.runLater(new Runnable() {
  @Override
  public void run() {

    BorderPane borderPane = new BorderPane();
    WebView webComponent = new WebView();

    webComponent.getEngine().load(&quot;http://google.com/&quot;);

    borderPane.setCenter(webComponent);
    Scene scene = new Scene(borderPane,450,450);
    myFXPanel.setScene(scene);

  }
});
</pre>
<p style="text-align: justify">The Platform.runLater creates a JavaFX application thread, and this thread has to be used for all the JavaFX based operations (we can create multiple such threads, but yes, for any of the JavaFX related operation is carried out as part of this thread).</p>
<p style="text-align: justify">In the above snippet, we create an instance of BorderPane, set it as the root of scene when we create a Scene object and then add the WebView to the BorderPane. We also ask the WebEngine of the WebView to load the URL: www.google.com. The scene object is then added to the JFXPanel. Remember, that JFXPanel is alread added to the JFrame or some Swing components. So you have a Swing application loading your web pages.</p>
<p style="text-align: justify">Below is the complete code for loading web pages in Swing applications.</p>
<pre class="brush: java; title: ; notranslate">
import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.web.WebView;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingHtmlDemo {
  public static void main(String [] args){

    SwingUtilities.invokeLater(new Runnable() {
    @Override
      public void run() {
        ApplicationFrame mainFrame = new ApplicationFrame();
        mainFrame.setVisible(true);
      }
    });

  }

}

/**
* Main window used to display some HTML content.
*/
class ApplicationFrame extends JFrame{

  JFXPanel javafxPanel;
  WebView webComponent;
  JPanel mainPanel;

  JTextField urlField;
  JButton goButton;

  public ApplicationFrame(){

    javafxPanel = new JFXPanel();

    initSwingComponents();

    loadJavaFXScene();
  }

  /**
  * Instantiate the Swing compoents to be used
  */
  private void initSwingComponents(){
    mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    mainPanel.add(javafxPanel, BorderLayout.CENTER);

    JPanel urlPanel = new JPanel(new FlowLayout());
    urlField = new JTextField();
    urlField.setColumns(50);
    urlPanel.add(urlField);
    goButton = new JButton(&quot;Go&quot;);

    /**
     * Handling the loading of new URL, when the user
     * enters the URL and clicks on Go button.
     */
    goButton.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        Platform.runLater(new Runnable() {
          @Override
          public void run() {
            String url = urlField.getText();
            if ( url != null &amp;&amp; url.length() &gt; 0){
                webComponent.getEngine().load(url);
            }
          }
        });

      }
    });

    urlPanel.add(goButton);
    mainPanel.add(urlPanel, BorderLayout.NORTH);

    this.add(mainPanel);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setSize(700,600);
  }

  /**
  * Instantiate the JavaFX Components in
  * the JavaFX Application Thread.
  */
  private void loadJavaFXScene(){
    Platform.runLater(new Runnable() {
      @Override
      public void run() {

        BorderPane borderPane = new BorderPane();
        webComponent = new WebView();

        webComponent.getEngine().load(&quot;http://google.com/&quot;);

        borderPane.setCenter(webComponent);
        Scene scene = new Scene(borderPane,450,450);
        javafxPanel.setScene(scene);

      }
    });
  }
}
</pre>
<p>I used JavaFX SDK for Linux on Ubuntu and IntelliJ to develop this sample application. One can download the JavaFX SDK from <a title="JavaFX SDK" href="http://www.oracle.com/technetwork/java/javafx/downloads/devpreview-1429449.html" target="_blank">here</a>.</p>
<div style='clear:both'></div><p>Related posts:</p><ol>
<li><a href='http://www.javabeat.net/examples/2007/10/26/customizing-dragging-and-dropping-for-swing-components/' rel='bookmark' title='Customizing Dragging and Dropping for Swing Components'>Customizing Dragging and Dropping for Swing Components</a></li>
<li><a href='http://www.javabeat.net/examples/2010/09/17/struts-html-text-areatag/' rel='bookmark' title='Struts HTML Text AreaTag (  &lt; html:textarea &gt;  )'>Struts HTML Text AreaTag (  &lt; html:textarea &gt;  )</a></li>
<li><a href='http://www.javabeat.net/examples/2010/09/21/struts-html-img-tag-htmlimg/' rel='bookmark' title='Struts HTML Img Tag ( &lt; html:img &gt;)'>Struts HTML Img Tag ( &lt; html:img &gt;)</a></li>
</ol><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/sl3zyP3X4bs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/05/06/embedding-html-into-java-swing-applications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/05/06/embedding-html-into-java-swing-applications/</feedburner:origLink></item>
		<item>
		<title>Creating JSON document using Java and GSON API</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/JzcBleSU7Do/</link>
		<comments>http://www.javabeat.net/examples/2012/05/05/creating-json-document-using-java-and-gson-api/#comments</comments>
		<pubDate>Sat, 05 May 2012 06:00:37 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[gson]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JavaScript Object Notation (JSON)]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1383</guid>
		<description><![CDATA[We saw how to parse JSON using GSON API, in this post we would take a look at how the same GSON API can be used to create JSON from the Java objects. Please read this to get an idea of what GSON is. Diving right into the topic of this example, we would make use [...]
Related posts:<ol>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/' rel='bookmark' title='Parsing JSON using Java and GSON library'>Parsing JSON using Java and GSON library</a></li>
<li><a href='http://www.javabeat.net/examples/2012/05/01/invoking-restful-web-service-using-api-in-java-net-and-gson/' rel='bookmark' title='Invoking RESTful Web Service using API in java.net and GSON'>Invoking RESTful Web Service using API in java.net and GSON</a></li>
<li><a href='http://www.javabeat.net/examples/2012/05/03/using-jsonslurper-groovy-api-from-java-to-parse-json/' rel='bookmark' title='Using JsonSlurper Groovy API from Java to parse JSON'>Using JsonSlurper Groovy API from Java to parse JSON</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/aonXWJFIAGFXCIDnPFj8sQ7SX28/0/da"><img src="http://feedads.g.doubleclick.net/~a/aonXWJFIAGFXCIDnPFj8sQ7SX28/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/aonXWJFIAGFXCIDnPFj8sQ7SX28/1/da"><img src="http://feedads.g.doubleclick.net/~a/aonXWJFIAGFXCIDnPFj8sQ7SX28/1/di" border="0" ismap="true"></img></a></p><p>We saw how to <a title="Parsing JSON using Java and GSON library" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/">parse JSON</a> using GSON API, in this post we would take a look at how the same GSON API can be used to create JSON from the Java objects. Please read <a title="Parsing JSON using Java and GSON library" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/">this</a> to get an idea of what GSON is. Diving right into the topic of this example, we would make use of the toJson method of <strong>com.google.gson.Gson</strong> class. One of the overloaded versions of toJson() takes in an source of type Object and the type information which is of class java.lang.reflect.Type.</p>
<p>Lets define the model which would hold the data:</p>
<pre class="brush: java; title: ; notranslate">
class Book{

  @SerializedName(&quot;isbn&quot;)
  String isbn;

  @SerializedName(&quot;title&quot;)
  String title;

  @SerializedName(&quot;publication&quot;)
  String publication;

  @SerializedName(&quot;authors&quot;)
  String authors;

  public Book ( String isbn,
                String title,
                String publication,
                String authors)
  {
    this.isbn = isbn;
    this.title = title;
    this.publication = publication;
    this.authors = authors;
  }

}
</pre>
<p>We populate a list with some values for this model bean and this list would be converted to JSON output. Note the use of <strong>@SerializedName</strong> annotation in the model class. This indicates the name used for the attribute in the json output. We populate the list of books using:</p>
<pre class="brush: java; title: ; notranslate">
private static List&lt;Book&gt; populateBooks(){

  List&lt;Book&gt; myBooks = new ArrayList&lt;Book&gt;();
  Book book = new Book(&quot;007163360X&quot;,
                       &quot;Java Programming&quot;,
                       &quot;McGraw-Hill Osborne&quot;,
                       &quot;Dr (Poornachandra) Sarang&quot;);
  myBooks.add(book);

  book = new Book(&quot;1849516626&quot;,
                  &quot;Apache Tomcat 7 Essentials&quot;,
                  &quot;Tanuj Khare&quot;,
                  &quot;Packt Press&quot;);
  myBooks.add(book);

  book = new Book(&quot;007179431X&quot;,
                  &quot;Web Developer's Cookbook&quot;,
                  &quot;Robin Nixon&quot;,
                  &quot;McGraw-Hill Osborne&quot;);
  myBooks.add(book);

  book = new Book(&quot;9781935182962&quot;,
                  &quot;Practical Unit Testing&quot;,
                  &quot;Ken Rimple &amp; Srini Penchikala&quot;,
                  &quot;Manning&quot;);
  myBooks.add(book);

  return myBooks;
}
</pre>
<p>Once we have a list, we need to serialize it to JSON, for that we need to setup a Type information for generic List, this is not possible out of the box in Java and hence we would make use of <strong>com.google.gson.reflect.TypeToken</strong> class in the GSON API, to create the type information like:</p>
<pre class="brush: java; title: ; notranslate">
// Get the type information for the List&lt;Book&gt;
Type listType = new TypeToken&lt;List&lt;Book&gt;&gt;(){}.getType();
</pre>
<p>Next up is to use this type information along with the list of books and pass it to the toJson method to obtain the JSON output.</p>
<p>The complete code:</p>
<pre class="brush: java; title: ; notranslate">
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class JsonCreatorDemo {

  /**
  * Populate the Books information into a List
  * @return
  */
  private static List&lt;Book&gt; populateBooks(){

    List&lt;Book&gt; myBooks = new ArrayList&lt;Book&gt;();
    Book book = new Book(&quot;007163360X&quot;,
                         &quot;Java Programming&quot;,
                         &quot;McGraw-Hill Osborne&quot;,
                         &quot;Dr (Poornachandra) Sarang&quot;);
    myBooks.add(book);

    book = new Book(&quot;1849516626&quot;,
                    &quot;Apache Tomcat 7 Essentials&quot;,
                    &quot;Tanuj Khare&quot;,
                    &quot;Packt Press&quot;);
    myBooks.add(book);

    book = new Book(&quot;007179431X&quot;,
                    &quot;Web Developer's Cookbook&quot;,
                    &quot;Robin Nixon&quot;,
                    &quot;McGraw-Hill Osborne&quot;);
    myBooks.add(book);

    book = new Book(&quot;9781935182962&quot;,
                    &quot;Practical Unit Testing&quot;,
                    &quot;Ken Rimple &amp; Srini Penchikala&quot;,
                    &quot;Manning&quot;);
    myBooks.add(book);

    return myBooks;
  }

  public static void main(String [] args){

    List&lt;Book&gt; myBooks = populateBooks();

    Gson myGson = new Gson();

    // Get the type information for the List&lt;Book&gt;
    Type listType = new TypeToken&lt;List&lt;Book&gt;&gt;(){}.getType();

    // Serialize the List of books into JSON
    System.out.println(myGson.toJson(myBooks,listType));

  }
}

class Book{

  @SerializedName(&quot;isbn&quot;)
  String isbn;

  @SerializedName(&quot;title&quot;)
  String title;

  @SerializedName(&quot;publication&quot;)
  String publication;

  @SerializedName(&quot;authors&quot;)
  String authors;

  public Book ( String isbn,
                String title,
                String publication,
                String authors)
  {
    this.isbn = isbn;
    this.title = title;
    this.publication = publication;
    this.authors = authors;
  }

}
</pre>
<p>JSON Output:</p>
<pre class="brush: jscript; title: ; notranslate">
[
  {
    &quot;isbn&quot;:&quot;007163360X&quot;,
    &quot;title&quot;:&quot;Java Programming&quot;,
    &quot;publication&quot;:&quot;McGraw-Hill Osborne&quot;,
    &quot;authors&quot;:&quot;Dr (Poornachandra) Sarang&quot;
  },
  {
    &quot;isbn&quot;:&quot;1849516626&quot;,
    &quot;title&quot;:&quot;Apache Tomcat 7 Essentials&quot;,
    &quot;publication&quot;:&quot;Tanuj Khare&quot;,
    &quot;authors&quot;:&quot;Packt Press&quot;
  },
  {
    &quot;isbn&quot;:&quot;007179431X&quot;,
    &quot;title&quot;:&quot;Web Developer\u0027s Cookbook&quot;,
    &quot;publication&quot;:&quot;Robin Nixon&quot;,
    &quot;authors&quot;:&quot;McGraw-Hill Osborne&quot;
  },
  {
    &quot;isbn&quot;:&quot;9781935182962&quot;,
    &quot;title&quot;:&quot;Practical Unit Testing&quot;,
    &quot;publication&quot;:&quot;Ken Rimple \u0026 Srini Penchikala&quot;,
    &quot;authors&quot;:&quot;Manning&quot;
  }
]
</pre>
<div style='clear:both'></div><p>Related posts:</p><ol>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/' rel='bookmark' title='Parsing JSON using Java and GSON library'>Parsing JSON using Java and GSON library</a></li>
<li><a href='http://www.javabeat.net/examples/2012/05/01/invoking-restful-web-service-using-api-in-java-net-and-gson/' rel='bookmark' title='Invoking RESTful Web Service using API in java.net and GSON'>Invoking RESTful Web Service using API in java.net and GSON</a></li>
<li><a href='http://www.javabeat.net/examples/2012/05/03/using-jsonslurper-groovy-api-from-java-to-parse-json/' rel='bookmark' title='Using JsonSlurper Groovy API from Java to parse JSON'>Using JsonSlurper Groovy API from Java to parse JSON</a></li>
</ol><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/JzcBleSU7Do" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/05/05/creating-json-document-using-java-and-gson-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/05/05/creating-json-document-using-java-and-gson-api/</feedburner:origLink></item>
		<item>
		<title>Whats new in Java 7 – try-with-resource construct in Project Coin</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/HmrP0UrAiHs/</link>
		<comments>http://www.javabeat.net/examples/2012/05/04/whats-new-in-java-7-try-with-resource-construct-in-project-coin/#comments</comments>
		<pubDate>Fri, 04 May 2012 06:00:47 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[java 7]]></category>
		<category><![CDATA[project coin]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1374</guid>
		<description><![CDATA[In our previous post we looked at different features added as part of Project Coin, in this post we will look at another language construct added as part of Java 7 and Project Coin in particular. It is the try-with-resource construct also called as Automatic Resource Management. Before getting into the details of the construct, [...]
Related posts:<ol>
<li><a href='http://www.javabeat.net/examples/2012/05/02/whats-new-in-java-7-features-as-part-of-project-coin/' rel='bookmark' title='What&#8217;s new in Java 7- Features as part of Project Coin'>What&#8217;s new in Java 7- Features as part of Project Coin</a></li>
<li><a href='http://www.javabeat.net/examples/2010/10/03/struts-bean-resource-tag-beanresource/' rel='bookmark' title='Struts BEAN Resource Tag ( &lt; bean:resource &gt;)'>Struts BEAN Resource Tag ( &lt; bean:resource &gt;)</a></li>
<li><a href='http://www.javabeat.net/examples/2008/04/12/how-to-use-resource-bundle-in-jsf/' rel='bookmark' title='How to use Resource Bundle in JSF?'>How to use Resource Bundle in JSF?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/Kf1_4FA3FWBOK3CZHobvuJij9go/0/da"><img src="http://feedads.g.doubleclick.net/~a/Kf1_4FA3FWBOK3CZHobvuJij9go/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/Kf1_4FA3FWBOK3CZHobvuJij9go/1/da"><img src="http://feedads.g.doubleclick.net/~a/Kf1_4FA3FWBOK3CZHobvuJij9go/1/di" border="0" ismap="true"></img></a></p><p style="text-align: justify">In our <a title="What’s new in Java 7- Features as part of Project Coin" href="http://www.javabeat.net/examples/2012/05/02/whats-new-in-java-7-features-as-part-of-project-coin/">previous post</a> we looked at different features added as part of Project Coin, in this post we will look at another language construct added as part of Java 7 and Project Coin in particular. It is the <a title="Try-with-resource" href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html" target="_blank">try-with-resource</a> construct also called as Automatic Resource Management. Before getting into the details of the construct, let me show you some basic code which I would be using through out this example.</p>
<p style="text-align: justify">Lets create a class called Resource which implements Closeable interface and its a dummy resource class something on liens of a FileReader or your other IO classes. Lets also have a custom exception say SomeException which extends Exception class. The code for the two is as follows:</p>
<pre class="brush: java; title: ; notranslate">
class Resource implements Closeable{

  public String resourceName;
  public Resource(String resourceName) throws SomeException{
    this.resourceName = resourceName;
    System.out.println(this.resourceName+&quot; created!
                                Might throw an exception&quot;);
  }

  public void useResource() {
    System.out.println(&quot;Using the resource &quot;+this.resourceName);
  }

  @Override
  public void close() throws IOException {
    System.out.println(&quot;Closing the resource &quot;+this.resourceName);
  }
}

class SomeException extends Exception{
}
</pre>
<p>Suppose I wanted to create an instance of Resource and use it, prior to the try-with-resource construct we would do something like:</p>
<pre class="brush: java; title: ; notranslate">
Resource myResource = null;
try{
  myResource = new Resource(&quot;POOR OLD RESOURCE&quot;);
  myResource.useResource();
}catch(SomeException ex){
  ex.printStackTrace();
}finally {
  if (myResource != null) {
    try {
      myResource.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
</pre>
<p>Output:</p>
<pre class="brush: bash; title: ; notranslate">
POOR OLD RESOURCE created! Might throw an exception
Using the resource POOR OLD RESOURCE
Closing the resource POOR OLD RESOURCE
</pre>
<p style="text-align: justify">We generally clear all the resources in the finally block because that is the one which is called irrespective of the exception being thrown or not. But close() method in the Closeable interface itself throws an IOException which makes us to use another try..catch block in the finally method. Now, if both the try block and the catch block throw exception, prior to Java 7 the one thrown in the try block would have been <strong>suppressed</strong> by the one thrown in the catch block. In Java 7 there&#8217;s has been a new API added to Throwable which states- getSuppressedExeceptions. Let me not go into those details now. Coming back to our try-with-resources construct, the above code can be written concisely as:</p>
<pre class="brush: java; title: ; notranslate">
try ( Resource myResource2 = new Resource(&quot;TRY-WITH-RESOURCE&quot;)){
  myResource2.useResource();
}catch ( SomeException | IOException ex){
  ex.printStackTrace();
}
</pre>
<p>Output:</p>
<pre class="brush: bash; title: ; notranslate">
TRY-WITH-RESOURCE created! Might throw an exception
Using the resource TRY-WITH-RESOURCE
Closing the resource TRY-WITH-RESOURCE
</pre>
<p>Look at the reduction in the number of lines, and also it makes the code more readable. The construct:</p>
<pre class="brush: java; title: ; notranslate">
try ( Resource myResource2 = new Resource(&quot;TRY-WITH-RESOURCE&quot;))
</pre>
<p>is the new construct added as part of Project Coin. One can use and declare multiple resource within the try block.</p>
<pre class="brush: java; title: ; notranslate">
try ( Resource myResource2 = new Resource(&quot;TRY-WITH-RESOURCE&quot;);
      Resource myResource3 = new Resource(&quot;TRY-WITH-RESOURCE2&quot;))
</pre>
<p>The complete code can be downloaded from <a title="try-with-resource code" href="https://gist.github.com/2578499" target="_blank">here</a>.</p>
<div style='clear:both'></div><p>Related posts:</p><ol>
<li><a href='http://www.javabeat.net/examples/2012/05/02/whats-new-in-java-7-features-as-part-of-project-coin/' rel='bookmark' title='What&#8217;s new in Java 7- Features as part of Project Coin'>What&#8217;s new in Java 7- Features as part of Project Coin</a></li>
<li><a href='http://www.javabeat.net/examples/2010/10/03/struts-bean-resource-tag-beanresource/' rel='bookmark' title='Struts BEAN Resource Tag ( &lt; bean:resource &gt;)'>Struts BEAN Resource Tag ( &lt; bean:resource &gt;)</a></li>
<li><a href='http://www.javabeat.net/examples/2008/04/12/how-to-use-resource-bundle-in-jsf/' rel='bookmark' title='How to use Resource Bundle in JSF?'>How to use Resource Bundle in JSF?</a></li>
</ol><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/HmrP0UrAiHs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/05/04/whats-new-in-java-7-try-with-resource-construct-in-project-coin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/05/04/whats-new-in-java-7-try-with-resource-construct-in-project-coin/</feedburner:origLink></item>
		<item>
		<title>Using JsonSlurper Groovy API from Java to parse JSON</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/OLF0waH-13o/</link>
		<comments>http://www.javabeat.net/examples/2012/05/03/using-jsonslurper-groovy-api-from-java-to-parse-json/#comments</comments>
		<pubDate>Thu, 03 May 2012 06:00:28 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JavaScript Object Notation (JSON)]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1309</guid>
		<description><![CDATA[We have seen here on how to parse JSON in Java using Gson and here on how to parse JSON in Groovy. I also touched upon in brief about Groovy here. The beauty of these JVM languages is that one can invoke these APIs from Java, the only requirement is that you need to have [...]
Related posts:<ol>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/' rel='bookmark' title='Parsing JSON using Groovy'>Parsing JSON using Groovy</a></li>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/' rel='bookmark' title='Parsing JSON using Java and GSON library'>Parsing JSON using Java and GSON library</a></li>
<li><a href='http://www.javabeat.net/examples/2012/05/01/invoking-restful-web-service-using-api-in-java-net-and-gson/' rel='bookmark' title='Invoking RESTful Web Service using API in java.net and GSON'>Invoking RESTful Web Service using API in java.net and GSON</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/2Xy3LURu6Yc68GfYoU8dx38Kdog/0/da"><img src="http://feedads.g.doubleclick.net/~a/2Xy3LURu6Yc68GfYoU8dx38Kdog/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/2Xy3LURu6Yc68GfYoU8dx38Kdog/1/da"><img src="http://feedads.g.doubleclick.net/~a/2Xy3LURu6Yc68GfYoU8dx38Kdog/1/di" border="0" ismap="true"></img></a></p><p style="text-align: justify">We have seen <a title="Parsing JSON using Java and GSON library" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/" target="_blank">here</a> on how to parse JSON in Java using Gson and <a title="Parsing JSON using Groovy" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/" target="_blank">here</a> on how to parse JSON in Groovy. I also touched upon in brief about Groovy <a title="Parsing JSON using Groovy" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/" target="_blank">here</a>. The beauty of these JVM languages is that one can invoke these APIs from Java, the only requirement is that you need to have the language jar on the classpath. In our example below we use <a title="JsonSlurper Code" href="https://github.com/groovy/groovy-core/blob/master/src/main/groovy/json/JsonSlurper.java" target="_blank">JsonSlurper</a> in Groovy to parse the JSON documents from Java. Sounds cool right! In one of the talks on Functional Programming, <a title="Venkat Subramaniam" href="http://twitter.com/#!/venkat_s" target="_blank">Venkat</a> showed us how we could exploit the Software Transactional Memory feature in Clojure to create concurrent applications in Java with less pain.</p>
<p style="text-align: justify">With so many <a title="JVM Languages" href="http://radar.oreilly.com/2011/07/jvm-languages.html" target="_blank">JVM languages</a> coming up i.e languages which run on JVM, developers are more becoming ployglot i.e use multiple langauges in their code. Going on same lines, in the below example I show you how we could exploit the JSON API in Groovy and use it in our Java program. So all you readers out there keep in mind to add the language specific jar to your classpath. This jar tells the compiler where to find the required API information. For Groovy you can download the required Groovy Development Kit from <a title="Groovy Download" href="http://groovy.codehaus.org/Download" target="_blank">here</a>. Let GROOVY_HOME be the home directory of your Groovy installation. You would find a jar in the GROOVY_HOME/embeddable folder which would be named like: groovy-all-&lt;version&gt;.jar. This is the jar which you need to add it to the classpath for your Java code to find the right APIs.</p>
<p style="text-align: justify">If you are not familiar with JSON, do stop by to read about it <a title="What is JavaScript Object Notation (JSON)?" href="http://www.javabeat.net/examples/2012/04/28/what-is-javascript-object-notation-json/" target="_blank">here</a>, if you are not familiar with Json parsing in Groovy, do read it over <a title="Parsing JSON using Groovy" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/" target="_blank">here</a>.</p>
<p style="text-align: justify">The json document which I used is:</p>
<pre class="brush: jscript; title: ; notranslate">
[
  {
    &quot;id&quot;:&quot;6253282&quot;,
    &quot;name&quot;:&quot;Twitter API&quot;,
    &quot;screen_name&quot;:&quot;twitterapi&quot;,
    &quot;url&quot;:&quot;http:\/\/dev.twitter.com&quot;,
    &quot;followers_count&quot;:1004641,
    &quot;friends_count&quot;:33,
    &quot;favourites_count&quot;:24,
    &quot;statuses_count&quot;:3277
  },
  {
    &quot;id&quot;:&quot;15082387&quot;,
    &quot;name&quot;:&quot;Sanaulla&quot;,
    &quot;screen_name&quot;:&quot;sanaulla&quot;,
    &quot;url&quot;:&quot;http:\/\/blog.sanaulla.info&quot;,
    &quot;followers_count&quot;:241,
    &quot;friends_count&quot;:302,
    &quot;favourites_count&quot;:41,
    &quot;statuses_count&quot;:1876

  }
]
</pre>
<p>The Java code which does the parsing is:</p>
<pre class="brush: java; title: ; notranslate">
import groovy.json.JsonSlurper;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import java.util.Map;

public class JavaJsonParserDemo {

  public static void main(String [] args){

    String jsonSrouce = &quot;/home/mohamed/twitterUser.json&quot;;
    JsonSlurper jsonParser = new JsonSlurper();
    try {
      List&lt;Map&gt; parsedData = (List&lt;Map&gt;)jsonParser.parse( new FileReader(jsonSrouce));
      for ( Map aObject : parsedData){
        System.out.println(aObject);
        System.out.println(aObject.get(&quot;screen_name&quot;));
      }
    }catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
}
</pre>
<p style="text-align: justify">If you happen to explore the source of JsonSlurper <a title="JsonSlurper Code" href="https://github.com/groovy/groovy-core/blob/master/src/main/groovy/json/JsonSlurper.java" target="_blank">here</a>, you can see that the parse() method invokes either parseObject() or parseArray(). In our sample JSON it would invoke parseArray(), which would return some List. Looking into parseArray() we can find that the List is actually a List of Maps. Keeping this in mind, the declaration used above is List.</p>
<p style="text-align: justify">Running this program the output would be:</p>
<pre class="brush: bash; title: ; notranslate">
{id=6253282, favourites_count=24, friends_count=33, name=Twitter API,
screen_name=twitterapi, statuses_count=3277, followers_count=1004641,
url=http://dev.twitter.com}
twitterapi
{id=15082387, favourites_count=41, friends_count=302, name=Sanaulla,
screen_name=sanaulla, statuses_count=1876, followers_count=241,
url=http://blog.sanaulla.info}
sanaulla
</pre>
<div style='clear:both'></div><p>Related posts:</p><ol>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/' rel='bookmark' title='Parsing JSON using Groovy'>Parsing JSON using Groovy</a></li>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/' rel='bookmark' title='Parsing JSON using Java and GSON library'>Parsing JSON using Java and GSON library</a></li>
<li><a href='http://www.javabeat.net/examples/2012/05/01/invoking-restful-web-service-using-api-in-java-net-and-gson/' rel='bookmark' title='Invoking RESTful Web Service using API in java.net and GSON'>Invoking RESTful Web Service using API in java.net and GSON</a></li>
</ol><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/OLF0waH-13o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/05/03/using-jsonslurper-groovy-api-from-java-to-parse-json/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/05/03/using-jsonslurper-groovy-api-from-java-to-parse-json/</feedburner:origLink></item>
		<item>
		<title>What’s new in Java 7- Features as part of Project Coin</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/SIJvqh1wJwE/</link>
		<comments>http://www.javabeat.net/examples/2012/05/02/whats-new-in-java-7-features-as-part-of-project-coin/#comments</comments>
		<pubDate>Wed, 02 May 2012 06:00:24 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[Java 7.0]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[java 7]]></category>
		<category><![CDATA[project coin]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1281</guid>
		<description><![CDATA[As part of the Project Coin, there were quite a few language enhancements were added to the Language. The last time Java language changed was in the Java 5 release when Generics were added. The changes in introduced in the Java 7 were welcomed by java community around the world. This was seen as a stepping [...]
No related posts.]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/HWdms5g20ZSG6PuJaUpqQGeHolM/0/da"><img src="http://feedads.g.doubleclick.net/~a/HWdms5g20ZSG6PuJaUpqQGeHolM/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/HWdms5g20ZSG6PuJaUpqQGeHolM/1/da"><img src="http://feedads.g.doubleclick.net/~a/HWdms5g20ZSG6PuJaUpqQGeHolM/1/di" border="0" ismap="true"></img></a></p><p style="text-align: justify">As part of the <a title="Project Coin" href="http://openjdk.java.net/projects/coin/" target="_blank">Project Coin</a>, there were quite a few language enhancements were added to the Language. The last time Java language changed was in the Java 5 release when Generics were added. The changes in introduced in the Java 7 were welcomed by java community around the world. This was seen as a stepping stone to the plethora of changes to be introduced with Java 8 and above. Nonetheless Java 7 has its own set of <a title="Java 7 issues" href="http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#knownissues" target="_blank">issues</a>, but this shouldn&#8217;t be a concern for someone to <a title="Java 7 latest build" href="http://jdk7.java.net/download.html" target="_blank">download</a> the latest build and give it a shot.</p>
<p style="text-align: justify">In this post I would like to pick a few features added as part of Project Coin and in the coming posts try to cover the remaining features. The enhancements we would be looking at are:</p>
<ul>
<li>String in Switch statements.</li>
<li>Generic Type Inference (Diamond Operator)</li>
<li>Multi Catch blocks</li>
<li>Binary Integral literals and underscores in numeric literals.</li>
</ul>
<p><strong>Generic Type Inference (Diamond Operator)</strong><br />
Pre Java 7, for a map of string versus list of integers we would have a declaration like:</p>
<pre class="brush: java; title: ; notranslate">
Map&lt;Stirng,List&lt;Integer&gt;&gt; myMap = new HashMap&lt;Stirng,List&lt;Integer&gt;&gt;();
</pre>
<p>we could also write:</p>
<pre class="brush: java; title: ; notranslate">
Map&lt;Stirng,List&lt;Integer&gt;&gt; myMap = new HashMap();
</pre>
<p>But for the above code the compiler would issue an warning:</p>
<pre class="brush: bash; title: ; notranslate">Note: Java7FeatureDemo.java uses unchecked or unsafe operations.</pre>
<p>With Java 7, the above declaration is equivalent to:</p>
<pre class="brush: java; title: ; notranslate">
Map&lt;Stirng,List&lt;Integer&gt;&gt; myMap = new HashMap&lt;&gt;();
</pre>
<p>The compiler now would inference the type based on the declaration on the left. This is in my opinion is a good step towards <a href="http://marxsoftware.blogspot.in/2011/03/jdk-7-diamond-operator.html" target="_blank">removing redundancy</a> in the declaration.</p>
<p>If you are using a IDE which supports Java 7 language enhancements, in my case I was using <a title="IntelliJ" href="http://www.jetbrains.com/idea/" target="_blank">IntelliJ</a>, when you use the pre Java 7 type of declaration it suggests:</p>
<p><a href="http://www.javabeat.net/examples/wp-content/uploads/2012/05/Java7Diamond.png"><img class="alignnone  wp-image-1294" src="http://www.javabeat.net/examples/wp-content/uploads/2012/05/Java7Diamond-300x82.png" alt="Java 7 - Diamond Operator" width="500" height="100" /></a></p>
<p><strong>Strings in switch:</strong><br />
Prior to Java 7, we didn&#8217;t have an option to use Strings in switch. An alternative approach was to use enums in the switch statement:</p>
<pre class="brush: java; title: ; notranslate">
public class PreJava7 {
  enum GRADE{
    A,B,C,D;
  }

  public static void main(String[] args){

    GRADE choice = GRADE.A;

    switch (choice){
      case A:
        System.out.println(&quot;A chosen&quot;);
        break;
      case B:
        System.out.println(&quot;B chosen&quot;);
        break;
      case C:
        System.out.println(&quot;C chosen&quot;);
        break;
    }
  }
}
</pre>
<p>With Java 7 the same code can be written as:</p>
<pre class="brush: java; title: ; notranslate">
String choice = &quot;A&quot;;

switch (choice){
  case &quot;A&quot;:
    System.out.println(&quot;A chosen&quot;);
    break;
  case &quot;B&quot;:
    System.out.println(&quot;B chosen&quot;);
    break;
  case &quot;C&quot;:
    System.out.println(&quot;C chosen&quot;);
    break;
}
</pre>
<p><strong>Multi Catch blocks:</strong><br />
If a code block throws multiple exceptions and you want all of the catch blocks to do the same operation, say logging the exception, we would write something like:</p>
<pre class="brush: java; title: ; notranslate">
public class PreJava7 {
  public static void main(String[] args){
    try {
      exceptionMethod1();
      exceptionMethod2();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (NoSuchFieldException e) {
      e.printStackTrace();
    }

  }
  static void exceptionMethod1() throws IOException{}
  static void exceptionMethod2() throws NoSuchFieldException{}
}
</pre>
<p>Look at the redundancy of code in both the catch blocks. With the introduction of Mutli catch blocks, the same catch block can be used to capture multiple exceptions thereby leading to code reuse. So the modified code would be:</p>
<pre class="brush: java; title: ; notranslate">
try {
  exceptionMethod1();
  exceptionMethod2();
} catch (IOException | NoSuchFieldException e) {
  e.printStackTrace();
}
</pre>
<p>If you use an IDE which supports Java 7 features, then using multiple catch blocks would generate the suggestion as follows:<br />
<a href="http://www.javabeat.net/examples/wp-content/uploads/2012/05/Java7_Idenctical.png"><img class="alignnone  wp-image-1298" src="http://www.javabeat.net/examples/wp-content/uploads/2012/05/Java7_Idenctical-300x57.png" alt="Java 7 Multiple Catch Blocks" width="500" height="100" /></a></p>
<p><strong>Binary Integral literals and underscores in numeric literals</strong>:<br />
Binary literals can be represented by using <strong>b</strong> or <strong>B</strong>, just like the way we used <strong>x</strong> for Hexadecimal literals.</p>
<pre class="brush: java; title: ; notranslate">
int binary1 = 0b011;
int binary2 = 0B111;

System.out.println(binary1);
System.out.println(binary2);
</pre>
<p>Now coming to the underscores in numeric literals:<br />
Pre Java 7, we would write something like:</p>
<pre class="brush: java; title: ; notranslate">
int hugeNumber = 1000000000;
</pre>
<p>A trivia now: How fast can you count the number of zeros in hugeNumber? The time taken to count the number increases with the age of a person. Jokes apart, lets see how this is can be changed with Java 7 enhancement:</p>
<pre class="brush: java; title: ; notranslate">
int hugeNumber2 = 1_000_000_000;
System.out.println(hugeNumber == hugeNumber2);//Prints True
</pre>
<p>So, how easy is it now to count the number of zeros?</p>
<p>These were some of the few enhancements added as part of <a title="Project Coin" href="http://openjdk.java.net/projects/coin/" target="_blank">Project Coin</a> in Java 7 release. There are few more features which were pushed to Java 8 and another feature try-with-resources ( Automatic Resource Management) which is part of Java 7 and I would write about it in my upcoming posts.</p>
<p>If you are interested in obtaining a fully functional code, please do it from <a title="Java 7 Example" href="https://gist.github.com/2569878" target="_blank">here</a>.<br />
Note: In order to run the examples given above you need to download the JDK 7 from <a title="JDK 7 download" href="http://www.oracle.com/technetwork/java/javase/downloads/index.html" target="_blank">here</a>.</p>
<div style='clear:both'></div><p>No related posts.</p><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/SIJvqh1wJwE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/05/02/whats-new-in-java-7-features-as-part-of-project-coin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/05/02/whats-new-in-java-7-features-as-part-of-project-coin/</feedburner:origLink></item>
		<item>
		<title>Invoking RESTful Web Service using API in java.net and GSON</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/1bkTUVNhGvA/</link>
		<comments>http://www.javabeat.net/examples/2012/05/01/invoking-restful-web-service-using-api-in-java-net-and-gson/#comments</comments>
		<pubDate>Tue, 01 May 2012 06:00:14 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[gson]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JavaScript Object Notation (JSON)]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1204</guid>
		<description><![CDATA[In our previous post, we wrote about parsing JSON using Java and GSON library. Moving further, in this article we will look at how to use classes in java.net package to invoke a RESTful Web Service and then parse the JSON response using GSON library. For this we make use of the Twitter REST API [...]
Related posts:<ol>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/' rel='bookmark' title='Parsing JSON using Java and GSON library'>Parsing JSON using Java and GSON library</a></li>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/' rel='bookmark' title='Parsing JSON using Groovy'>Parsing JSON using Groovy</a></li>
<li><a href='http://www.javabeat.net/examples/2008/05/22/java-messaging-servicejms/' rel='bookmark' title='Java Messaging Service(JMS)'>Java Messaging Service(JMS)</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/z6m-hiIZRaQiGAJUQIs0spBYq7Y/0/da"><img src="http://feedads.g.doubleclick.net/~a/z6m-hiIZRaQiGAJUQIs0spBYq7Y/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/z6m-hiIZRaQiGAJUQIs0spBYq7Y/1/da"><img src="http://feedads.g.doubleclick.net/~a/z6m-hiIZRaQiGAJUQIs0spBYq7Y/1/di" border="0" ismap="true"></img></a></p><p style="text-align: justify;">In our <a title="Parsing JSON using Java and GSON library" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/">previous post</a>, we wrote about parsing JSON using Java and <a href="http://code.google.com/p/google-gson/" target="_blank">GSON library</a>. Moving further, in this article we will look at how to use classes in java.net package to invoke a <strong>RESTful Web Service</strong> and then parse the <strong>JSON</strong> response using GSON library. For this we make use of the <a href="https://dev.twitter.com/" target="_blank">Twitter REST API</a> and more specifically <a href="https://dev.twitter.com/docs/api/1/get/statuses/user_timeline" target="_blank">statuses/user_timeline</a> API. A bit about the API:</p>
<p style="text-align: justify;"><strong>GET status/user_timeline</strong>: Returns the 20 most recent statuses posted by the authenticating user. It is also possible to request another user&#8217;s timeline by using the screen_name or user_id parameter. The other users timeline will only be visible if they are not protected, or if the authenticating user&#8217;s follow request was accepted by the protected user.</p>
<p style="text-align: justify;">The resource URL is: http://api.twitter.com/1/statuses/user_timeline.format</p>
<p>The API returns lot of data, but we are interested in only the status text and the created date. Keeping that in mind, our model class will be:</p>
<pre class="brush: java; title: ; notranslate">
class Tweet{
  public String text;
  public String created_at;
  public String toString(){
    return &quot;Posted &quot;+text+&quot; at &quot;+created_at;
  }
}
</pre>
<p>The example can be divided into:</p>
<ol>
<li>Take screen name input from the user and construct the URL for the API which we call as the fetchURL.</li>
<li>Use URLConnection class and its connect() and getInputSteam() APIs to connect to the fetchURL and then obtain the input stream.</li>
<li>The input stream obtained above is used to construct the JsonReader object( from the GSON library).</li>
<li>Then parse the JSON as explained <a title="Parsing JSON using Java and GSON library" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/">here</a>.</li>
</ol>
<p><strong>Invoking the REST API:</strong></p>
<pre class="brush: java; title: ; notranslate">String fetchUrl =
  &quot;http://api.twitter.com/1/statuses/user_timeline.json?screen_name=&quot;;
//this.screenName is obtained as a user input
fetchUrl = fetchUrl+this.screenName;
URLConnection urlConnection =  new URL(fetchUrl).openConnection();
urlConnection.connect();</pre>
<p style="text-align: justify;">One can see that to invoke a REST web service, we need not have to use any other APIs then then ones provided in the java.net package. There are a lot of libraries available for invoking and creating REST APIs. But in this example we stick with java.net package. This simplicity is due to the fact that REST APIs are based on top of HTTP related protocols and uses GET, POST, PUT, DELETE and other methods supported by HTTP.</p>
<p><strong>Parsing the JSON response:</strong></p>
<pre class="brush: java; title: ; notranslate">JsonReader reader = new JsonReader(
      new InputStreamReader(urlConnection.getInputStream()));
JsonParser parser = new JsonParser();
JsonElement rootElement = parser.parse(reader);
JsonArray tweetsJson = rootElement.getAsJsonArray();</pre>
<p><strong>Populate the required model instances and add them to the List of tweets (or List&lt;Tweet&gt;).</strong></p>
<pre class="brush: java; title: ; notranslate">List timeline = new ArrayList();
Gson myGson = new Gson();
for ( JsonElement tweetElement : tweetsJson){
  Tweet myTweet = myGson.fromJson(tweetElement, Tweet.class);
  timeline.add(myTweet);
}</pre>
<p>Read <a title="Parsing JSON using Java and GSON library" href="http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/">here</a> for details on parsing the JSON using Java and GSON API.</p>
<p>Here is the complete code:</p>
<pre class="brush: java; title: ; notranslate">
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class RestfulDemo {
  public static void main(String [] args) throws IOException{
    Scanner commandlineReader = new Scanner(System.in);
    System.out.println(&quot;Enter the screen name&quot;);
    String screenName = commandlineReader.nextLine();
    TwitterTimeline myTimeline = new TwitterTimeline(screenName);
    myTimeline.fetchTimeline();
    for ( Tweet myTweet : myTimeline.timeline){
      System.out.println(myTweet);
    }
  }
}

class TwitterTimeline {
  public String screenName;
  public List timeline;
  private String fetchUrl =
  &quot;http://api.twitter.com/1/statuses/user_timeline.json?screen_name=&quot;;
  TwitterTimeline( String screenName) {
    this.screenName = screenName;
  }

  public void fetchTimeline() throws IOException {
    fetchUrl = fetchUrl+this.screenName;
    URLConnection urlConnection =  new URL(fetchUrl).openConnection();
    urlConnection.connect();
    JsonReader reader = new JsonReader(
         new InputStreamReader(urlConnection.getInputStream()));
    JsonParser parser = new JsonParser();
    JsonElement rootElement = parser.parse(reader);
    JsonArray tweetsJson = rootElement.getAsJsonArray();
    timeline = new ArrayList();
    Gson myGson = new Gson();
    for ( JsonElement tweetElement : tweetsJson){
      Tweet myTweet = myGson.fromJson(tweetElement, Tweet.class);
      timeline.add(myTweet);
     }
  }
}
/*
 * Model class for a Tweet
 */
class Tweet {
  public String text;
  public String created_at;
  public String toString(){
    return &quot;Posted &quot;+text+&quot; at &quot;+created_at;
  }
}
</pre>
<p>Note: Make sure you have GSON library in the classpath.</p>
<p>Also if you have any issues while trying out this example, do drop a comment here and we will get back to you at the earliest.</p>
<div style='clear:both'></div><p>Related posts:</p><ol>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/' rel='bookmark' title='Parsing JSON using Java and GSON library'>Parsing JSON using Java and GSON library</a></li>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/' rel='bookmark' title='Parsing JSON using Groovy'>Parsing JSON using Groovy</a></li>
<li><a href='http://www.javabeat.net/examples/2008/05/22/java-messaging-servicejms/' rel='bookmark' title='Java Messaging Service(JMS)'>Java Messaging Service(JMS)</a></li>
</ol><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/1bkTUVNhGvA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/05/01/invoking-restful-web-service-using-api-in-java-net-and-gson/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/05/01/invoking-restful-web-service-using-api-in-java-net-and-gson/</feedburner:origLink></item>
		<item>
		<title>Parsing JSON using Groovy</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/9srpMWbgsuk/</link>
		<comments>http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 09:33:02 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1171</guid>
		<description><![CDATA[In our previous post we saw how we used Gson API to parse the Json using Java. Not spending too much time on the introduction, I would want to straight away dive into the same parsing which can be done using Groovy language. Groovy is a scripting language which runs on the JVM. It can [...]
Related posts:<ol>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/' rel='bookmark' title='Parsing JSON using Java and GSON library'>Parsing JSON using Java and GSON library</a></li>
<li><a href='http://www.javabeat.net/examples/2012/04/28/what-is-javascript-object-notation-json/' rel='bookmark' title='What is JavaScript Object Notation (JSON)?'>What is JavaScript Object Notation (JSON)?</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/QUshysf1kagt1CyLnvSS6JT6hZ8/0/da"><img src="http://feedads.g.doubleclick.net/~a/QUshysf1kagt1CyLnvSS6JT6hZ8/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/QUshysf1kagt1CyLnvSS6JT6hZ8/1/da"><img src="http://feedads.g.doubleclick.net/~a/QUshysf1kagt1CyLnvSS6JT6hZ8/1/di" border="0" ismap="true"></img></a></p><p style="text-align: justify">In our previous post we saw how we used Gson API to parse the Json using Java. Not spending too much time on the introduction, I would want to straight away dive into the same parsing which can be done using <a href="http://en.wikipedia.org/wiki/Groovy_%28programming_language%29" target="_blank">Groovy</a> language. <a href="http://en.wikipedia.org/wiki/Groovy_%28programming_language%29" target="_blank">Groovy</a> is a scripting language which runs on the JVM. It can inter-operate with the Java APIs and compiles down into byte code which can then be executed on the JVM.</p>
<p style="text-align: justify">In this example as well we would make use of the same json document described here.</p>
<p style="text-align: justify">Groovy support for Json was added in the 1.8 version when a new groovy.json package was added. So you dont have to use an external API for parsing the json documents. <a href="http://groovy.codehaus.org/api/groovy/json/JsonSlurper.html" target="_blank">JsonSlurper</a> parses the given json document into a data structure of lists and maps. Due to this conversion the name=value pairs in the json document can be accessed by object.name notation where object represents the json object and name represents the name of the attribute.</p>
<p>The model bean in this case is defined as:</p>
<pre class="brush: groovy; title: ; notranslate">
class GroovyUser{
  def id
  def screenName
  def name
  def url
  def followersCount
  def friendsCount
  def favouritesCount
  def statusesCount

  GroovyUser(id,
        screenName,
        name,
        url,
        followersCount,
        friendsCount,
        favouritesCount,
        statusesCount){
    this.id = id
    this.screenName = screenName
    this.name = name
    this.url = url
    this.followersCount = followersCount
    this.friendsCount = friendsCount
    this.favouritesCount = favouritesCount
    this.statusesCount = statusesCount

  }

  def String toString(){
    return &quot;Name: &quot;+this.name+&quot;\n&quot;+
    &quot;ScreenName:&quot;+this.screenName+&quot;\n&quot;+
    &quot;Followers: &quot;+this.followersCount+&quot;\n&quot;+
    &quot;Friends: &quot;+this.friendsCount+&quot;\n&quot;+
    &quot;Favourites: &quot;+this.favouritesCount+&quot;\n&quot;+
    &quot;Statuses: &quot;+this.statusesCount+&quot;\n&quot;
  }
}
</pre>
<p>As Groovy can be used a scripting language, the following code need not be compiled instead one could directly run the code by:</p>
<pre class="brush: bash; title: ; notranslate">$ groovy filename.groovy</pre>
<p>You would have to download and install the required binaries and libraries for running the groovy programs. More can be found at the <a href="http://groovy.codehaus.org/" target="_blank">official site</a>.</p>
<pre class="brush: groovy; title: ; notranslate">
import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper();

/*
Read the JSON from the file system
*/
def reader = new BufferedReader(
              new FileReader(&quot;/home/mohamed/twitterUser.json&quot;))
def parsedData = jsonSlurper.parse(reader)
def usersList = new ArrayList&lt;GroovyUser&gt;()
parsedData.each {
  aUser -&gt;
    def user = new GroovyUser(aUser.id,
    aUser.screen_name,
    aUser.name,
    aUser.url,
    aUser.followers_count,
    aUser.friends_count,
    aUser.favourites_count,
    aUser.statuses_count)
    usersList.add(user)
}

usersList.each {aUser -&gt; println aUser}
</pre>
<p>There are few new things to note here:</p>
<ul>
<li>As Groovy supports closures, we are making use of the methods like &#8220;each&#8221; which is provided by the Groovy API on collections. The each method would for each element in the collection, execute the block of code provided with the each method. Something like-myCollection.each{ aData -&gt; println aData }</li>
<li>Semi colons are optional</li>
<li>Type details for the variables are optional, so you can see that the variables have been declared by using &#8220;def&#8221; keyword but no type is declared.</li>
<li>Look at the tremendous decrease in the number of lines of code written above. Parsing Json in Groovy is such a pleasure.</li>
</ul>
<p style="text-align: justify">On a closing note, the difference in the lines of code in Java and Groovy might tempt few of them to learn the syntax of the language. I am sure learning groovy is pretty easy as it has a short learning curve. Over the last few years there has been a transition to polyglot programming and with the advent of new languages which run on the JVM, they can inter-operate with an existing java application with no additional overhead.</p>
<p>We would over the coming days try to provide a few getting started like tutorials for Groovy and other JVM languages like Scala.</p>
<div style='clear:both'></div><p>Related posts:</p><ol>
<li><a href='http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/' rel='bookmark' title='Parsing JSON using Java and GSON library'>Parsing JSON using Java and GSON library</a></li>
<li><a href='http://www.javabeat.net/examples/2012/04/28/what-is-javascript-object-notation-json/' rel='bookmark' title='What is JavaScript Object Notation (JSON)?'>What is JavaScript Object Notation (JSON)?</a></li>
</ol><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/9srpMWbgsuk" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/04/30/parsing-json-using-groovy/</feedburner:origLink></item>
		<item>
		<title>Parsing JSON using Java and GSON library</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/oiAw_ygaqJI/</link>
		<comments>http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/#comments</comments>
		<pubDate>Mon, 30 Apr 2012 09:28:50 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[JSON]]></category>
		<category><![CDATA[gson]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[JavaScript Object Notation (JSON)]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1078</guid>
		<description><![CDATA[In my previous post here, I gave a brief overview of JavaScript Object Notation (JSON). In this post I would go a bit further and show how one can parse the JSON documents into Java objects using the GSON library. The JSON data for this tutorial was obtained from: &#8220;https://api.twitter.com/1/users/show.json?screen_name=&#8221; where screen_name was TwitterAPI and [...]
No related posts.]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/K6N2mnKV4bcbc_QhGW5AaBvQ_jg/0/da"><img src="http://feedads.g.doubleclick.net/~a/K6N2mnKV4bcbc_QhGW5AaBvQ_jg/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/K6N2mnKV4bcbc_QhGW5AaBvQ_jg/1/da"><img src="http://feedads.g.doubleclick.net/~a/K6N2mnKV4bcbc_QhGW5AaBvQ_jg/1/di" border="0" ismap="true"></img></a></p><p>In my previous post <a href="http://www.javabeat.net/examples/2012/04/28/what-is-javascript-object-notation-json/">here</a>, I gave a brief overview of JavaScript Object Notation (JSON). In this post I would go a bit further and show how one can parse the JSON documents into Java objects using the <strong><a href="http://code.google.com/p/google-gson/" target="_blank">GSON</a></strong> library. The JSON data for this tutorial was obtained from: &#8220;<a href="https://api.twitter.com/1/users/show.json?screen_name=" target="_blank">https://api.twitter.com/1/users/show.json?screen_name=&#8221;</a> where screen_name was TwitterAPI and sanaulla. So I condensed the data into the following:</p>
<pre class="brush: jscript; title: ; notranslate">[
  {
    &quot;id&quot;:&quot;6253282&quot;,
    &quot;name&quot;:&quot;Twitter API&quot;,
    &quot;screen_name&quot;:&quot;twitterapi&quot;,
    &quot;url&quot;:&quot;http:\/\/dev.twitter.com&quot;,
    &quot;followers_count&quot;:1004641,
    &quot;friends_count&quot;:33,
    &quot;favourites_count&quot;:24,
    &quot;statuses_count&quot;:3277
  },
  {
    &quot;id&quot;:&quot;15082387&quot;,
    &quot;name&quot;:&quot;Sanaulla&quot;,
    &quot;screen_name&quot;:&quot;sanaulla&quot;,
    &quot;url&quot;:&quot;http:\/\/blog.sanaulla.info&quot;,
    &quot;followers_count&quot;:241,
    &quot;friends_count&quot;:302,
    &quot;favourites_count&quot;:41,
    &quot;statuses_count&quot;:1876
  }
]</pre>
<p>Let me call this file as <strong>twitterUser.json</strong>. It is an array of user profile data where each user profile contains: name, id, screen_name, url, followers_count, friends_count, favourites_count and statuses_count. In order to run the following code, you need to download the <strong>GSON API</strong> jar from <a href="http://code.google.com/p/google-gson/downloads/detail?name=google-gson-2.1-release.zip" target="_blank">here</a> and add it to your classpath. Moving further, we need to create a Model class which would hold the data obtained from JSON document.</p>
<pre class="brush: java; title: ; notranslate">
/**
* Model class for storing the selected few attributes
* for a Twitter User profile.
*/
class TwitterUser{
  private String id;
  private String name;
  private String screen_name;
  private String url;
  private int friends_count;
  private int followers_count;
  private int favourites_count;
  private int statuses_count;
  public TwitterUser(){
  }
  @Override
  public String toString(){
    return &quot;Name: &quot;+this.name+&quot;\n&quot; +
    &quot;Screen Name: &quot;+this.screen_name+&quot;\n&quot; +
    &quot;Number of Friends: &quot;+ this.friends_count + &quot;\n&quot; +
    &quot;Number of Followers: &quot;+ this.followers_count +&quot;\n&quot; +
    &quot;Number of Status updates: &quot;+this.statuses_count +&quot;\n&quot; +
    &quot;Number of favorites: &quot;+this.favourites_count +&quot;\n&quot;;
  }
}</pre>
<p>Before putting forth the code, let me brief about the classes where are used for parsing the Json:</p>
<ul>
<li><strong><a href="http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html" target="_blank">com.google.gson.Gson</a></strong>:<br />
<em>This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it.</em></li>
<li><strong><a href="google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonParser.html" target="_blank">com.google.gson.JsonParser</a></strong>:<br />
A parser to parse Json into a parse tree of JsonElements</li>
<li><strong><a href="http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html" target="_blank">com.google.gson.stream.JsonReader</a></strong>:<br />
Reads a JSON encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays.</li>
<li><strong><a href="http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonArray.html" target="_blank">com.google.gson.JsonArray</a></strong>:<br />
A class representing an array type in Json. An array is a list of JsonElements each of which can be of a different type.</li>
<li><strong><a href="http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonElement.html" target="_blank">com.google.gson.JsonElement: </a></strong><br />
A class representing an element of Json. It could either be a JsonObject, a JsonArray, a JsonPrimitive or a JsonNull.</li>
</ul>
<p>Reading the JSON document using JsonReader, assuming the document is present in the file systems:</p>
<pre class="brush: java; title: ; notranslate">JsonReader reader = new JsonReader(
        new InputStreamReader(new FileInputStream(this.jsonSource)));</pre>
<p style="text-align: justify">JsonReader has a constructor which takes in an instance of a Reader, in our case we use the InputStreamReader and pipe it to a FileInputStream.</p>
<p style="text-align: justify">Once we are able to read the json data, we go ahead and use JsonParser to parse the contents and obtain the array of objects which the json document stores. There is an another way to do this with out using the JsonParser explicitly, but lets stick to this as its more clearer.</p>
<pre class="brush: java; title: ; notranslate">
JsonParser jsonParser = new JsonParser();
JsonArray userarray= jsonParser.parse(jsonReader).getAsJsonArray();
</pre>
<p style="text-align: justify">parse(JsonReader) method of the JsonParser, parses the given Json and creates a parse tree of JsonElements. And the method getAsJsonArray() returns the parsed Json as an array of json objects. In our document we are sure that the document is an array of json objects (recall, the [ ] stands for representing the arrays in json). Suppose you were not sure if those are arrays, then you can use isJsonArray() method of the JsonElement class.</p>
<p>Next up, is to traverse through the array and populate the data from the json object in to our model bean TwitterUser which we had defined at the beginning.</p>
<pre class="brush: java; title: ; notranslate">List twitterUsers = new ArrayList&lt;&gt;();
for ( JsonElement aUser : userArray ) {
TwitterUser aTwitterUser = myGson.fromJson(aUser, TwitterUser.class);
twitterUsers.add(aTwitterUser);
}</pre>
<p style="text-align: justify">For each element in the <strong>JsonArray</strong> we use <strong>Gson.fromJson()</strong> to populate the data in the json object into the type defined by TwitterUser.class. How it works behind the scene is:</p>
<ul style="text-align: justify">
<li>It creates a new instance of TwitterUser, by invoking the default constructor.</li>
<li>Sets the values of the attributes in the TwitterUser class with those obtained from the json array element. If you closely look at the names of the attributes in the TwitterUser class and the ones in the Json document- they are exactly similar- something like- screen_name, friends_count, followerr_count and so on.</li>
</ul>
<p style="text-align: justify">The fromJson method in Gson has been overloaded to support multiple types of parameters, and from that we are using the fromJson(JsonElement json, Class&lt;T&gt; classOfT) version.</p>
<p>Now just to confirm we have parsed the correct data, iterate through the user list:</p>
<pre class="brush: java; title: ; notranslate">for ( TwitterUser tUser : twitterUsers)
{
  System.out.println(tUser);
}</pre>
<p>The complete source for the code is given below:</p>
<pre class="brush: java; title: ; notranslate">import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class JsonParserDemo {

  private String jsonSource;
  private boolean sourceFromFile;
  public JsonParserDemo(String jsonSource, boolean sourceFromFile){
    this.jsonSource = jsonSource;
    this.sourceFromFile = sourceFromFile;
  }
  public static void main(String[] args){
    JsonParserDemo jsonParserDemo =
     new JsonParserDemo(&quot;/home/mohamed/twitterUser.json&quot;, true);
    try(JsonReader jsonReader = jsonParserDemo.getJsonReader()){
      Gson myGson = new Gson();
      JsonParser jsonParser = new JsonParser();
      JsonArray userArray =  jsonParser.parse(jsonReader).getAsJsonArray();
      List twitterUsers = new ArrayList&lt;&gt;();
      for ( JsonElement aUser : userArray ){
        TwitterUser aTwitterUser = myGson.fromJson(aUser, TwitterUser.class);
        twitterUsers.add(aTwitterUser);
      }
      for ( TwitterUser tUser : twitterUsers){
        System.out.println(tUser);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
  * Obtain the JsonReader for the given source details.
  * @return the JsonReader instance
  * @throws FileNotFoundException
  */
  private JsonReader getJsonReader () throws FileNotFoundException{
    JsonReader reader = null;
    if (sourceFromFile){
      reader = new JsonReader(
        new InputStreamReader(new FileInputStream(this.jsonSource)));
    }
    return reader;
  }
}

/**
* Model class for storing the selected few attributes
* for a Twitter User profile.
*/
class TwitterUser{
  private String id;
  private String name;
  private String screen_name;
  private String url;
  private int friends_count;
  private int followers_count;
  private int favourites_count;
  private int statuses_count;

  public TwitterUser(){
  }

  @Override
  public String toString(){
    return &quot;Name: &quot;+this.name+&quot;\n&quot; +
      &quot;Screen Name: &quot;+this.screen_name+&quot;\n&quot; +
      &quot;Number of Friends: &quot;+ this.friends_count + &quot;\n&quot; +
      &quot;Number of Followers: &quot;+ this.followers_count +&quot;\n&quot; +
      &quot;Number of Status updates: &quot;+this.statuses_count +&quot;\n&quot; +
      &quot;Number of favorites: &quot;+this.favourites_count +&quot;\n&quot;;
  }
}</pre>
<div style='clear:both'></div><p>No related posts.</p><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/oiAw_ygaqJI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/04/30/parsing-json-using-java-and-gson-library/</feedburner:origLink></item>
		<item>
		<title>What is JavaScript Object Notation (JSON)?</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/rnVQTC5PRWo/</link>
		<comments>http://www.javabeat.net/examples/2012/04/28/what-is-javascript-object-notation-json/#comments</comments>
		<pubDate>Sat, 28 Apr 2012 02:30:54 +0000</pubDate>
		<dc:creator>Mohammed Sanaulla</dc:creator>
				<category><![CDATA[JSON]]></category>
		<category><![CDATA[JavaScript Object Notation (JSON)]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1058</guid>
		<description><![CDATA[A quick JSON search on Google would yield plenty of results and more specifically the JSON homepage. None the less we wanted to share something brief and something good about JSON. Lot of you are familiar with XML and XML had been the defacto data-transfer language in the area of RESTful webservices, but off late [...]
Related posts:<ol>
<li><a href='http://www.javabeat.net/examples/2009/09/17/java-vs-javascript/' rel='bookmark' title='Java Vs. JavaScript'>Java Vs. JavaScript</a></li>
<li><a href='http://www.javabeat.net/examples/2010/09/27/struts-html-javascript-tag-htmljavascript/' rel='bookmark' title='Struts HTML JavaScript Tag ( &lt; html:javascript &gt;)'>Struts HTML JavaScript Tag ( &lt; html:javascript &gt;)</a></li>
<li><a href='http://www.javabeat.net/examples/2011/02/24/top-10-javascript-tips-for-your-site/' rel='bookmark' title='Top 10 JavaScript Tips for your site'>Top 10 JavaScript Tips for your site</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/ofv1Ak8UPg-hq6XNs7POghC55_I/0/da"><img src="http://feedads.g.doubleclick.net/~a/ofv1Ak8UPg-hq6XNs7POghC55_I/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/ofv1Ak8UPg-hq6XNs7POghC55_I/1/da"><img src="http://feedads.g.doubleclick.net/~a/ofv1Ak8UPg-hq6XNs7POghC55_I/1/di" border="0" ismap="true"></img></a></p><p style="text-align: justify">A quick <strong>JSON</strong> <a href="https://www.google.co.in/search?q=json" target="_blank">search</a> on Google would yield plenty of results and more specifically the <strong>JSON</strong> <a href="http://www.json.org/" target="_blank">homepage</a>. None the less we wanted to share something brief and something good about <strong>JSON</strong>. Lot of you are familiar with XML and XML had been the defacto data-transfer language in the area of <strong>RESTful webservices</strong>, but off late <strong>JSON</strong> has been gaining popularity for reasons which I would explain a bit further. Before going further into XML versus JSON, let me give a brief overview of the structure of JSON documents. And for those not aware of what <strong>JSON</strong> stands for, its JavaScript Object Notation. I know the use of &#8220;JavaScript&#8221; term has more relevance and is not like the use of &#8220;Java&#8221; in the term &#8220;JavaScript&#8221;.</p>
<p style="text-align: justify"><span id="more-1058"></span>A <strong>JSON</strong> structure consists of name-value pairs where a collection of such name-value pairs is called an Object, and each value could be an object themselves or be some primitives like Strings, Numbers and so on. Also values can be arrays of objects or primitive values. Sounds confusing right, let me explain with an example, consider a <strong>JSON</strong> document retrieved from <a href="http://api.twitter.com/1/trends/available.json" target="_blank">http://api.twitter.com/1/trends/available.json</a> which shows the available twitter trends and their location information. Let me get a small excerpt from that document:</p>
<pre class="brush: jscript; title: ; notranslate">[
 {
   &quot;parentid&quot;: 23424900,
   &quot;name&quot;: &quot;Mexico City&quot;,
   &quot;url&quot;: &quot;http://where.yahooapis.com/v1/place/116545&quot;,
   &quot;country&quot;: &quot;Mexico&quot;,
   &quot;countryCode&quot;: &quot;MX&quot;,
   &quot;placeType&quot;: {
     &quot;name&quot;: &quot;Town&quot;,
     &quot;code&quot;: 7
   },
   &quot;woeid&quot;: 116545
 },
 {
   &quot;name&quot;: &quot;Jackson&quot;,
   &quot;url&quot;: &quot;http://where.yahooapis.com/v1/place/2428184&quot;,
   &quot;country&quot;: &quot;United States&quot;,
   &quot;countryCode&quot;: &quot;US&quot;,
   &quot;placeType&quot;: {
     &quot;name&quot;: &quot;Town&quot;,
     &quot;code&quot;: 7
   },
   &quot;parentid&quot;: 23424977,
   &quot;woeid&quot;: 2428184
 }
]</pre>
<p style="text-align: justify">In the above example, the notation <strong>[ ]</strong> is used to represent the Arrays and anything within <strong>{ }</strong> is considered to be an object literal/ or an object. We can observe that we have an array of two objects where each object represents some twitter trend details. Digging further we can observe that objects have a &#8220;name&#8221;:value pattern, this is somewhat closer to our Map representations. The &#8220;placeType&#8221; attribute has another object as its value, similarly attributes like &#8220;code&#8221;, &#8220;woeid&#8221; have Numbers as their values.</p>
<p style="text-align: justify">Just in case you want to learn more about this structure/syntax, you can visit JSON.org for a beautiful diagrammatic explanation.</p>
<p style="text-align: justify"><strong>Origin and Use of JSON: </strong></p>
<p style="text-align: justify"><a href="http://en.wikipedia.org/wiki/Douglas_Crockford" target="_blank">Douglas Crockford</a> of <a href="http://www.flipkart.com/javascript-8184045220/p/itmczzj4cafppxym?pid=9788184045222&amp;_l=d7izwEFQZLoDqctmJtMgDw--&amp;_r=qNcsGfroVfguAZKYslLaDQ--&amp;ref=6751de83-5318-4fa5-920a-a5ffdca8ead1" target="_blank">JavaScript Good Parts</a> fame was the earliest promoters of <strong>JSON</strong> notation and it was named so because  it mimics the object notation used in JavaScript. It doesn&#8217;t require JavaScript to use but its fairly easy to create JavaScript objects using the <strong>JSON</strong> data. There are lot of APIs in almost all languages which provide support for parsing and creating <strong>JSON</strong> documents and languages like Groovy provide such support within their standard APIs. NoSQL databases like CouchDB, MongoDB extensively use JSON for representing the data.</p>
<p style="text-align: justify">Lot of RESTful Webservice APIs out there support both XML and JSON data formats. And with JavaScript frameworks like Backbone.js it becomes really easy to consume the JSON documents provided by these RESTful APIs and create model objects. An advantage of JSON over XML is that, its really less verbose than XML. And also the JSON representation is more closer to the Object/Key-value kind of notation which lot of us Java programmers are familiar with.</p>
<p style="text-align: justify">In the coming posts, we would be writing on how one can parse JSON in Java and other JVM languages and also how to use it in parsing the data from a RESTful API. So before that, we thought of giving a brief overview of JSON.</p>
<p style="text-align: justify">Any of you have more to share about JSON, any good/bad experiences of using JSON, do leave them here as comments, we would be more than happy to update the post to add your comments.</p>
<p style="text-align: justify">
<div style='clear:both'></div><p>Related posts:</p><ol>
<li><a href='http://www.javabeat.net/examples/2009/09/17/java-vs-javascript/' rel='bookmark' title='Java Vs. JavaScript'>Java Vs. JavaScript</a></li>
<li><a href='http://www.javabeat.net/examples/2010/09/27/struts-html-javascript-tag-htmljavascript/' rel='bookmark' title='Struts HTML JavaScript Tag ( &lt; html:javascript &gt;)'>Struts HTML JavaScript Tag ( &lt; html:javascript &gt;)</a></li>
<li><a href='http://www.javabeat.net/examples/2011/02/24/top-10-javascript-tips-for-your-site/' rel='bookmark' title='Top 10 JavaScript Tips for your site'>Top 10 JavaScript Tips for your site</a></li>
</ol><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/rnVQTC5PRWo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/04/28/what-is-javascript-object-notation-json/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/04/28/what-is-javascript-object-notation-json/</feedburner:origLink></item>
		<item>
		<title>Download file from HTTP &amp; HTTPS server using Java</title>
		<link>http://feedproxy.google.com/~r/JavabeatTips/~3/kqmErQGqi2Q/</link>
		<comments>http://www.javabeat.net/examples/2012/04/13/download-file-from-http-https-server-using-java/#comments</comments>
		<pubDate>Fri, 13 Apr 2012 06:08:37 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/examples/?p=1050</guid>
		<description><![CDATA[In the earlier articles, JavaBeat has published many articles on uploading and downloding of files using the Java programming. Upload and Download is essential utility in the programming world because every server must have the feature to upload and download the files by the user or downlod the reports incase of the enterprise applications. The [...]
Related posts:<ol>
<li><a href='http://www.javabeat.net/examples/2007/10/10/file-upload-and-download-using-java/' rel='bookmark' title='File Upload and Download using Java'>File Upload and Download using Java</a></li>
<li><a href='http://www.javabeat.net/examples/2008/09/25/how-to-enable-ssl-on-jboss-application-server/' rel='bookmark' title='How to enable SSL on JBoss application server?'>How to enable SSL on JBoss application server?</a></li>
<li><a href='http://www.javabeat.net/examples/2008/08/01/sar-service-archive-file-in-jboss/' rel='bookmark' title='SAR (Service Archive) file in JBoss'>SAR (Service Archive) file in JBoss</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[
<p><a href="http://feedads.g.doubleclick.net/~a/9mAmd30VaaOUFQYyXRT0mHSgrvA/0/da"><img src="http://feedads.g.doubleclick.net/~a/9mAmd30VaaOUFQYyXRT0mHSgrvA/0/di" border="0" ismap="true"></img></a><br/>
<a href="http://feedads.g.doubleclick.net/~a/9mAmd30VaaOUFQYyXRT0mHSgrvA/1/da"><img src="http://feedads.g.doubleclick.net/~a/9mAmd30VaaOUFQYyXRT0mHSgrvA/1/di" border="0" ismap="true"></img></a></p><p>In the earlier articles, JavaBeat has published many articles on <a href="http://www.javabeat.net/examples/2007/10/10/file-upload-and-download-using-java/">uploading and downloding of files </a>using the Java programming. <strong>Upload and Download</strong> is essential utility in the programming world because every server must have the feature to upload and download the files by the user or <strong>downlod</strong> the reports incase of the enterprise applications. The challenging part is that, the process could be different based on the type of server and the security infrastructure in that serever for example <strong>SSL certificate</strong>. This example provides the simple way to download a file from the <strong>HTTP</strong> web server and store it in your local system. Also there is a way to download a file from the <strong>HTTPS</strong> server.</p>
<p>Try this program and let us know if it is working for you. If you have any doubts, please psot it in the comments section. We would try to resolve your problems.</p>

<div class="wp_syntax"><div class="code"><pre class="language" style="font-family:monospace;">package com.service;
&nbsp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.MalformedInputException;
&nbsp;
public class TestClass {
	public static void main(String[] args) {
		URL url = null;
		URLConnection con = null;
		int i;
		try {
			url = new URL(&quot;https://localhost:8080/AppName/FileName.txt&quot;);
			con = url.openConnection();
			File file = new File(
					&quot;C:\\Foldername\\Address.txt&quot;);
			BufferedInputStream bis = new BufferedInputStream(
					con.getInputStream());
			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file.getName()));
			while ((i = bis.read()) != -1) {
				bos.write(i);
			}
			bos.flush();
			bis.close();
		} catch (MalformedInputException malformedInputException) {
			malformedInputException.printStackTrace();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}
}</pre></div></div>

<p>The above code will work for the normal <strong>HTTP server</strong>. Incase if you are trying to download from the HTTPS server, you will get the follwoing exception (<strong>javax.net.ssl.SSLHandshakeException)</strong>:</p>

<div class="wp_syntax"><div class="code"><pre class="language" style="font-family:monospace;">javax.net.ssl.&lt;strong&gt;SSLHandshakeException&lt;/strong&gt;: Remote host closed connection during handshake
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
	at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
	at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
	at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
	at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
	at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
	at com.infosys.finanztools.fms.test.data.service.TestClass.main(TestClass.java:23)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
	at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source)
	... 9 more</pre></div></div>

<p>You have to use the following snippet of code to make it work:</p>

<div class="wp_syntax"><div class="code"><pre class="language" style="font-family:monospace;">System.setProperty(&quot;java.protocol.handler.pkgs&quot;,
        &quot;com.sun.net.ssl.internal.www.protocol&quot;);
   Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());</pre></div></div>

<div style='clear:both'></div><p>Related posts:</p><ol>
<li><a href='http://www.javabeat.net/examples/2007/10/10/file-upload-and-download-using-java/' rel='bookmark' title='File Upload and Download using Java'>File Upload and Download using Java</a></li>
<li><a href='http://www.javabeat.net/examples/2008/09/25/how-to-enable-ssl-on-jboss-application-server/' rel='bookmark' title='How to enable SSL on JBoss application server?'>How to enable SSL on JBoss application server?</a></li>
<li><a href='http://www.javabeat.net/examples/2008/08/01/sar-service-archive-file-in-jboss/' rel='bookmark' title='SAR (Service Archive) file in JBoss'>SAR (Service Archive) file in JBoss</a></li>
</ol><img src="http://feeds.feedburner.com/~r/JavabeatTips/~4/kqmErQGqi2Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/examples/2012/04/13/download-file-from-http-https-server-using-java/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://www.javabeat.net/examples/2012/04/13/download-file-from-http-https-server-using-java/</feedburner:origLink></item>
	</channel>
</rss>

