com.talis.storage.memory.MemoryStore.java Source code

Java tutorial

Introduction

Here is the source code for com.talis.storage.memory.MemoryStore.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.memory;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;

import com.talis.storage.ItemNotFoundException;
import com.talis.storage.Store;
import com.talis.storage.StoredItem;
import com.talis.storage.SubmittedItem;

public class MemoryStore implements Store {

    private final Map<URI, StoredItem> storage;

    public MemoryStore() {
        storage = new HashMap<URI, StoredItem>();
    }

    @Override
    public synchronized StoredItem read(URI tmbURI) throws IOException, ItemNotFoundException {
        StoredItem stored = storage.get(tmbURI);
        if (null == stored) {
            throw new ItemNotFoundException(tmbURI);
        } else {
            byte[] entity = IOUtils.toByteArray(stored.getEntity());
            StoredItem toStore = copyItem(entity, stored);
            StoredItem toReturn = copyItem(entity, stored);
            storage.put(tmbURI, toStore);
            return toReturn;
        }
    }

    @Override
    public synchronized StoredItem write(URI tmbURI, SubmittedItem submitted) throws IOException {
        byte[] entity = IOUtils.toByteArray(submitted.getEntity());
        String etag = DigestUtils.md5Hex(entity);

        SubmittedItem clone = new SubmittedItem(submitted.getMediaType(), new ByteArrayInputStream(entity),
                submitted.getMetadata());
        StoredItem toStore = new StoredItem(clone, new Date(System.currentTimeMillis()), etag);
        storage.put(tmbURI, toStore);
        return copyItem(entity, toStore);
    }

    @Override
    public synchronized void delete(URI tmbURI) throws IOException {
        storage.remove(tmbURI);
    }

    private StoredItem copyItem(byte[] entity, StoredItem original) {
        SubmittedItem enclosed = new SubmittedItem(original.getMediaType(), new ByteArrayInputStream(entity),
                original.getMetadata());
        return new StoredItem(enclosed, original.getLastModified(), original.getEtag());
    }
}