Language Translator

Showing posts with label RESTful WebService Example. Show all posts
Showing posts with label RESTful WebService Example. Show all posts

RESTFUL WEBSERVICE CODE


package tutorials.jersey;

import java.util.List;

/**
*
* @author Java Program and Codes
* A model class for this very simple Jersey RESt example.
*
*/
public class Shoe {

/**
* In memory list. In a real world example this might
* be backed by a database or such.
*/
public static List SHOES_LIST = new ArrayList();

public static Shoe getShoe(int id) {
return SHOES_LIST.get(id);
}

public static void addShoe(String model, String category) {
SHOES_LIST.add(new Shoe(SHOES_LIST.size(), model, category));
}

/**
* Create some data
*/
static {
SHOES_LIST.add(new Shoe(1,"Caterpillar","Working"));
SHOES_LIST.add(new Shoe(2,"Prada","Classy"));
}

private int id;
private String model;
private String category;

public Shoe(int id, String model, String category) {
uper();
this.id = id;
this.model = model;
his.category = category;
}

public String toJson() {
String result = "{ 'id' : " + this.id + " , ";
result += " 'model' : " + this.model + " , ";
result += "'category' : " + this.category + " }";
return result;
}

public int getId() {
return id;
}

public String getModel() {
return model;
}

public String getCategory() {
return category;
}



REST service code :


package tutorials.jersey;

import javax.ws.rs.ConsumeMime;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.ProduceMime;
import javax.ws.rs.UriParam;
import javax.ws.rs.UriTemplate;
import javax.ws.rs.WebApplicationException;
import com.sun.ws.rest.api.representation.FormURLEncodedProperties;

/**
*
* @author Java programs and codes

*Shoe service for the simple jersey tutorial.
*Demonstrate the use of Uri template, overriding some
*urls with different HTTP verbs, using the
*WebApplicationException in
*a HTTP compliant way, using different produced Mime types.
*/

@UriTemplate("/shoe")
public class ShoeService {

@HttpMethod("GET")
@ProduceMime("text/html")
public String listShoes() {
String result = "";

result += "";
for (Shoe shoe : Shoe.SHOES_LIST) {
result += "";
result += "";
result += "";
}
result += "

" + shoe.getId() + "" + shoe.getModel() + "" + shoe.getCategory() + "
";
return result;
}

@HttpMethod("GET")
@UriTemplate("/{id}")
@ProduceMime("text/json")
public String listShoe(@UriParam("id")
String idString) {
int id = 0;
try {
id = Integer.parseInt(idString);
}
catch (NumberFormatException e) {
throw new WebApplicationException(405);
}
try {
return Shoe.getShoe(id).toJson();
}
catch (IndexOutOfBoundsException e) {
throw new WebApplicationException(404);
}
}

@HttpMethod("GET")
@UriTemplate("/new")
@ProduceMime("text/html")
public String formForShoe() {
String result = "";
result += "

";
result += "Model :

";
result += "Category :
";
result += "
";
return result;
}


@HttpMethod("POST")
@ProduceMime("text/plain")
@ConsumeMime("application/x-www-form-urlencoded")
public String addShoe(FormURLEncodedProperties formData) {
String model = formData.get("model");
String category = formData.get("category");
if ((model == null) || (category == null)) {
throw new WebApplicationException(405);
}
else {
Shoe.addShoe(model, category);
}
return "Added OK";
}

}




The annotation @UriTemplate("/shoe") on top of the service class means any url for this service starts with /shoe. That's the basic resource url. Now both method listShoes and
addShoe define no UriTemplate which means they get executed directly at the root of the class url, /shoe. It is fine to have more than one method on this url since they use different HTTP verbs, defined by the @HttpMethod annotation.

According to the REST philosophy it makes sense that the /shoe resource with no additional parameter serves a list of all shoes available.
It makes also sense that a POST on this resource url creates a new resource. The addShoe method demonstrates how, by having the annotation @ConsumeMime("application/x-www-form-urlencoded") on top of the method, you get
Jersey to inject the form data for free: FormURLEncodedProperties formData.

Method listShoe demonstrate the use of a parameter parsed from the url. By defining {id} using bracket in the url template, then annotating method parameter String idString as coming from the url template parameter of name "id"
, we have jersey pass, it to the method for free.

All methods demonstrate the use of different MIME types for the output, especially a single shoe is served as its json view in the example. We could have different methods using the same url template and HTTP verb as soon as they serve different MIME type.

Finally we demonstrate how easily you can deal with HTTP errors. Jersey's WebApplicationException(int code) will have your servlet container respond with an HTTP error of the code passed as a parameter. It is also possible to define custom error messages, making it very easy to extend this exception with your own custom exceptions.
We respect REST philosophy by having wrong parameters (for instance in listShoe when id is not a number)
being a 405 error, while a shoe that does not exist (in listShoe too) corresponds to a 404 resource not found error.

WebResource class:



package tutorials.jersey;

import com.sun.ws.rest.api.core.DefaultResourceConfig;

/**
*
* @author

* WebResource definition for the Shoe Service example.
*/
public class WebResources extends DefaultResourceConfig {

public WebResources() {
getResourceClasses().add(.jersey.ShoeService.class);
// getResourceClasses().add(OtherClass.class);
// can add any number of Web services here.
}
}



This class serves as a configuration class to have Jersey know about all your services classes. Just add them all once at a time.

Web.xml





Jersey

Jersey
com.sun.ws.rest.impl.container.servlet.ServletAdaptor

webresourceclass
tutorials.jersey.WebResources

1


Jersey
/*