com.github.carlomicieli.rest.resources.RailwaysResource.java Source code

Java tutorial

Introduction

Here is the source code for com.github.carlomicieli.rest.resources.RailwaysResource.java

Source

/*
 * Copyright 2012 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.github.carlomicieli.rest.resources;

import java.net.URI;

import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
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.WebApplicationException;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataAccessException;

import com.github.carlomicieli.entities.Railway;
import com.github.carlomicieli.rest.representations.RailwayRepresentation;
import com.github.carlomicieli.services.RailwayService;
import com.sun.jersey.api.spring.Autowire;

import static com.github.carlomicieli.rest.representations.RailwaysArrayRepresentation.*;

/**
 * 
 * @author Carlo Micieli
 *
 */
@Autowire
@Scope("request")
@Path("/railways")
public class RailwaysResource {
    private static final Logger log = LoggerFactory.getLogger("rest");

    private @Inject RailwayService railwayService;

    private CacheControl getCacheControl() {
        CacheControl cache = new CacheControl();
        cache.setMaxAge(10);
        cache.setPrivate(true);
        return cache;
    }

    /**
     * Returns the list of all railway.
     * <p>
     * <code>GET /railways</code>
     * </p>
     * 
     * @return the list of brands.
     */
    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response getRailways() {
        log.info("GET /railways");

        try {
            final RailwayRepresentation[] railways = createArray(railwayService.getAllRailways());

            return Response.ok(railways).cacheControl(getCacheControl()).build();
        } catch (DataAccessException ex) {
            log.error(ex.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Returns a railway resource.
     * <p>
     * <code>GET /railways/{railwayId}</code>
     * </p>
     * 
     * @param railwayId the railway unique id.
     * @return the railway resource.
     */
    @GET
    @Path("/{brandId}")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response getBrand(@PathParam("railwayId") long railwayId) {
        log.info("GET /railways/{}", railwayId);

        try {
            final RailwayRepresentation railway = new RailwayRepresentation(railwayService.getRailway(railwayId));
            return Response.ok(railway).tag(railway.tag()).cacheControl(getCacheControl()).build();
        } catch (DataAccessException ex) {
            log.error(ex.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }

    @POST
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response post(MultivaluedMap<String, String> formValues) {
        return post(new RailwayRepresentation(formValues));
    }

    @POST
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response post(RailwayRepresentation railwayRep) {
        log.info("POST /railways");

        final Railway railway = railwayRep.getInner();

        try {
            long id = railwayService.create(railway);

            // the response contains the ETag for the resource just created.
            return Response.created(URI.create(Long.toString(id))).tag(railwayRep.tag()).build();
        } catch (RuntimeException ex) {
            log.error(ex.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * Update the railway resource.
     * <p>
     * <code>PUT /railways</code>
     * </p>
     * 
     * @param formValues the brand representation.
     * @return HTTP response.
     */
    @PUT
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response put(MultivaluedMap<String, String> formValues) {
        return put(new RailwayRepresentation(formValues));
    }

    /**
     * Update the brand resource.
     * <p>
     * <code>PUT /railways</code>
     * </p>
     * 
     * @param brandRep the brand representation.
     * @return HTTP response.
     */
    @PUT
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response put(RailwayRepresentation railwayRep) {
        log.info("PUT /railways");

        final Railway railway = railwayRep.getInner();

        try {
            railwayService.save(railway);

            return Response.noContent().build();
        } catch (RuntimeException ex) {
            log.error(ex.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 
     * @param railwayId
     */
    @DELETE
    @Path("/{railwayId}")
    public void delete(@PathParam("railwayId") long railwayId) {
        log.info("DELETE /railways/{}", railwayId);

        try {
            railwayService.remove(new Railway(railwayId));
        } catch (RuntimeException ex) {
            log.error(ex.getMessage());
            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
        }
    }

    /**
     * 
     * @param railwayRep
     */
    @DELETE
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public void delete(RailwayRepresentation railwayRep) {
        delete(railwayRep.getId());
    }
}