JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

WebServices : REST vs SOAP

April 26, 2014 by Krishna Srinivasan Leave a Comment

The World Wide Web is evolving from a sea of information to a service oriented marketplaces and Web Services are a critical part of this evolution.

What is a Web service?

A web service is a method of communication between two electronic devices over the World Wide Web.

W3C defines web service as a “software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web-related standards.” [1]

Web-service-diagram

A more constrained architectural style for reliable Web applications known as Representation State Transfer (REST) was proposed by Roy Fielding. [2] In a REST-style architecture requests and responses are built around the transfer of representations of resources. A resource (e.g. Person) can be essentially any coherent and meaningful concept that may be addressed. A representation of a resource is typically a document (e.g. XML or JSON) that captures the current or intended state of a resource.

What is SOAP?

SOAP is a protocol specification for exchanging structured information in the implementation of Web Services. It uses XML for the message format. It is independent of the transport protocol (could be HTTP, FTP, TCP, UDP, or named pipes).

SOAP based services strictly define the format of messages passed back and forth. A SOAP message contains the data, the action to perform on it, the headers, and the error details in case of failure. Security is provided by WS-Security standards and is end-to-end. It supports identity through intermediaries, not just point to point (SSL).

SOAP provides a mechanism for services to describe themselves to clients (WSDL), and to advertise their existence (UDDI). SOAP also provides reliable messaging (WS-ReliableMessaging), that is a successful retry logic built in and provides end to end reliability through soap intermediaries.

What is REST?

Representational State Transfer (REST) is an architecture style for designing networked applications, that

  1. Involves clients and servers sending request and responses respectively.
  2. Request and response are built around the transfer of representations of resources. (e.g. request JSON representation of User)

REST recognises everything a resource (e.g. User, Lottery, etc.) and each resource implements a standard uniform interface (typically HTTP interface), resources have name and addresses (URIs), each resource has one or more representation (like JSON or XML) and resource representations move across the network usually over HTTP.

RESTful web APIs (or RESTful web service) is a web API implemented using HTTP and principles of REST. RESTful API separates user interface concerns from data storage concerns. It improves portability of interface across multiple platforms and simplifies server components by making them stateless. Each request from client contains all the state information and server does not hold client context in the session.

SOAP vs REST?

One of the major benefits of SOAP is that you have a WSDL service description. You can pretty much discover the service automatically and generate a useable client proxy from that service description (generate the service calls, the necessary data types for the methods and so forth). Note that with version 2.0, WSDL supports all HTTP verbs and can be used to document RESTful services as well, but there is a less verbose alternative in WADL (Web Application Description Language) for that purpose.

With RESTful services, message security is provided by the transport protocol (HTTPS), and is point-to-point only. It doesn’t have a standard messaging system and expects clients to deal with communication failures by retrying. SOAP has successful/retry logic built in and provides end-to-end reliability even through SOAP intermediaries.

One of the major benefits of RESTful API is that it is flexible for data representation, for example you could serialize your data in either XML or JSON format. RESTful APIs are cleaner or easier to understand because they add an element of using standardised URIs and gives importance to HTTP verb used (i.e. GET, POST, PUT and DELETE).

RESTful services are also lightweight, that is they don’t have a lot of extra xml markup. To invoke RESTful API all you need is a browser or HTTP stack and pretty much every device or machine connected to a network has that.

Finally, which ever architecture you choose make sure its easy for developers to access it, and well documented.

This article is originally published at BLOG BY MANISH CHHABRA, re-posted here with authors permission and as part of the JBC program. 

Filed Under: WebServices Tagged With: REST, SOAP

RESTful Web Service using Jersey

November 14, 2013 by Krishna Srinivasan Leave a Comment

In this tutorial I am going to explain a very basic example using Jersey REST Services. Building webservices using the REST concept is popular because of its simple nature and light weight. We have already explained how to write REST services using the Spring MVC framework. Spring provides out of the box support for the REST integration using their MVC framework. Jersey is the reference implementation for the REST specification. Writing your first REST service is very simple.

1. SetUp Jersey Environment

You have to get the required JAR files to get start with Jersey development. You would require the following JAR files.

  • asm-all-3.3.1.jar
  • jersey-core-1.17.jar
  • jersey-server-1.17.jar
  • jersey-servlet-1.17.jar

jersey-example

Alternatively you can set the maven dependency if you use maven as the build tool.

[code lang=”xml”]
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-servlet</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.17.1</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
[/code]

2. Create Jersey REST Service

[code lang=”java”]
package org.jersey.examples;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class JerseySimpleExample {
@GET
@Path("/{param}")
public Response getMsg(@PathParam("param") String message) {
String output = "HI Jersey : " + message;
return Response.status(200).entity(output).build();
}
}
[/code]

3. Configure Web.xml for Jersey Implementation

[code lang=”xml”]
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Jersey Example</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>jersey</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>org.jersey.examples</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/jersey/*</url-pattern>
</servlet-mapping>
</web-app>
[/code]

4. Run First Jersey Service

Onec the above steps are completed, you can access the Jersey application using the following URL:

[code]
http://localhost:8080/DOJO_APP/rest/hello/krishna
[/code]

I hope this tutorial helped you to easily get started on using the Jersey REST API. In my future articles, I will come up with few more examples.

Filed Under: WebServices Tagged With: Jersey, REST

Implementing RESTful API for obtaining the book details for an ISBN

May 8, 2012 by Mohamed Sanaulla Leave a Comment

Lot of developers out there at some point in time would want to know about an API to get the book details and I was in such a situation sometime back and I managed to find out about ISBNDb. But when I looked for the apis sometime later, I landed here where there are 53 APIs are listed. I am not sure how easy are others to use, but I found ISBNDb was just enough for my needs.

The base URL for the API is: https://isbndb.com/api/books.xml. It supports querying on lot of attributes like isbn, title, book_id, publisher_id (which are ISBNdb specific). In this example we are interested in using ISBN to query for the book details. But before proceeding further, you have to sign up to get access to the developer key. Once you have the developer key, to get the book details given the ISBN the URL would be: https://isbndb.com/api/books.xml?access_key=[KEY]&index1=isbn&value1=[ISBN]. The access_key query param would be assigned the key which you have obtained. index1, value1 are the params which are used to pass filter data for obtaining the book details.  We could even filter on book title wherein we add index2=title and value2=any_book_title.

also read:

  • Java EE Tutorials
  • Java EE 7 Tutorials
  • Java EE Interview Questions

Lets use this API to obtain the book details and this would be implemented in Groovy.

Our Model class for the holding a book details would be:

[code lang=”java”]
class Book {
def isbn
def title
def authors
def publisher
def String toString(){
"Title: ${title}\nISBN: ${isbn}\n"+
"Authors: ${authors}\n"+
"Publisher: ${publisher}"
}
}
[/code]

Building the URL for the API invocation:

[code lang=”java”]

def baseURL = "https://isbndb.com/api/books.xml"
def ACCESS_KEY = "YOUR_KEY"

def scanner = new Scanner(System.in);
println "Enter the ISBN"
def isbnInput = scanner.nextLine()
def queryParams = []
queryParams &lt;&lt; "access_key=${ACCESS_KEY}"
queryParams &lt;&lt; "index1=isbn"
queryParams &lt;&lt; "value1=${isbnInput}"
def queryString = queryParams.join("&amp;")
def completeApiURl = "${baseURL}?${queryString}"

[/code]

The above code accepts the ISBN from the User and then prepares the required URL for invoking. One can see that we have made use of Java class in Groovy. The operator “<<” when used with an array appends the values to the array. And the join(“&”) would concatenate all the elements of the array using the “&” character. Once we have the complete URL, we make use of the java.net.URL class to obtain the XML Response and then use XmlSlurper (remember JsonSlurper?) to parse the XML to get the required information:

[code lang=”java”]
def apiResponse = new URL(completeApiURl).text
def xmlSlurper = new XmlSlurper()
def parsedXml = xmlSlurper.parseText(apiResponse)

def newBook =
new Book(title:parsedXml.BookList.BookData.Title,
isbn: parsedXml.BookList.BookData.@isbn,
authors: parsedXml.BookList.BookData.AuthorsText,
publisher: parsedXml.BookList.BookData.PublisherText)

println newBook
[/code]

The complete code is:

[code lang=”java”]
def baseURL = "https://isbndb.com/api/books.xml"
def ACCESS_KEY = "MKKGCUMQ"

def scanner = new Scanner(System.in);
println "Enter the ISBN"
def isbnInput = scanner.nextLine()
def queryParams = []
queryParams &lt;&lt; "access_key=${ACCESS_KEY}"
queryParams &lt;&lt; "index1=isbn"
queryParams &lt;&lt; "value1=${isbnInput}"
def queryString = queryParams.join("&amp;")
def completeApiURl = "${baseURL}?${queryString}"
def apiResponse = new URL(completeApiURl).text
def xmlSlurper = new XmlSlurper()
def parsedXml = xmlSlurper.parseText(apiResponse)

def newBook = new Book(title:parsedXml.BookList.BookData.Title,
isbn: parsedXml.BookList.BookData.@isbn,
authors: parsedXml.BookList.BookData.AuthorsText,
publisher: parsedXml.BookList.BookData.PublisherText)
println newBook

class Book {
def isbn
def title
def authors
def publisher

def String toString(){
"Title: ${title}\n"+
"ISBN: ${isbn}\n"+
"Authors: ${authors}\n"+
"Publisher: ${publisher}"
}
}
[/code]

The execution and output of the above code:

[code]
$ groovy BookManager.groovy
Enter the ISBN
098478280X
Title: Cracking the Coding Interview
ISBN: 098478280X
Authors: Gayle Laakmann McDowell,
Publisher: CareerCup
[/code]

Filed Under: Java EE Tagged With: REST

Invoking RESTful Web Service using API in java.net and GSON

May 1, 2012 by Mohamed Sanaulla Leave a Comment

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 and more specifically statuses/user_timeline API. A bit about the API:

also read:

  • Java Tutorials
  • Java EE Tutorials
  • Design Patterns Tutorials
  • Java File IO Tutorials

GET status/user_timeline: Returns the 20 most recent statuses posted by the authenticating user. It is also possible to request another user’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’s follow request was accepted by the protected user.
The resource URL is: http://api.twitter.com/1/statuses/user_timeline.format
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:

[code lang=”java”]
class Tweet{
public String text;
public String created_at;
public String toString(){
return "Posted "+text+" at "+created_at;
}
}
[/code]

The example can be divided into:

  1. Take screen name input from the user and construct the URL for the API which we call as the fetchURL.
  2. Use URLConnection class and its connect() and getInputSteam() APIs to connect to the fetchURL and then obtain the input stream.
  3. The input stream obtained above is used to construct the JsonReader object( from the GSON library).
  4. Then parse the JSON as explained here.

Invoking the REST API:

[code lang=”java”] String fetchUrl =
"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
//this.screenName is obtained as a user input
fetchUrl = fetchUrl+this.screenName;
URLConnection urlConnection =  new URL(fetchUrl).openConnection();
urlConnection.connect();[/code]
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.
Parsing the JSON response:

[code lang=”java”] JsonReader reader = new JsonReader(
new InputStreamReader(urlConnection.getInputStream()));
JsonParser parser = new JsonParser();
JsonElement rootElement = parser.parse(reader);
JsonArray tweetsJson = rootElement.getAsJsonArray();[/code]

Populate the required model instances and add them to the List of tweets (or List<Tweet>).

[code lang=”java”] List timeline = new ArrayList();
Gson myGson = new Gson();
for ( JsonElement tweetElement : tweetsJson){
Tweet myTweet = myGson.fromJson(tweetElement, Tweet.class);
timeline.add(myTweet);
}[/code]

Read here for details on parsing the JSON using Java and GSON API.

Here is the complete code:

[code lang=”java”]
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("Enter the screen name");
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 =
"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=";
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 "Posted "+text+" at "+created_at;
}
}
[/code]

Note: Make sure you have GSON library in the classpath.

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.

Filed Under: Java Tagged With: GSON.JSON, REST

Invoking SOAP and RESTful Web Services using Flex 4.0

February 28, 2011 by Krishna Srinivasan Leave a Comment

Introduction

Flex 4.0 framework facilitates to interact with various kinds of RPC services. Flex Applications can invoke traditional Web Services or Restful web services that returns XML, JSON etc. MXML’s RPC components provides access to SOAP (Simple Object Access Protocol) based web services and Restful web services using HTTP Services. Flex supports requests and responses of web services which are defined as SOAP messages. SOAP defines a standard for communicating the request and response using XML between the Service provider and consumer. The proxy service for LCDS (LiveCycle Data Services) and BlazeDS intercepts requests to web services located remotely, redirects the requests, and returns the responses to the consumers.

also read:

  • Adobe Flex Tutorials
  • Java FX Tutorials
  • Charting with Flex 4.0
  • New Features in Flex 4.0

Working with Web Services

The RPC components and non visual components can be defined in MXML using <fx:Declarations> tag. The Web service components can be created using MMXL code or Action Script (the Object oriented language for Flex) classes also. Let us define a simple SOAP based web service using Java (JAX-WS) that is displayed in a web server to just say Hello to the received user name.

JAX-WS Web Service
[code lang=”java”] package mypack;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
*
* @author GopiKrishna_Chaganti
*/
// defining the web service
@WebService()
public class FlexWS {

/**
* Web service operation
*/// defining the web method for execution
@WebMethod(operationName = "greet")
public String greet(@WebParam(name = "name") // parameter passed
String name) {
return "Hello "+name+", this is a SOAP Web Service!";// response returned in SOAP
}
} [/code]
SOAP based web services need to define the WSDL file so that the consumers can implement the client stubs.
Let us create Flex 4 MXML code to invoke the web service:
[code lang=”xml”] <?xml version="1.0" encoding="utf-8"?>
<!–Defining the Flex app container –>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" xmlns:ns1="*">

<fx:Declarations>
<!– declaring the web service using Flex 4 spark component,
wsdl attribute to define the location of WSDL,
useProxy to confirm the usage of proxy –>
<s:WebService id="srv" wsdl="http://localhost:8080/FlexWS/FlexWSService?WSDL" useProxy="false" showBusyCursor="true">
<!–once result is received succefully, this block will be used –>
<s:result>
tt.visible = true;
tt.text= event.result.toString();
Alert.show(event.result.toString());
</s:result>
<!–defining the fault handler –>
<s:fault>
Alert.show(event.fault.faultString);
</s:fault>
</s:WebService>
</fx:Declarations>
<s:VGroup width="100%" height="100%" paddingLeft="15" paddingTop="15">
<s:HGroup gap="10">
<mx:FormItem label="Enter your name : " color="#EEE7E7" focusColor="#70EDEE" borderColor="#C14F4F" chromeColor="#0C0C0C" backgroundColor="#271818" dropShadowVisible="true">
<s:TextInput id="t" color="#0C0D0D"/>
</mx:FormItem>
</s:HGroup>
<s:HGroup width="312" height="62">
<s:TextArea id="tt" width="313" height="59" verticalAlign="middle" textAlign="center"/>
</s:HGroup>
<s:TileGroup width="150" height="21">
<!– calling the appropriate method of web service –>
<s:Button label="SOAP" click="srv.greet(t.text)" x="68" y="10"/>
</s:TileGroup>
</s:VGroup>
</s:Application>[/code]
The execution is as follows: After entering the name and clicking the SOAP button the following output can be observed.

Invoing Restful Web Service

Let us modify the code to invoke the Restful web service. The Java restful web service is defined as follows:

JAX-RS Service
[code lang=”java”] package mypack;

import java.util.Date;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

/**
* REST Web Service
*
* @author GopiKrishna_Chaganti
*/
// defining the JAX-RS resource class
@Path("weather")
public class WeatherResource {
// this method is invoked when the GET method is used to invoke the HTTP url.
@GET
@Produces
public String getHtml(@QueryParam("name") String name) { // Query parameter is defined
return "Hi " + name.toUpperCase() + ", you are using Restful Web Service!";
}[/code]
Let us modify the Flex 4 MXML as well as follows:
Add the following mxml code to the <fx:Declarations> tag.
GET and POST methods can mentioned before accessing the Restful web service using method attribute.
[code lang=”xml”] <s:HTTPService id="userRequest" url="http://localhost:8080/FlexWS/resources/weather"
useProxy="false" method="GET">
<s:request xmlns="">
<name>{t.text}</name>
</s:request>
<s:result>
tt.text=event.result.toString();
</s:result>
</s:HTTPService>[/code]
Now the output can be shown as follows:

Invoing Restful Web Service for JSON response

After entering the text and clicking on Restful button the above output will be observed. Let us further add one more method to Restful web service to generate the JSON response for the weather casting request.

JAX-RS Service with JSON response
[code lang=”java”] @Path("weather")
public class WeatherResource {

@GET
@Produces("text/plain")
public String getHtml(@QueryParam("name") String name) {
return "Hi " + name.toUpperCase() + ", you are using Restful Web Service!";
}

@GET
@Produces({"application/json"})
@Path("{city}")
public Weather getJSon(@PathParam("city") String city) {
System.out.println("Request for " + city + " came!");
Weather w = new Weather();
w.setDate(new Date());
w.setCity(city);
if (city.equals("Hyderabad")) {
w.setClimate("Its Hot today!");
} else if (city.equals("Bangalore")) {
w.setClimate("Its Cool today!");
} else {
w.setClimate("Its Humid today!");
}
return w;
}
}[/code]
The above getJSon receives the path parameter for JAX-RS resource class and generates the JSON weather response for the city requested. To achieve this we can use JAXB class to generate the JSON response. The Weather JAXB pojo is as follows:
[code lang=”java”] package mypack;

import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author GopiKrishna_Chaganti
*/
@XmlRootElement // defining the root element
public class Weather {
Date date;
String city;
// defining the sub elements
@XmlElement
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}

@XmlElement
public String getClimate() {
return climate;
}

public void setClimate(String climate) {
this.climate = climate;
}
String climate;
@XmlElement
public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}
}[/code]
The following Flex 4 MXML and Action script will send the request to the weather casting Restful web service.
[code lang=”java”] <?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="100%" height="100%" >
// defining the Action Script
<fx:Script>
<![CDATA[
import com.adobe.serialization.json.*;
import com.adobe.webapis.*;
import com.adobe.webapis.events.*;

import mx.controls.Alert;
import mx.rpc.events.ResultEvent;
import mx.rpc.http.HTTPService;

private function search():void
{
// defining the HTTP Service & adding the path parameter
var service:HTTPService = new HTTPService();
service.url = "http://localhost:8080/FlexWS/resources/weather/"+searchStr.text;

// for setting query parameters if any
//service.request.city = searchStr.text;
// result format is considered as text
service.resultFormat = "text";
// adding the listener to execute when the successful response is received
service.addEventListener(ResultEvent.RESULT, onServerResponse);
// sending the request
service.send();
}
private function onServerResponse(event:ResultEvent):void {
try {
// decoding the event response text to JSON response
var json:Object = JSON.decode(event.result as String);
// extracting the data
date.text=json.date.toString();
city.text=json.city.toString();
climate.text=json.climate.toString();
Alert.show("Displayed"+json.city);
}

// handling if fault is received
catch (error:Error) {
Alert.show("Error on search: " + error.message);
}
}

]]>
</fx:Script>

<mx:TextInput id="searchStr" enter="search()" width="200" x="201" y="76"/>
<mx:Label text="Get Weathercasting: " x="56" y="78"/>
<mx:Button id="btnSearch" click="search()" label="Search" x="441" y="77"/>

<mx:Label text="Date : " x="227" y="154"/>
<mx:Text id="date" x="307" y="154"/>
<mx:Label text="City : " x="227" y="185"/>
<mx:Text id="city" x="307" y="185"/>
<mx:Label text="Climate : " x="227" y="213"/>
<mx:Text id="climate" x="307" y="213"/>

</s:Application>[/code]
The output can observed as below:

Invoing Restful Web Service for XML response

Let us add one more method to the restful web resource to represent the climate variations for yesterday, today and tomorrow days.

JAX-RS Service with XML response
[code lang=”java”] String[] cities = {"cityA", "cityB", "cityC", "cityD", "cityE"};

@GET
@Produces({"application/xml"})
@Path("predict")
public WeatherCast[] getXML() {
System.out.println("PREDICT called!!!!!!!");
WeatherCast[] wc = new WeatherCast[5];
for (int i = 0; i < 5; i++) {
wc[i] = new WeatherCast();
wc[i].setCity(cities[i]);
wc[i].setToday(i*Math.random());
wc[i].setYesterday(i*Math.random()-10);
wc[i].setTomorrow(i*Math.random()+10);
}
return wc;
}

====================================================
JAXB class for WeatherCasting
====================================================
package mypack;

import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
*
* @author GopiKrishna_Chaganti
*/
@XmlRootElement
public class WeatherCast {
String city;
double yesterday;
double today;

public double getToday() {
return today;
}

public void setToday(double today) {
this.today = today;
}

public double getTomorrow() {
return tomorrow;
}

public void setTomorrow(double tomorrow) {
this.tomorrow = tomorrow;
}

public double getYesterday() {
return yesterday;
}

public void setYesterday(double yesterday) {
this.yesterday = yesterday;
}
double tomorrow;

@XmlElement
public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

@XmlElement
public String getClimate() {
return climate;
}

public void setClimate(String climate) {
this.climate = climate;
}
String climate;
}[/code]
Line chart control can be added to MXML code to receive the XML response as below:
[code lang=”java”] <mx:LineChart id="chart" dataProvider="{weatherData.weatherCast}" width="100%" height="100%">
<mx:series>
<mx:LineSeries xField="today" yField="today" displayName="Today" />
<mx:LineSeries xField="tomorrow" yField="tomorrow" displayName="Tomorrow" />
<mx:LineSeries xField="yesterday" yField="yesterday" displayName="Yesterday" />
</mx:series>
</mx:LineChart>
<mx:Legend dataProvider="{chart}" />[/code]
The output can be shown as follows:

Conclusion

Flex supports extensively for web services. Using RPC components, Flex applications can connect to the remote services like SOAP and REST based web services. Flex can also handle various responses like XML, JSON etc using its rich API.

Filed Under: Adobe Flex Tagged With: Adobe Flex 4.0, REST, WebServices

RESTful Java Web Services

December 8, 2009 by Krishna Srinivasan Leave a Comment

RESTful Java Web ServicesThis article is sample chapter for the book RESTful Java Web Services. If you’re already familiar with REST theory, but are new to RESTful Java web services, and want to use the Java technology stack together with Java RESTful frameworks to create robust web services, this is the book for you.

also read:

  • What is UDDI?
  • Apache Axis 2 Web Services
  • RESTFul Java Web Services

This book is a guide for developing RESTful web services using Java and the most popular RESTful Java frameworks available today. This book covers the theory of REST, practical coding examples for RESTful clients, a practical outline of the RESTful design, and a complete implementation of a non-trivial web service using the frameworks Jersey’s JAX-RS, Restlet’s Lightweight REST, JBoss’s JAX-RS RESTEasy, and Struts 2 with the REST plugin.

We cover each framework in detail so you can compare their strengths and weaknesses. This coverage will also provide you with enough knowledge to begin developing your own web services after the first reading.

  • Spring RESTFul Services

The RESTful development process follows traditional development paradigms. However, with RESTful web services, we need to analyze the resource requirements first, design the representation for our resources second, identify the URIs third, and, lastly, worry about implementation technologies.

Throughout this book we’ve talked about creating web services that are noun dependent as opposed to verb dependent. In this chapter we’ll look at what that means in terms of the design process. For this, we’ll design a blogging application, but we’ll leave the implementation for later chapters. Our sample application is a micro-blogging web service (similar to Twitter), where users create accounts and then post entries.

Finally, while designing our application, we’ll define a set of steps that can be applied to designing any software system that needs to be deployed as a RESTful web service.

Designing a RESTful web service

Designing RESTful web services is not different from designing traditional web applications. We still have business requirements, we still have users who want to do things with data, and we still have hardware constraints and software architectures to deal with. The main difference, however, is that we look at the requirements to tease out resources and forget about specific actions to be taken on these resources.

We can think of RESTful web service design as being similar to Object Oriented Design (OOD). In OOD, we try to identify objects from the data we want to represent together with the actions that an object can have. But the similarities end at the data structure definition, because with RESTful web services we already have specific calls that are part of the protocol itself.The underlying RESTful web service design principles can be summarized in the following four steps:

  1. Requirements gathering—this step is similar to traditional software requirement gathering practices.
  2. Resource identification—this step is similar to OOD where we identify objects, but we don’t worry about messaging between objects.
  3. Resource representation definition—because we exchange representation between clients and servers, we should define what kind of representation we need to use. Typically, we use XML, but JSON has gained popularity. That’s not to say that we can’t use any other form of resource representation—on the contrary, we could use XHTML or any other form of binary representation, though we let the requirements guide our choices.
  4. URI definition—with resources in place, we need to define the API, which consists of URIs for clients and servers to exchange resources’ representations.

This design process is not static. These are iterative steps that gravitate around resources. Let’s say that during the URI definition step we discover that one of the URI’s responses is not covered in one of the resources we have identified. Then we go back to define a suitable resource. In most cases, however, we find that the resources that we already have cover most of our needs, and we just have to combine existing resources into a meta-resource to take care of the new requirement.

Requirements of sample web service

The RESTful web service we design in this chapter is a social networking web application similar to Twitter.

Throughout this book, we follow an OOD process mixed with an agile philosophy for designing and coding our applications. This means that we create just enough documentation to be useful, but not so much that we spend an inordinate amount of time deciphering it during our implementation phase.

As with any application, we begin by listing the main business requirements, for which we have the following use cases (these are the main functions of our application):

  • A web user creates an account with a username and a password (creating an account means that the user is now registered).
  • Registered users post blog entries to their accounts. We limit messages to 140 characters.
  • Registered and non-registered users view all blog entries.
  • Registered and non-registered users view user profiles.
  • Registered users update their user profiles, for example, users update their password.
  • Registered and non-registered users search for terms in all blog entries.

However simple this example may be, social networking sites work on these same principles: users sign up for accounts to post personal updates or information. Our intention here, though, is not to fully replicate Twitter or to fully create a social networking application. What we are trying to outline is a set of requirements that will test our understanding of RESTful web services design and implementation.

The core value of social networking sites lies in the ability to connect to multiple users who connect with us, and the value is derived from what the connections mean within the community, because of the tendency of users following people with similar interests. For example, the connections between users create targeted distribution networks.

The connections between users create random graphs in the graph theory sense, where nodes are users and edges are connections between users. This is what is referred to as the social graph.

Resource identification

Out of the use cases listed above, we now need to define the service’s resources. From reading the requirements we see that we need users and messages. Users appear in two ways: a single user and a list of users. Additionally, users have the ability to post blog entries in the form of messages of no more than 140 characters. This means that we need resources for a single message and a list of messages. In sum, we identify the following resources:

  1. User
  2. List of users
  3. Message
  4. List of messages

Representation definition

As we discussed in our introduction to RESTful web services, a representation is a temporal mapping of a resource at the time of a request. Furthermore, a representation is transmitted between clients and servers over HTTP. Because of HTTP’s fl exibility, any binary stream can be transferred. Nevertheless, we don’t recommend choosing just any type of binary representation that requires special code or libraries to consume. We recommend using primarily XML and JSON structures, remembering, of course, that the requirements of the problem we’re solving dictate what representation types we must provide.

A well-designed RESTful web service needs to provide multiple resource representations. We can’t assume that only web browsers will be accessing our public APIs or that only the one type of client we identified in our requirement gathering process will use our services.

What are the options available, then?

Again, arriving at the ideal representation format is a matter of the design process. We need to take into account what the service is doing and what clients will be using the resources for. The safest representation format is therefore XML. This is what web services are known for: transferring XML streams over web transport protocols. More important, most programming languages already have libraries available to parse XML streams.

Finally, we need to account for linkability of representations. Linkability of representation means that the web services provide for resource discoverability, such that resources link to other resources (what’s currently being referred to as HATEOS or Hypermedia As The Engine Of State transfer). For example, our URI for a list of users returns a structure of users with each element in the list having a direct URI to each element in the service (a link to a user).

XML representations

From our analysis, we identified two types of resources: users and messages. As part of the heuristics we outlined earlier, we need to define what our representation will look like. The following representations are the structures that we will have to implement when we actually code the web service.

Users

We first define a user representation as follows:

[code lang=”xml”]
<user>
<username></username>
<password></password>
<link></link>
</user>
[/code]

As part of a user resource, we store only a username and a password. The username is unique in the context of our system and is used to uniquely identify each user. The link element, which points back to the web service, is either assigned when the resource is created or a representation is built for transport (for our sample service, we let the backend create the link).

We now define a list of users as follows:

[code lang=”xml”] <users>
<count></count>
<link></link>
<user>
<username></username>
<password></password>
<link></link>
</user>
…
<user>
<username></username>
<password></password>
<link></link>
</user>
</users>[/code]

This XML structure declares a list of users stored in an XML element . We use ellipses or … to show that we can have more than one user in the list.

We can see here the linkability concept at play: with a list of users we can drill down to individual users using the link element’s value.

Messages

We first define a single blog entry or message as follows:

[code lang=”xml”] <message>
<messageID></messageID>
<content></content>
<link></link>
<user>
<username></username>
<password></password>
<link></link>
</user>
</message>[/code]

A message needs a message id, the body of the message (the content element), and the user who posted the message. Note that depending on what we are doing with the message, we don’t pass all the resource’s information back and forth. For example, when we are creating a message at the client layer, we don’t know what the value for messageID is. Therefore, we still need to pass the message structure to the service, but our web service will know that any messageID value needs to be ignored, because, in our case, it will be created by the storage layer.

Finally, we define a list of messages as follows:

[code lang=”xml”] <messages>
<count></count>
<link></link>
<message>
<messageID></messageID>
<content></content>
<link></link>
<user>
<username></username>
<password></password>
<link></link>
</user>
</message>
…
<message>
<messageID></messageID>
<content></content>
<link></link>
<user>
<username></username>
<password></password>
<link></link>
</user>
</message>
</messages>[/code]

This XML structure holds a collection of messages, and each message holds the user who posted the message.

We use the XML representation type for input and output. Input in this case means that we send a resource representation to create and update the resources at the web service layer in the form of an XML object. Output means that a client requests an XML representation of a resource.

JSON representations

We use the same key names for our JSON representation, and we still have only two types of resources: users and messages. Again, these structures are our specification of what we need to return for each request.

Users

We define a user representation as follows:

[code lang=”html”] {"user":{"username":"john", "password":"password", "link":"/users/
john"}}[/code]

And we define a list of users as follows (we use the … characters to show that there is more than one user in the array):

[code lang=”html”] {"users-result":{"count":"6", "users":[{"username":"john",
"password":"password", "link":"/users/john"}, …,{"username":"jane",
"password":"password", "link":"/users/jane"}]}}[/code]

The array for all users as a JSON structure, looks as follows:

[code lang=”html”] "users":[{"username":"john", "password":"password", "link":"/users/
john"}, …,{"username":"jane", "password":"password", "link":"/users/
jane"}][/code]

Once the JSON response has been evaluated with the JavaScript eval() function, similar to what we did in Chapters 2 and 3, we can then access any of the values in the structure. For example, if we need the user name of the first element on the array, we use users-result.users[0].username.

Messages

We now define a message representation as follows:

[code lang=”html”] {"message":{"messageID":"some-id", "content":"some content",
"link":"/messages/some-id", "user":{"user":{"username":"john",
"password":"password", "link":"/users/john"}}}[/code]

And a list of messages as follows:

[code lang=”html”] {"messages-result":{"count":"6", "link":"/messages",
"messages":[{"messageID":"some-id", "content":"some content",
"link":"/messages/some-id", "user":{"username":"john",
"password":"password", "link":"/users/john"}}, …,{"messageID":"someid2",
"content":"some content", "link":"/messages/some-id2",
"user":{"username":"jane", "password":"password", "link":"/users/
jane"}}]}}[/code]

Each message element in the array has a user structure embedded as follows:

[code lang=”html”] {"messageID":"some-id", "content":"some content",
"user":{"username":"john", "password":"password", "link":"/users/
john"}}[/code]

Once the JSON response has been evaluated with the JavaScript eval() function, we can then access the first element on the list with messages-result.messages[0]. content; if we want to get the user name of the user who posted the message, we access the value with messages-result.messages[0].user.username.

Note that during implementation we’ll use JSON representations only as response streams. This means that we won’t use JSON structures to create or update resources at the web service layer. Although we could use XML and JSON to update resources at the service layer, we’ll omit JSON for the sake of brevity.

URI definition

The next step involves the definition of URIs. This is a crucial step, as the URIs define our API and it’s likely that we want to make our web service public.

We strive to make our APIs logical, hierarchical, and as permanent as we can. We must emphasize these three tenets, as we may have many developers depending on the services we make available. Therefore, a good API is one that doesn’t change too often and is unambiguous to use. Furthermore, the idea of RESTful APIs is that we maintain URI uniqueness and reliability of service. (For a complete discussion about this topic, see http://www.w3.org/Provider/Style/URI.)

The first thing we need is a web address. In our case, we assume that we’re using our development machine running on http://localhost:8080/.

It’s important to distinguish between a web service and a web application:
we use web services to implement web applications, and web services can be, and are recommended to be, independent of web applications. What’s more, web applications are meant to be consumed by humans as opposed to web services that are intended for machine consumption.

For example, a RESTful API could live under http://api. restfuljava.com/ and a web application using the API could ive under http://restfuljava.com/. Both the API and the web application should be running on independent hardware for performance reasons, but when we get to implement our sample service we run everything on the same server.

The nomenclature of RESTful URIs falls under the topic of URI templates and the following conventions are widely used. First, for items or identifiers that don’t change, we find the keyword to be part of the actual URI—for instance, we use users to be the URI for a list of all users. Second, we use keys or dynamic keywords to be enclosed in { and }. Applying these conventions, our URI list for users looks as follows:

  • http://localhost:8080/users—with the GET method, this URI returns a list of all users; with the POST method, we create a new user and the payload is a user’s XML representation; we don’t support the PUT method; finally, we don’t support the DELETE method for an entire list of users
  • http://localhost:8080/users/{username}—with the GET method, this URI returns a representation of a user with a unique identifier username; with the PUT method, it updates a user; and, with the DELETE method, it deletes a user.

And for messages, our URI list looks as follows:

  • http://localhost:8080/messages—with the GET method, this URI returns a list of all messages from all users; with the POST method, it creates a new message, with the message’s XML representation as the payload of the request
  • http://localhost:8080/messages/{messageID}—with the GET method, this URI returns a representation for a message with the unique identifier messageID; with the DELETE method, it deletes a message; and we don’t support the POST or PUT methods
  • http://localhost:8080/messages/users/{username}—with the GET method, this URI returns a list of all message for a user with identifier username; no POST, PUT, or DELETE methods are supported

At the time of this writing, the URI Template specification is still under review. For more information, see http://tools.ietf.org/html/draft-gregorio-uritemplate-03.

Executing logic with RESTful URIs

A question arises when designing RESTful web services that has to do with executing code at the server level. Specifically, how do we execute logic if we limit our client/server interactions to only four CRUD-like calls (POST, GET, PUT, and DELETE)? For this we need to introduce URIs that execute logic on the server,remembering that responses must be in the form of resource representations. In other words, we avoid any RPC style calls and concentrate on the resources only.

For our web service, we only offer the ability of searching for a term or a phrase in the blog entries. For example, any user can search for the term “programming” or” software development” using the following URI (note that the URI pattern is arbitrary and you can choose whatever makes sense for the service you are developing):

[code] http://localhost:8080/messages/search/{search_item}[/code]

This URI returns a list of messages that contain the word or words search_item—this is strictly a GET method call and no POST, PUT, or DELETE method is supported.

Using URIs to request representation types

A RESTful web service is one that adheres to all the constraints we outlined in Chapter 1, RESTful Architectures. However, we have encountered APIs that don’t strictly adhere to every constraint. For example, requesting representation types via URIs is something we saw with Twitter’s API. We requested three different types of representations with the URI ttp://twitter.com/statuses/public_timeline. {xml, json, rss}.

We said that this is not technically a RESTful web service request, because we don’t use the communication protocol—HTTP headers—to tell the service what kind of representation to get. Even though this is not a RESTful web service, it still works. Nevertheless, the API may be open to interpretation. For example, what does it mean to send an HTTP GET request to the URI http://twitter.com/statuses/
public_timeline.json with an HTTP Accept header value of application/xml? Do we get a JSON representation or an XML epresentation? A properly designed RESTful web service has to adhere to all REST constraints, and using the protocol to negotiate representations is part of being RESTful.

Creating a properly defined RESTful web service, however, ensures that there are no misunderstandings on how to use such services. For example, setting the HTTP method type to GET with an appropriate Accept header value makes it clear that we are requesting a resource of a specific type. In the end, you, as a developer or software architect, need to make a decision as to which style will benefit your users the most.

Using this representation request style is a design decision that facilitates—it can be argued—the writing of clients. For instance, the majority of public APIs are read only, so using a straight HTTP GET request with the type of representation embedded in the URI is easier than instantiating a full HTTP request and modifying the HTTP header Accept each time. Note that neither is hard to implement; however, with the former, we save a couple of lines of code at the client layer. Again, it’s a matter of choice.

Our sample web service is a canonical application, thus we don’t deviate from any of the constraints. This means that we use the HTTP protocol to request a preferred resource representation and not the URI style described in this section.[/code]

Summary

  • Invoking RESTful Web Service using API in java.net and GSON 
  • Introduction to Spring REST Services
  • RESTEasy Hello World Example

As we’ve seen, the RESTful design process is resource centric. In addition, we have no arbitrary actions executing on the data—we have HTTP method calls that exchange representations using clearly defined URIs. The steps to arrive at a web service that adheres to all REST constraints are similar to traditional web application design. So we can still use all our traditional requirement gathering techniques, but tweak the process to account for proper design of usable URIs and consumable representations.

Now that we have our social networking web service specification defined together with a set of RESTful design principles, the next step is implementation. We have four different REST frameworks in the menu, so in the next chapter we begin with Jersey, which is the reference implementation of the Java API for RESTful Web Services Specification, more commonly known as JAX-RS.

Filed Under: WebServices Tagged With: Book Review, REST

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved