001/*
002 * (C) Copyright 2011-2014 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.blob.binary;
020
021import java.io.File;
022import java.io.FileInputStream;
023import java.io.IOException;
024import java.io.InputStream;
025
026import org.nuxeo.ecm.core.blob.BlobManager;
027import org.nuxeo.ecm.core.blob.BlobProvider;
028import org.nuxeo.runtime.api.Framework;
029
030/**
031 * Lazy Binary that fetches its remote stream on first access.
032 */
033public class LazyBinary extends Binary {
034
035    private static final long serialVersionUID = 1L;
036
037    // transient to be Serializable
038    protected transient CachingBinaryManager cbm;
039
040    public LazyBinary(String digest, String repoName, CachingBinaryManager cbm) {
041        super(digest, repoName);
042        this.cbm = cbm;
043    }
044
045    // because the class is Serializable, re-acquire the CachingBinaryManager
046    protected CachingBinaryManager getCachingBinaryManager() {
047        if (cbm == null) {
048            if (blobProviderId == null) {
049                throw new UnsupportedOperationException("Cannot find binary manager, no blob provider id");
050            }
051            BlobManager bm = Framework.getService(BlobManager.class);
052            BlobProvider bp = bm.getBlobProvider(blobProviderId);
053            cbm = (CachingBinaryManager) bp.getBinaryManager();
054        }
055        return cbm;
056    }
057
058    @Override
059    public InputStream getStream() throws IOException {
060        File file = getFile();
061        return file == null ? null : new FileInputStream(file);
062    }
063
064    @Override
065    public File getFile() {
066        try {
067            return getCachingBinaryManager().getFile(digest);
068        } catch (IOException e) {
069            throw new RuntimeException(e);
070        }
071    }
072
073}