dk.cphbusiness.rest.RestService.java Source code

Java tutorial

Introduction

Here is the source code for dk.cphbusiness.rest.RestService.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dk.cphbusiness.rest;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import dk.cphbusiness.entity.Book;
import dk.cphbusiness.facade.Facade;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;

/**
 * REST Web Service
 *
 * @author sofus
 */
@Path("books")
public class RestService {
    Gson gson;

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of RestService
     */
    public RestService() {
        gson = new GsonBuilder().setPrettyPrinting().setFieldNamingPolicy(FieldNamingPolicy.IDENTITY).create();
    }

    @GET
    @Produces("application/json")
    public String getBooks() {
        return gson.toJson(Facade.getBooks());
    }

    @POST
    @Consumes("application/json")
    public void createBook(String book) {
        Facade.createBook(gson.fromJson(book, Book.class));
    }

    @DELETE
    @Path("{id}")
    @Consumes("application/json")
    public void deleteBook(@PathParam("id") String ISBN) {
        Facade.deleteBook(ISBN);
    }

    @GET
    @Path("{id}")
    @Produces("application/json")
    public String getBook(@PathParam("id") String ISBN) {
        return gson.toJson(Facade.getBook(ISBN));
    }

}