RSS

Monthly Archives: November 2012

REST clients for Java, MySQL and JSON Restful Web Services

This is the second part of the tutorial which demonstrates Restful web service using Java, MySQL and JSON. In this tutorial we are going to create several REST clients for our web service. You can download each REST client project. Each REST client is going to parse the JSON response and display output.

Java REST client
Download
We use Java SE application as our client. To parse JSON, gson library is added to project /lib folder Also it is included in project build path as an external JAR.

Course.java – data bound model class

public class Course
{
private int id;
private String name;
private String duration;
private double fee;

public Course()
{

}

public Course(int id, String name, String duration, double fee)
{
super();
this.id = id;
this.name = name;
this.duration = duration;
this.fee = fee;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getDuration()
{
return duration;
}

public void setDuration(String duration)
{
this.duration = duration;
}

public double getFee()
{
return fee;
}

public void setFee(double fee)
{
this.fee = fee;
}

@Override
public String toString()
{
return "Course [id=" + id + ", name=" + name + ", duration=" + duration
+ ", fee=" + fee + "]";
}

}

Main.java

package com;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class Main
{

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
String json = readUrl("http://localhost:8080/RestProject/Rest/courseService/courses");
Gson gson = new Gson();
JsonParser jsonParser = new JsonParser();
JsonArray courseArray = jsonParser.parse(json).getAsJsonArray();
List<Course> coursesList = new ArrayList<Course>();
for (JsonElement course : courseArray)
{
Course courseObj = gson.fromJson(course, Course.class);
coursesList.add(courseObj);
}

for (Course courseObj : coursesList)
{
System.out.println("ID : " + courseObj.getId());
System.out.println("Course Name : " + courseObj.getName());
System.out.println("Duration : " + courseObj.getDuration());
System.out.println("Course fee : " + courseObj.getFee());
}

}

private static String readUrl(String urlString) throws Exception
{
BufferedReader reader = null;
try
{
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);

return buffer.toString();
} finally
{
if (reader != null)
reader.close();
}

}
}

PHP REST client
CURL or file_get_contents() can be used to get JSON  from the web service URL.

$json = file_get_contents("http://localhost:8080/RestProject/Rest/courseService/courses");
$json_o = json_decode($json);

$msg .= "";
foreach($json_o as $item)
{
$msg .= "Course ID : ". $item->id. "<br>";
$msg .= "Course Name : ". $item->name. "<br>";
$msg .= "Duration  : ". $item->duration. "<br>";
$msg .= "Course fee : ". $item->fee. "<br><br>";
}
echo $msg;

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, "http://localhost:8080/RestProject/Rest/courseService/courses");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
$json = curl_exec($ch);
$json_o = json_decode($json);

$msg .= "";
foreach($json_o as $item)
{
$msg .= "Course ID : ". $item->id. "<br>";
$msg .= "Course Name : ". $item->name. "<br>";
$msg .= "Duration  : ". $item->duration. "<br>";
$msg .= "Course fee : ". $item->fee. "<br><br>";
}
echo $msg;

Android REST client

Download


 
3 Comments

Posted by on November 28, 2012 in C#.Net, Java, PHP

 

Tags: ,

Search People Using Pipl API

If you are a Facebook user or Twitter user like me, you already know how to find a particular person. Facebook Friends Finder is a great tool. It is so intelligent that it can find mutual relationships and many more. Several weeks ago, I wanted some methodology to develop a web solution to allow someone to find his interested people. It should not be limited to Facebook. The user may wish to see search results from different social networks. Obviously, it ‘s very difficult to integrate several social networks and develop a combined solution. The easiest way is to find a good API that provides reliable information. There comes Pipl. It ‘s highly sophisticated.

So you know what I gonna explore today. The Pipl Search API. This is a Restful API that can generate response in xml as well as json format for a given user information. There are huge amount of query parameters. You can use any of them as you wish. In this tutorial, I show you how to find a person when we know his first name and last name. Very simple. Just a matter of decoding json/xml response.

HTML Form

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
</head>

<body>
<form method="get">
First <input name="first" type="text" value="asantha">
Last <input name="last" type="text" value="prasad">
<input name="btn" type="submit">
</form>
</body>
</html>

PHP Script


 if(isset($_GET['first']) && isset($_GET['last']))
 {
 $first = $_GET['first'];
$last = $_GET['last'];</pre>
$json = file_get_contents("http://apis.pipl.com/search/v2/json/?first_name=$first&last_name=$last&key=h6cbvuu8mkj97vbrztanvptp");

$json_o = json_decode($json);

$count = 0;
 foreach($json_o->results->records as $rec)
 {
 echo ++$count." ".$rec->names[0]->display ."<br>";
 echo "Domain : " .$rec->source->domain."<br>";

$url =  $rec->source->url;
 echo "<a href='$url'>URL</a><br>";

$img =  $rec->images[0]->url;
 echo "<img src='$img' width='125px' height='125px'>";
 echo "<hr><br>";
 }

echo "<hr><h3>suggestions</h3>";
 $suggest =  $json_o->suggested_searches[0]->source->url."h6cbvuu8mkj97vbrztanvptp";
 echo "<a href='$suggest'>visit</a>";
 }

 
Leave a comment

Posted by on November 10, 2012 in PHP

 

Tags: ,

Restful Web Services Java, MySQL and JSON

Today we are going to build another restful web service in eclipse using gson library. When client makes a request, the application queries the database and produces response in JSON format. This JSON can be parsed with most of the programming languages.
We will see how various clients can consume this web service in the second part of the tutorial.

Download Sourcecode
Project Architecture

Create a new dynamic web project in Eclipse and add jersy, gson library to WEB-INF/lib.

course.java
We utilize this class when we wanna bind data after querying database.

package dto;

public class Course
{
private int id;
private String name;
private String duration;
private double fee;

public Course()
{

}

public Course(int id, String name, String duration, double fee)
{
super();
this.id = id;
this.name = name;
this.duration = duration;
this.fee = fee;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public String getDuration()
{
return duration;
}

public void setDuration(String duration)
{
this.duration = duration;
}

public double getFee()
{
return fee;
}

public void setFee(double fee)
{
this.fee = fee;
}

@Override
public String toString()
{
return "Course [id=" + id + ", name=" + name + ", duration=" + duration
+ ", fee=" + fee + "]";
}

}

 

Database.java

package dao;

import java.sql.Connection;
import java.sql.DriverManager;

public class Database
{
public Connection getConnection() throws Exception
{
try
{
String connectionURL = "jdbc:mysql://localhost:3306/codezone4";
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "");
return connection;
} catch (Exception e)
{
throw e;
}

}

}

Access.java

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import dto.Course;

public class Access
{
public ArrayList<Course> getCourses(Connection con) throws SQLException
{
ArrayList<Course> courseList = new ArrayList<Course>();
PreparedStatement stmt = con.prepareStatement("SELECT * FROM courses");
ResultSet rs = stmt.executeQuery();
try
{
while(rs.next())
{
Course courseObj = new Course();
courseObj.setId(rs.getInt("id"));
courseObj.setName(rs.getString("name"));
courseObj.setDuration(rs.getString("duration"));
courseObj.setFee(rs.getDouble("fee"));
courseList.add(courseObj);
}
} catch (SQLException e)
{
e.printStackTrace();
}
return courseList;

}
}

AccessManager.java

package model;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

import dao.Access;
import dao.Database;
import dto.Course;

public class AccessManager
{
public ArrayList<Course> getCourses() throws Exception
{
ArrayList<Course> courseList = new ArrayList<Course>();
Database db = new Database();
Connection con = db.getConnection();
Access access = new Access();
courseList = access.getCourses(con);
return courseList;
}
}

CourseService.java

package webService;

import java.util.ArrayList;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import com.google.gson.Gson;

import model.AccessManager;

import dto.Course;

@Path("/courseService")
public class CourseService
{
@GET
@Path("/courses")
@Produces("application/json")
public String courses()
{
String courses = null;
ArrayList<Course> courseList = new ArrayList<Course>();
try
{
courseList = new AccessManager().getCourses();
Gson gson = new Gson();
courses = gson.toJson(courseList);
} catch (Exception e)
{
e.printStackTrace();
}
return courses;
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RestProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Course Service</servlet-name>
<servlet-class>com.sun.jersey.server.impl.container.servlet.ServletAdaptor</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Course Service</servlet-name>
<url-pattern>/Rest/*</url-pattern>
</servlet-mapping>
</web-app>

Run the application in server.
visit following URL :
http://localhost:8440/RestProject/Rest/courseService/courses
The port number in the URL depends on your server settings.
You will see the JSON response.

 

Help make a developer’s life happy and strong.

Donate Button with Credit Cards

 
46 Comments

Posted by on November 8, 2012 in J2EE, Java

 

Tags: ,

Java Restful Web Services(JAX-RS) Using Jersy

This tutorial demonstrates how to build a Java Restful web service in Eclipse using Jersy plugin.

Download project

REST(Representational State Transfer) is an architectural style. This is not a standard whereas SOAP is standardized. RESTful web services are based on HTTP protocol and its methods PUT, GET, POST, and DELETE. They do not require XML SOAP messages or WSDL service definitions.

REST can be considered similar to a client-server architecture. There ‘s a REST server waiting for the requests from REST clients.

Requirements :

Main Topics
  1. Install Jersy plugin
  2. Create resource
  3. Create client
  4. Configure web.xml

1. Install Jersy plugin

Create new dynamic web project. Add  following jars from the downloaded Jersey zip file to WEB-INF/lib. Add them to project Build Path.

1. Create resource

package com.res;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

//Sets the path to base URL + /hello
@Path("/hello")
public class Hello {

// This method is called if TEXT_PLAIN is request
@GET
@Produces(MediaType.TEXT_PLAIN)
public String sayPlainTextHello() {
return "Hello Jersey";
}

// This method is called if XMLis request
@GET
@Produces(MediaType.TEXT_XML)
public String sayXMLHello() {
return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";
}

// This method is called if HTML is request
@GET
@Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello Jersey" + "</title>"
+ "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";
}

}

3. Create client

package com.client;

import java.net.URI;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

public class client {

/**
* @param args
*/
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
// Fluent interfaces
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
// Get plain text
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
// Get XML
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_XML).get(String.class));
// The HTML
System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_HTML).get(String.class));
}

private static URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8440/Success").build();
}

}

4. Configure web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Success</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.res</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>

web.xml is tricky!
[Extracted from : http://www.javahotchocolate.com/tutorials/restful.html%5D
The display name. It can be anything, but it’s

what goes first thing in the URL (browser address

line) after the protocol (http) and domain-

name:port-number. Note that I’m not using

anything that looks like a package name here. I

don’t even have to use the Eclipse project name.

Obviously, it cannot contain a space.

The servlet name. It can have spaces in it, but it’s

used in another place and the two must be identical.

The servlet name doesn’t show up outside this file,

but this file uses it to find the appropriate mapping

definition.

The servlet container class. This pertains to the

framework you’re using. Here, we’re using Jersey, so

we’re sure to name that class which comes out of

the user library (set of Jersey JARs) we used.

The servlet container class parameter name, as

dictated (in this instance) by the REST servlet

container or framework in use.

The value of the preceding parameter. It must be

the package name that contains at least and at most

one (JAXB) servlet (.java file). There may be more

than one such servlet, but if so, the other(s) must be

in a different Java package.

The servlet name must be identical to the one

already specified above. As noted, if there are two

servlets, there are two servlet definitions and two,

separate servlet mapping definitions.

The URL pattern. It starts with ‘/’ and ends with

‘/*’ and can be any legitimate directory-like

identifier (without spaces). It is the penultimate

element of the URL, just before the class name path.

web.xml:



    Fun

	
    
        Jersey REST Service
        com.sun.jersey.spi.container.servlet.ServletCo

ntainer
        
            com.sun.jersey.config.property.packages

de.vogella.jersey.first 1 Fun with REST com.sun.jersey.spi.container.servlet.ServletCo ntainer com.sun.jersey.config.property.packages

com.etretatlogiciels.fun 1 Jersey REST Service /rest/* Fun with REST /fun/*
 
3 Comments

Posted by on November 5, 2012 in J2EE, Java

 

Tags: ,

StaX API – The XML Parser for Java (Part 2)

There are differnet methods to parse XML in Java. Dom(Document Object Model) and SAX(Simple API for XML) are well known APIs. However this tutorial uses StaX API(Streaming API for XML) which is more sophisticated than others.

The core StaX API comes in two flavors to parse XML. They are

  •     Cursor API
  •     Event Iterator API

Event Iterator API is more flexible than Cursor API. So let’s focus on Event Iterator API. Part 2 of this tutorial demonstrates how to write XML in Java. In Part 1, we read xml using StaX API.

books2.xml

<?xml version="1.0"?><books>
<type>1</type>
<title>901</title>
<author>0</author>
</books>

Book.java (Model class)

package model;

public class Book {

private String isbn;
private String type;
private String title;
private String author;

public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}

@Override
public String toString() {
return "Book [isbn=" + isbn + ", type=" + type + ", title=" + title
+ ", author=" + author + "]";
}

}

BookParser.java


import java.io.FileOutputStream;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartDocument;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class BookParser
{

private String bookFile;

public void setFile(String bookFile)
{
this.bookFile = bookFile;
}


private void createNode(XMLEventWriter eventWriter, String name,
String value)
{

try
{
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
XMLEvent tab = eventFactory.createDTD("\t");
// Create Start node
StartElement sElement = eventFactory.createStartElement("", "",
name);
eventWriter.add(tab);
eventWriter.add(sElement);
// Create Content
Characters characters = eventFactory.createCharacters(value);
eventWriter.add(characters);
// Create End node
EndElement eElement = eventFactory.createEndElement("", "", name);
eventWriter.add(eElement);
eventWriter.add(end);
} catch (FactoryConfigurationError e)
{

e.printStackTrace();
} catch (XMLStreamException e)
{

e.printStackTrace();
}

}

public void saveBooks() throws Exception
{
// Create a XMLOutputFactory
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
// Create XMLEventWriter
XMLEventWriter eventWriter = outputFactory
.createXMLEventWriter(new FileOutputStream(bookFile));
// Create a EventFactory
XMLEventFactory eventFactory = XMLEventFactory.newInstance();
XMLEvent end = eventFactory.createDTD("\n");
// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument();
eventWriter.add(startDocument);

// Create books open tag
StartElement booksStartElement = eventFactory.createStartElement("","", "books");
eventWriter.add(booksStartElement);
eventWriter.add(end);
// Write the different nodes
createNode(eventWriter, "type", "1");
createNode(eventWriter, "title", "901");
createNode(eventWriter, "author", "0");

eventWriter.add(eventFactory.createEndElement("", "", "books"));
eventWriter.add(end);
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();
}
}


So now we are going to write XML to books2.xml

public class TestWrite
{

/**
* @param args
*/
public static void main(String[] args)
{
BookParser parser = new BookParser();
parser.setFile("books2.xml");
try
{
parser.saveBooks();
} catch (Exception e)
{
e.printStackTrace();
}

}

}


 
Leave a comment

Posted by on November 5, 2012 in Java, XML

 

Tags: ,

StaX API – The XML Parser for Java (Part 1)

There are differnet methods to parse XML in Java. Dom(Document Object Model) and SAX(Simple API for XML) are well known APIs. However this tutorial uses StaX API(Streaming API for XML) which is more sophisticated than others.

The core StaX API comes in two flavors to parse XML. They are

  •     Cursor API
  •     Event Iterator API

Event Iterator API is more flexible than Cursor API. So let’s focus on Event Iterator API. Part 1 of this tutorial demonstrates how to read XML in Java. Part2 of this tutorial is about writing XML.

books.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book isbn="000-1">
<type>novel</type>
<title>Kidnaped</title>
<author>R.L.Stevenson</author>
</book>
<book isbn="000-2">
<type>religious</type>
<title>Peace of mind</title>
<author>N.K.Dumney</author>
</book>
<book isbn="000-3">
<type>educational</type>
<title>Head First Java</title>
<author>Kathy Sierra</author>
</book>
</books>

Book.java (Model class)

package model;

public class Book {

private String isbn;
private String type;
private String title;
private String author;

public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}

@Override
public String toString() {
return "Book [isbn=" + isbn + ", type=" + type + ", title=" + title
+ ", author=" + author + "]";
}

}

BookParser.java


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import model.Book;

public class BookParser
{
static final String BOOK = "book";
static final String ISBN = "isbn";
static final String TYPE = "type";
static final String TITLE = "title";
static final String AUTHOR = "author";

@SuppressWarnings("unchecked")
public List<Book> readBooks(String file)
{
List<Book> books = new ArrayList<Book>();
try
{
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
InputStream in = new FileInputStream(file);
XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
Book book = null;

while (eventReader.hasNext())
{
XMLEvent event = eventReader.nextEvent();

if (event.isStartElement())
{
StartElement startElement = event.asStartElement();
if (startElement.getName().getLocalPart() == (BOOK))
{
book = new Book();
// Read attributes of Book element
Iterator<Attribute> attributes = startElement
.getAttributes();
while (attributes.hasNext())
{
Attribute attribute = attributes.next();
if (attribute.getName().toString().equals(ISBN))
{
book.setIsbn(attribute.getValue());
}
}
}

if (event.isStartElement())
{
if (event.asStartElement().getName().getLocalPart()
.equals(TYPE))
{
event = eventReader.nextEvent();
book.setType(event.asCharacters().getData());
continue;
}
}

if (event.asStartElement().getName().getLocalPart()
.equals(TITLE))
{
event = eventReader.nextEvent();
book.setTitle(event.asCharacters().getData());
continue;
}
if (event.asStartElement().getName().getLocalPart()
.equals(AUTHOR))
{
event = eventReader.nextEvent();
book.setAuthor(event.asCharacters().getData());
continue;
}
}
// Reach the end of book element
if (event.isEndElement())
{
EndElement endElement = event.asEndElement();
if (endElement.getName().getLocalPart() == (BOOK))
{
books.add(book);
}
}
}

} catch (FileNotFoundException ex)
{
ex.printStackTrace();
} catch (XMLStreamException ex)
{
ex.printStackTrace();
}
return books;
}

}

So now we are going to read XML from books.xml


import java.util.List;

import model.Book;

public class TestRead
{

/**
* @param args
*/
public static void main(String[] args)
{
BookParser parser = new BookParser();
List<Book> books = parser.readBooks("books.xml");
for (Book book : books)
{
System.out.println(book);
}

}

}

 
Leave a comment

Posted by on November 5, 2012 in Java, XML

 

Tags: ,