com.talis.storage.http.ItemResource.java Source code

Java tutorial

Introduction

Here is the source code for com.talis.storage.http.ItemResource.java

Source

/*
 * Copyright 2010 Talis Information Ltd
 * 
 *    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.talis.storage.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.talis.storage.InvalidKeyException;
import com.talis.storage.ItemFactory;
import com.talis.storage.ItemNotFoundException;
import com.talis.storage.Store;
import com.talis.storage.StoredItem;
import com.talis.storage.SubmittedItem;

@Path("/items/{id: .+}")
public class ItemResource {

    private final Store myStore;
    private final ItemFactory itemFactory;
    private static final transient Logger LOG = LoggerFactory.getLogger(ItemResource.class);

    @Inject
    public ItemResource(Store store, ItemFactory itemFactory) {
        myStore = store;
        this.itemFactory = itemFactory;
    }

    @GET
    public Response get(@PathParam("id") final String id) {
        URI tmbURI = makeInternalURI(id);
        try {
            final StoredItem item = myStore.read(tmbURI);
            LOG.debug(String.format("StoredThing has media type : %s", item.getMediaType()));

            StreamingOutput output = new StreamingOutput() {
                @Override
                public void write(OutputStream output) throws IOException {
                    try {
                        IOUtils.copyLarge(item.getEntity(), output);
                    } catch (Exception e) {
                        LOG.error("Error fetching chunk", e);
                    } finally {
                        LOG.info("Closing output");
                        output.flush();
                        output.close();
                    }
                }
            };

            return Response.ok(output, item.getMediaType()).header("etag", item.getEtag())
                    .header("last-modified", item.getLastModified()).header("cache-control", "max-age=7200")
                    .build();
        } catch (InvalidKeyException e) {
            throw new WebApplicationException(e, 400);
        } catch (IOException e) {
            throw new WebApplicationException(e, 500);
        } catch (ItemNotFoundException e) {
            throw new WebApplicationException(e, 404);
        }
    }

    @PUT
    @Consumes("*/*")
    public Response put(@PathParam("id") final String id, @Context HttpHeaders headers, InputStream entityStream) {

        URI tmbURI = makeInternalURI(id);
        LOG.debug(String.format("PUT request to URI : %s", tmbURI.toString()));

        MediaType mediaType = headers.getMediaType();
        try {
            SubmittedItem submitted = itemFactory.newSubmittedItem(mediaType, entityStream);
            myStore.write(tmbURI, submitted);
        } catch (InvalidKeyException e) {
            throw new WebApplicationException(e, 400);
        } catch (IOException e) {
            throw new WebApplicationException(e, 500);
        }

        return Response.created(tmbURI).build();
    }

    @DELETE
    public Response delete(@PathParam("id") String id) {

        URI tmbURI = makeInternalURI(id);
        LOG.debug(String.format("DELETE request to URI :  %s", tmbURI.toString()));

        try {
            myStore.delete(tmbURI);
        } catch (InvalidKeyException e) {
            throw new WebApplicationException(e, 400);
        } catch (IOException e) {
            throw new WebApplicationException(e, 500);
        }

        return Response.noContent().build();
    }

    public URI makeInternalURI(String id) {
        return URI.create(String.format("http://%s/items/%s", StorageServer.SERVICE_HOST, id));
    }

}