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.apache.commons.io.IOUtils;
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<>());
041    }
042
043    public MemoryStore(Map<String, byte[]> store) {
044        this.store = store;
045        this.location = "java:" + System.identityHashCode(this);
046    }
047
048    @Override
049    public boolean exists(String name) {
050        return store.containsKey(name);
051    }
052
053    @Override
054    public byte[] getBytes(String name) {
055        return store.get(name);
056    }
057
058    @Override
059    public InputStream getStream(String name) {
060        byte[] data = store.get(name);
061        return data == null ? null : new ByteArrayInputStream(data);
062    }
063
064    @Override
065    public URL getURL(String name) { // TODO not yet implemented
066        return null;
067    }
068
069    @Override
070    public long lastModified(String name) {
071        return 0;
072    }
073
074    @Override
075    public void put(String name, InputStream data) throws IOException {
076        store.put(name, IOUtils.toByteArray(data));
077    }
078
079    @Override
080    public void put(String name, byte[] data) throws IOException {
081        store.put(name, data);
082    }
083
084    @Override
085    public void remove(String name) {
086        store.remove(name);
087    }
088
089    @Override
090    public String getLocation() {
091        return "java";
092    }
093
094    @Override
095    public String toString() {
096        return getLocation();
097    }
098}