001/*
002 * (C) Copyright 2006-2008 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu
018 */
019package org.nuxeo.ecm.webengine.loader.store;
020
021import java.io.ByteArrayInputStream;
022import java.io.IOException;
023import java.io.InputStream;
024import java.net.URL;
025import java.util.HashMap;
026import java.util.Map;
027
028import org.nuxeo.common.utils.FileUtils;
029
030/**
031 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
032 */
033public class MemoryStore implements ResourceStore {
034
035    protected final Map<String, byte[]> store;
036
037    protected String location;
038
039    public MemoryStore() {
040        this(new HashMap<String, byte[]>());
041    }
042
043    public MemoryStore(Map<String, byte[]> store) {
044        this.store = store;
045        this.location = "java:" + System.identityHashCode(this);
046    }
047
048    public boolean exists(String name) {
049        return store.containsKey(name);
050    }
051
052    public byte[] getBytes(String name) {
053        return store.get(name);
054    }
055
056    public InputStream getStream(String name) {
057        byte[] data = store.get(name);
058        return data == null ? null : new ByteArrayInputStream(data);
059    }
060
061    public URL getURL(String name) { // TODO not yet implemented
062        return null;
063    }
064
065    public long lastModified(String name) {
066        return 0;
067    }
068
069    public void put(String name, InputStream data) throws IOException {
070        store.put(name, FileUtils.readBytes(data));
071    }
072
073    public void put(String name, byte[] data) throws IOException {
074        store.put(name, data);
075    }
076
077    public void remove(String name) {
078        store.remove(name);
079    }
080
081    public String getLocation() {
082        return "java";
083    }
084
085    @Override
086    public String toString() {
087        return getLocation();
088    }
089}