001/* 002 * (C) Copyright 2015 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 * Florent Guillaume 018 */ 019package org.nuxeo.ecm.core; 020 021import java.io.ByteArrayInputStream; 022import java.io.IOException; 023import java.io.InputStream; 024import java.util.HashMap; 025import java.util.Map; 026import java.util.concurrent.atomic.AtomicLong; 027 028import org.apache.commons.io.IOUtils; 029import org.nuxeo.ecm.core.api.Blob; 030import org.nuxeo.ecm.core.blob.AbstractBlobProvider; 031import org.nuxeo.ecm.core.blob.BlobInfo; 032import org.nuxeo.ecm.core.blob.SimpleManagedBlob; 033 034/** 035 * Dummy storage in memory. 036 */ 037public class DummyBlobProvider extends AbstractBlobProvider { 038 039 protected Map<String, byte[]> blobs; 040 041 protected AtomicLong counter; 042 043 @Override 044 public void initialize(String blobProviderId, Map<String, String> properties) throws IOException { 045 super.initialize(blobProviderId, properties); 046 blobs = new HashMap<>(); 047 counter = new AtomicLong(); 048 } 049 050 @Override 051 public void close() { 052 blobs.clear(); 053 } 054 055 @Override 056 public Blob readBlob(BlobInfo blobInfo) { 057 return new SimpleManagedBlob(blobInfo) { 058 private static final long serialVersionUID = 1L; 059 060 @Override 061 public InputStream getStream() throws IOException { 062 int colon = key.indexOf(':'); 063 String k = colon < 0 ? key : key.substring(colon + 1); 064 byte[] bytes = blobs.get(k); 065 return new ByteArrayInputStream(bytes); 066 } 067 }; 068 } 069 070 @Override 071 public String writeBlob(Blob blob) throws IOException { 072 byte[] bytes; 073 try (InputStream in = blob.getStream()) { 074 bytes = IOUtils.toByteArray(in); 075 } 076 String k = String.valueOf(counter.incrementAndGet()); 077 blobs.put(k, bytes); 078 return k; 079 } 080 081}