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

Java tutorial

Introduction

Here is the source code for com.github.carlomicieli.rest.resources.RollingStocksResource.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 static com.github.carlomicieli.rest.representations.RollingStocksArrayRepresentation.createArray;

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.Era;
import com.github.carlomicieli.entities.RollingStock;
import com.github.carlomicieli.rest.representations.RollingStockRepresentation;
import com.github.carlomicieli.services.RollingStockService;
import com.sun.jersey.api.spring.Autowire;

@Autowire
@Scope("request")
@Path("/rollingstocks")
public class RollingStocksResource {
    private static final Logger log = LoggerFactory.getLogger("rest");

    private @Inject RollingStockService rsService;

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

    /**
     * Gets the list of rolling stocks representation.
     * @return the list of rolling stocks.
     */
    @GET
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response getRollingStocks() {
        log.info("GET /rollingstocks");

        try {
            final RollingStockRepresentation[] rollingStocks = createArray(rsService.getAllRollingStocks());

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

    @GET
    @Path("/{id}")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response get(@PathParam("id") long id) {
        log.info("GET /rollingstocks/{}", id);

        try {
            final RollingStockRepresentation rs = new RollingStockRepresentation(rsService.getRollingStock(id));
            return Response.ok(rs).tag(rs.tag()).cacheControl(getCacheControl()).build();
        } catch (DataAccessException ex) {
            log.error(ex.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }

    @GET
    @Path("/era/{era}")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response getByEra(@PathParam("era") String era) {
        log.info("GET /rollingstocks/era/{}", era);

        try {
            Era e = Enum.valueOf(Era.class, era);

            final RollingStockRepresentation[] rollingStocks = createArray(rsService.getAllRollingStocks(e));

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

    @GET
    @Path("/scale/{scale}")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public void getByScale(@PathParam("scale") String scale) {
        log.info("GET /rollingstocks/scale/{}", scale);
    }

    @GET
    @Path("/railway/{railway}")
    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public void getByRailway(@PathParam("railway") String railway) {
        log.info("GET /rollingstocks/railway/{}", railway);
    }

    @PUT
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response put(RollingStockRepresentation rsRep) {
        log.info("PUT /rollingstocks");

        final RollingStock rs = rsRep.getInner();

        try {
            rsService.save(rs);

            // the response contains the ETag for the resource just created.
            return Response.noContent().tag(rsRep.tag()).build();
        } catch (RuntimeException ex) {
            log.error(ex.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }

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

    @POST
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public Response post(RollingStockRepresentation rsRep) {
        log.info("POST /rollingstocks");

        final RollingStock rs = rsRep.getInner();

        try {
            long id = rsService.create(rs);

            // the response contains the ETag for the resource just created.
            return Response.created(URI.create(Long.toString(id))).tag(rsRep.tag()).build();
        } catch (RuntimeException 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 RollingStockRepresentation(formValues));
    }

    @DELETE
    @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
    public void delete(RollingStockRepresentation rsRep) {
        delete(rsRep.getId());
    }

    @DELETE
    @Path("/{rsId}")
    public void delete(@PathParam("rsId") long rsId) {
        log.info("DELETE /rollingstocks/{}", rsId);

        final RollingStock rs = new RollingStock(rsId);

        try {
            rsService.save(rs);
        } catch (RuntimeException ex) {
            log.error(ex.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }
    }
}