Java RESTful Web Services

REST...

...

...

LibraryResource.java

package my.project.rest.library;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
* http://localhost:8080/REST/service/library
* http://localhost:8080/REST/service/library/1
* http://localhost:8080/REST/service/library/count
* http://localhost:8080/REST/service/library/countx
*
*/
@Path("library")
public class LibraryResource {

@Context
private UriInfo uriInfo;

private static HashMap<Integer, Book> books = new HashMap<Integer, Book>();

/** Return the list of all books */
@GET
@Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
public List<Book> getAllBooks() {
List<Book> list = new ArrayList<Book>();
list.addAll(books.values());
return list;
}

/** Return the book with id */
@GET
@Path("{id}")
@Produces({MediaType.TEXT_XML, MediaType.APPLICATION_XML})
public Book getBook(@PathParam("id") String id) {

Book b = books.get(Integer.valueOf(id));

if (b != null) {
return b;
} else {
// throw new RuntimeException("getBook(): Book with id " + id
// + " not found");
return null;
}
}

/** Return number of books as plain text */
@GET
@Path("count")
@Produces(MediaType.TEXT_PLAIN)
public String getCount() {
return String.valueOf(books.size());
}

/** Return number of books as xml */
@GET
@Path("countx")
@Produces(MediaType.TEXT_XML)
public BookCounter getCountX() {
BookCounter c = new BookCounter();
c.setCount(books.size());
return c;
}

/** Create new book */
@PUT
@Consumes(MediaType.APPLICATION_XML)
public Response newBook(JAXBElement<Book> book) {

Book b = book.getValue();

if (!books.containsKey(b.getId())) {
books.put(b.getId(), b);
} else {
b = null;
}

Response res;
if (b == null) {
res = Response.noContent().build();
} else {
res = Response.created(uriInfo.getAbsolutePath()).build();
}

return res;
}

/** Delete a book with id */
@DELETE
@Path("{id}")
public Response deleteBook(@PathParam("id") Integer id) {

Book b = books.remove(id);

Response res;
if (b == null) {
res = Response.notModified("object not found").build();
// throw new RuntimeException("Delete: Book with id " + id + " not found");
} else {
res = Response.ok().build();
}

return res;
}

}

...

...

Book.java

package my.project.rest.library;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Book {

private Integer id;

private String title;

private String author;

private Boolean available;


public Book() {
}

public Book(Integer id, String title, String author, boolean avail) {
this.id = id;
this.title = title;
this.author = author;
this.available = avail;
}


public Integer getId() {
return id;
}

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

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;
}

public Boolean getAvailable() {
return available;
}

public void setAvailable(Boolean available) {
this.available = available;
}

}

BookCounter

package my.project.rest.library;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class BookCounter {

private Integer count;

public Integer getCount() {
return count;
}

public void setCount(Integer count) {
this.count = count;
}

}

...

...

DbMng.java

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RESTT</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>my.project.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
</web-app>

...

rest client

package my.project.rest.library;

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 LibClient {

private ClientConfig config = new DefaultClientConfig();
private Client client = Client.create(config);
private WebResource service = client.resource(getBaseURI());

public static void main(String[] args) {

LibClient client = new LibClient();
client.getAllBooks();
client.getCount();
client.createNewBook(4, "nov naslov", "nov avtor", false);
client.getCountX();
client.getSingleBook(2);
client.deleteBook(1);
client.getAllBooks();
client.getCount();

}

public void getAllBooks() {
System.out.println("=== GET ALL BOOKS ===");
// Get XML
System.out.println("text: " + service.path("library").accept(MediaType.TEXT_XML)
.get(String.class));
// Get XML for application
System.out.println("xml: " + service.path("library").accept(MediaType.APPLICATION_XML).get(String.class));
}

public void getSingleBook(int id) {
System.out.println("=== GET SINGLE BOOK ===");
System.out.println("xml: " + service.path("library").path(""+id).accept(MediaType.APPLICATION_XML).get(String.class));
}

public void getCount() {
System.out.println("=== GET COUNT ===");
System.out.println("text: " + service.path("library").path("count").accept(MediaType.TEXT_PLAIN).get(String.class));
}

public void getCountX() {
System.out.println("=== GET COUNT XML ===");
System.out.println("text: " + service.path("library").path("countx").accept(MediaType.TEXT_XML).get(String.class));
}

public void createNewBook(Integer id, String title, String author, boolean available) {
System.out.println("=== CREATE NEW BOOK ===");
Book book = new Book(id, title, author, available);
ClientResponse response = service.path("library").accept(MediaType.APPLICATION_XML).put(ClientResponse.class, book);
// Return code should be 201 == created resource
System.out.println("http code: " + response.getStatus());
}

public void deleteBook(int id) {
System.out.println("=== DELETE BOOK ===");
service.path("library/"+id).delete();
// Return code should be 200 == ok
}

private URI getBaseURI() {
return UriBuilder.fromUri("http://localhost:8080/REST/service").build();
}

}

...

...

...