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
[sourcecode language="java"]
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 + "]";
}
}
[/sourcecode]
Main.java
[sourcecode language="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();
}
}
}
[/sourcecode]
PHP REST client
CURL or file_get_contents() can be used to get JSON from the web service URL.
[sourcecode language="php"]
$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;
[/sourcecode]
Android REST client
Download
[sourcecode language="java"]
[/sourcecode]
Wednesday, November 28, 2012
Sunday, November 18, 2012
Android Login System using SQLite
I have already written several posts regarding Android database applications. This post might be similar to those tuts. However this is more complete Android Login System which uses SQLite as its database. All files can be downloaded here or there
Let's create the view. first. But I'm not going to show it in the post. Just two text boxes for username and password, two buttons for login and register.
DBHelper.java
[sourcecode language="java"]
package com.my.members;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "membersdb";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "CREATE TABLE (_id integer primary key autoincrement,username text not null,password text not null);";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.execSQL("DROP TABLE IF EXISTS members");
onCreate(db);
}
}
[/sourcecode]
DBAdapter.java
[sourcecode language="java"]
package com.my.members;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBAdapter
{
private static final String DATABASE_TABLE = "members";
public static final String KEY_ROW_ID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
SQLiteDatabase mDb;
Context mCtx;
DBHelper mDbHelper;
public DBAdapter(Context context)
{
this.mCtx = context;
}
public DBAdapter open() throws SQLException
{
mDbHelper = new DBHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close()
{
mDbHelper.close();
}
public long register(String user,String pw)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pw);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
public boolean Login(String username, String password) throws SQLException
{
Cursor mCursor = mDb.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
}
[/sourcecode]
MembersActivity
[sourcecode language="java"]
package com.my.members;
import android.app.Activity;
import android.content.Context;
import android.database.SQLException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MembersActivity extends Activity {
DBAdapter dbAdapter;
EditText txtUserName;
EditText txtPassword;
Button btnLogin;
Button btnRegister;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtUserName = (EditText) findViewById(R.id.et_user);
txtPassword = (EditText) findViewById(R.id.et_pw);
btnLogin = (Button) findViewById(R.id.btn_login);
btnRegister = (Button) findViewById(R.id.btn_reg);
dbAdapter = new DBAdapter(this);
dbAdapter.open();
btnLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtUserName.getWindowToken(), 0);
imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
if (username.length() > 0 && password.length() > 0) {
try {
if (dbAdapter.Login(username, password)) {
Toast.makeText(MembersActivity.this,
"Successfully Logged In", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(MembersActivity.this,
"Invalid username or password",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(MembersActivity.this, "Some problem occurred",
Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(MembersActivity.this,
"Username or Password is empty", Toast.LENGTH_LONG).show();
}
}
});
btnRegister.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(txtUserName.getWindowToken(), 0);
imm.hideSoftInputFromWindow(txtPassword.getWindowToken(), 0);
try {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
long i = dbAdapter.register(username, password);
if(i != -1)
Toast.makeText(MembersActivity.this, "You have successfully registered",Toast.LENGTH_LONG).show();
} catch (SQLException e) {
Toast.makeText(MembersActivity.this, "Some problem occurred",
Toast.LENGTH_LONG).show();
}
}
});
}
}
[/sourcecode]
Donate & help live a developer
Saturday, November 10, 2012
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
[sourcecode language="html"]
<!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>
[/sourcecode]
PHP Script
[sourcecode language="php"]
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>";
}
[/sourcecode]
Wednesday, November 7, 2012
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 Source Code
Download Source Code
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.
[sourcecode language="java"]
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 + "]";
}
}
[/sourcecode]
Database.java
[sourcecode language="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;
}
}
}
[/sourcecode]
Access.java
[sourcecode language="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;
}
}
[/sourcecode]
AccessManager.java
[sourcecode language="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;
}
}
[/sourcecode]
CourseService.java
[sourcecode language="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;
}
}
[/sourcecode]
web.xml
[sourcecode language="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>
[/sourcecode]
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.
We will see how various clients can consume this web service in the second part of the tutorial.
Download Source Code
Download Source Code
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.
[sourcecode language="java"]
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 + "]";
}
}
[/sourcecode]
Database.java
[sourcecode language="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;
}
}
}
[/sourcecode]
Access.java
[sourcecode language="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;
}
}
[/sourcecode]
AccessManager.java
[sourcecode language="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;
}
}
[/sourcecode]
CourseService.java
[sourcecode language="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;
}
}
[/sourcecode]
web.xml
[sourcecode language="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>
[/sourcecode]
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.
Monday, November 5, 2012
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 :
Create new dynamic web project. Add following jars from the downloaded Jersey zip file to WEB-INF/lib. Add them to project Build Path.
[sourcecode language="java"]
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> ";
}
}
[/sourcecode]
[sourcecode language="java"]
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();
}
}
[/sourcecode]
[sourcecode language="java"]
<?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>
[/sourcecode]
web.xml is tricky!
[Extracted from : http://www.javahotchocolate.com/tutorials/restful.html]
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:
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 :
- Eclipse IDE
- Jersey - Download Zip archive including .jar files
Main Topics
- Install Jersy plugin
- Create resource
- Create client
- 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
[sourcecode language="java"]
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> ";
}
}
[/sourcecode]
3. Create client
[sourcecode language="java"]
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();
}
}
[/sourcecode]
4. Configure web.xml
[sourcecode language="java"]
<?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>
[/sourcecode]
web.xml is tricky!
[Extracted from : http://www.javahotchocolate.com/tutorials/restful.html]
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/*
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
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
[sourcecode language="xml"]
<?xml version="1.0"?><books>
<type>1</type>
<title>901</title>
<author>0</author>
</books>
[/sourcecode]
Book.java (Model class)
[sourcecode language="java"]
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 + "]";
}
}
[/sourcecode]
BookParser.java
[sourcecode language="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();
}
}
[/sourcecode]
So now we are going to write XML to books2.xml
[sourcecode language="java"]
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();
}
}
}
[/sourcecode]
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
[sourcecode language="xml"]
<?xml version="1.0"?><books>
<type>1</type>
<title>901</title>
<author>0</author>
</books>
[/sourcecode]
Book.java (Model class)
[sourcecode language="java"]
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 + "]";
}
}
[/sourcecode]
BookParser.java
[sourcecode language="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();
}
}
[/sourcecode]
So now we are going to write XML to books2.xml
[sourcecode language="java"]
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();
}
}
}
[/sourcecode]
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
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
[sourcecode language="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>
[/sourcecode]
Book.java (Model class)
[sourcecode languaje="java"]
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 + "]";
}
}
[/sourcecode]
BookParser.java
[sourcecode languaje="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;
}
}
[/sourcecode]
So now we are going to read XML from books.xml
[sourcecode languaje="java"]
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);
}
}
}
[/sourcecode]
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
[sourcecode language="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>
[/sourcecode]
Book.java (Model class)
[sourcecode languaje="java"]
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 + "]";
}
}
[/sourcecode]
BookParser.java
[sourcecode languaje="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;
}
}
[/sourcecode]
So now we are going to read XML from books.xml
[sourcecode languaje="java"]
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);
}
}
}
[/sourcecode]
Saturday, November 3, 2012
Java SOAP Web Service With Apache Axis2 in Netbeans
<
Requirements
Main Topics
- Setup Development Environment
- Create Web Service
- Deploy Web Service to Tomcat Server
1. Setup Development Environment
Install Axis2 Support Plugin
Go to Tools >> Plugins and open Plugin Manager. Check whether Axis2 Support Plugin is already installed. Otherwise you may need to find it from Available Plugins and install.
Configure Axis2 for Tomcat
Extract axis2.war archive to Tomcat webapps directory.
You can find this directory in your CATALINA_BASE/webapps. If you are not sure where CATALINA_BASE points to, open Services tab and select Tomcat server. Right click Tomcat server and select properties. Most probably you will find it there. If there is no CATALINA_BASE, you have not run your Tomcat before. Start and stop Tomcat to allow this varible generate.
Start or restart the Tomcat server. Tomcat unpacks the axis2.war file into an axis2 folder in CATALINA_BASE/webapps.
Go to Tools >> Options and click Axis2 icon to view deployment options. Set the target location for Axis2 AAR files to your CATALINA_BASE (not TOMCAT_HOME)/ webapps/axis2 directory.
Make sure the Axis2 URL field contains the correct port number for your Tomcat server. To check the port number, start Tomcat (from the Services tab or from Tools -> Servers) and see what port Coyote HTTP/1.1 uses.
select Use Tomcat Manager for Deployment
Check whether username and password of manager role are correct by referring CATALINA_BASE/conf/tomcat-users.xml.
2. Create Web Service
File >> New Project. The New Project wizard opens. From the Java category, select a Java class library project. Click Next.
Right-click the project and choose New >> Other. The New File wizard opens. From the Web Services category, choose Axis2 Service from Java and click Next.
Keep settings as it is in the following wizard and click Next.
In this wizard enter Java Web Service class name and click Finish.
The IDE generates a HelloAxisWorld.java class in the axishello source package and a HelloAxisWorld Axis2 web service that mirrors this Java class.
3. Deploy Web Service to Tomcat Server
Right-click the web service's node. The context menu opens. Select Deploy to Server. The IDE compiles an Axis2 AAR file and copies it to the axis2.war file used by the application server.
If you enabled automatic deployment in Tomcat Manager, axis.war will automatically redeploy to server whenever it 's get updated.
To test the service, expand the web service node to reveal the operations. Right-click the hello:String node and select Test Operation in Browser.
To test the service, expand the web service node to reveal the operations. Right-click the hello:String node and select Test Operation in Browser.
Browser opens with a test value of your variables. You can find test value in the URL. Change it and refresh the page.
Friday, November 2, 2012
Java SOAP Web Service With Apache Axis2 in Eclipse
Today we are going to build a SOAP based Java web service. We are using AXIS2 which serves as a SOAP implementation. I assume that you have already installed Java JDK in to your machine.
Requirements :
1) Eclipse EE – Download
2) Apache Tomcat - Download
3) Apache Axis2 Binary Distribution - Download
4) Apache Axis2 WAR Distribution - Download
While installing these programs, consider about default ports. There may be port conflicts if you neglect this fact. This becomes an issue only if you are allocating ports which are already used by previously installed programs. For an instance, there may be a port conflict when attempting to install Tomcat server using port 8080 in a machine where Oracle 10g is installed. Both of these use port 8080 by default. So you may change the ports as necessary during or after the installation.
Please note that there may be various compatibility issues when using Eclipse and Apache Tomcat with Axis2 to build our web service. Most of the problems can be minimized with Netbeans. GlassFish server supports out of the box in many occasions with Netbeans.
Let's deal with Netbeans at a later time.
I'm using Eclipse Indigo, Apache Tomcat 6 and Axis2 for this tutorial.
Extract Apache Axis2 Binary Distribution. Create an Environment Variable as AXIS2_HOME. Get the path to Axis2 installation directory and use it as the value of AXIS2_HOME Environment Variable. (something like C:\Program Files\axis2-1.6.2)
Extract Axis2 WAR Distribution and copy axis2.war file to Tomcat server webapps directory.
Now you are ready to go ahead with this tutorial. First check our road map.
1. Setup Development Environment in Eclipse.
2. Create Web Service.
3. Deploy web service.
4. Create a client who consumes Web Service.
1. Setup Development Environment in Eclipse.
Now you need to configure Eclipse for Tomcat server and Axis2.
Open Eclipse IDE and go to Window >> Preferences
Add new server runtime environment.
Select your Tomcat server version and click Next. Browse your Tomcat installation directory in next window.
Now configure Axis2 in Axis2 preferences under Web Services category. Browse your Axis2 installation directory. You should see this message if this is fine.
"Axis2 runtime loaded successfully"
Select Server and Runtime. Make sure your server runtime is selected. Web service runtime should be Apache Axis2.
2. Create Web Service.
First create a new Dynamic Web Project (File >> New >> Other) and choose Web >> Dynamic Web Project. Enter project settings in the first window.
Select the target runtime that we configured earlier.
You should modify the configuration so that Axis2 is included into the project.
Remeber to put a tick on Axis2 web services
Click Next>>Next and Finish. Now Eclipse will load the project.
Now it's time to create web service class. This class can contain some methods which are exposed to outside. The clients are going to consume this web service class. First we create a Plain Old Java Class and convert it into a web service. Right click on project and select New>> Class
Add a public method to this class.
[sourcecode language="java"]
package com.codezone4;
public class MyService
{
public String testMethod(String param)
{
return "Read " + param;
}
}
[/sourcecode]
To expose this file as a web service right click on the Java file and select Web Services >> Create Web Service
or
select File >> New >> Other and choose Web Service.
You can can add web service using one of above methods.
We use bottom-up approach as web service type. Select the class which acts as the web service(that we just created). Make sure your configurations are correct.
Click Next. Make sure Generate a default service.xml file is selected and click Next. Now you are asked to Start Server. Do it!
Then Click Next and Finish the dialog.
Now you should be able to reach your web service through your browser. Tomcat server is started and you gonna run your web service in Tomcat.
Right click on your project and select Run as >> Run on server.
You may see the below screen through your Eclipse web browser. Alternatively you can copy the following URL into your web browser bar.
http://localhost:8440/HelloWorldWebService/
This port number 8888 depends on your Tomcat configuarations.
Go to Services. Under Available Services you will find your own service. Click on MyService link (You will find your web service class name here).
Can you see bunch of beautiful xml? This is your WSDL(Web Service Description Language). The clients who consume your service communicate with this WSDL to access the functionality of the web service.
Copy the URL for WSDL file.
You can validate this file at a later time when you create the client. To do that enable WSDL validation for all files in Eclipse preferences. This option can be found under web service category.
Obviously you can play with your web service without a real client using Web Service Explorer tool in Eclipse. Click that icon
This will launch a screen similar to the following.
Click WSDL page icon. On the next screen, click WSDL Main under navigation section.
Enter your WSDL URL into the box and click Go. On the left you will see a hierarchical representation of your web service. Play around with this for a while and test your web service with different inputs....
3. Deploy web service.
In current situation, the web service can only be run within Eclipse. So we are going to deploy it to Tomcat server. First create .aar (Axis Archive)
Got to your web service directory using command prompt.
Eg. C:\Users\AAA\Documents\Eclipse\HelloWorldWebService\WebContent\WEB-INF\services\MyService
Enter following command to create .aar file.
jar cvf HelloWorldWebService.aar com META-INF
This will generate .aar file in your web service directory. Now wanna upload this file using the Administration panel in Axis2. You can enter this area using Axis home page Administration link.
username : admin
password : axis2
Or else you can simply copy the .aar file and paste into Tomcat webapps\axis2\WEB-INF\services directory.
To verify your deployment first stop Tomcat server in Eclipse. Click on red, small rectangular button on Servers panel to stop Tomcat.
Next go to Tomcat bin directory and find startup.bat file. Run this file to start Tomcat. If you are using Mac run startup.sh file.
Then go to your web service URL.
http://localhost:8440/HelloWorldWebService/
4. Create a Web service client
Select File >> New >> Other and choose Web Service Client.
Enter WSDL URL into the box. Here you can browse for WSDL and validate if needed.
This will generate two new classes called MyServiceStub.java and MyServiceCallbackHandler.java. Now we can create client. Create new class called TestClient.java and paste following code.
[sourcecode language="java"]
package com.codezone4;
import java.rmi.RemoteException;
import com.codezone4.MyServiceStub.TestMethod;
import com.codezone4.MyServiceStub.TestMethodResponse;
public class TestClient {
public static void main(String[] args) throws RemoteException {
MyServiceStub stub = new MyServiceStub();
TestMethod method = new TestMethod();
method.setParam(" Cheers!");
TestMethodResponse response = stub.testMethod(method);
System.out.println(response.get_return());
}
}
[/sourcecode]
Run this client as a Java application. Observe the output in console. You should see the message that resulted from remote method call if everything worked fine.
I think you enjoy this web service tut. Please leave a comment.
Happy coding!
Subscribe to:
Posts (Atom)
How to enable CORS in Laravel 5
https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...
-
< Requirements Java Development Kit (JDK) NetBeans IDE Apache Axis 2 Apache Tomcat Server Main Topics Setup Development Environ...
-
Download Sourcecode [sourcecode language="csharp"] using System; using System.Collections.Generic; using System.Linq; using System...