001/*
002 * (C) Copyright 2011-2014 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Florent Guillaume
011 */
012package org.nuxeo.ecm.core.blob.binary;
013
014import java.io.File;
015import java.io.FileInputStream;
016import java.io.IOException;
017import java.io.InputStream;
018
019import org.nuxeo.ecm.core.blob.BlobManager;
020import org.nuxeo.ecm.core.blob.BlobProvider;
021import org.nuxeo.runtime.api.Framework;
022
023/**
024 * Lazy Binary that fetches its remote stream on first access.
025 */
026public class LazyBinary extends Binary {
027
028    private static final long serialVersionUID = 1L;
029
030    protected boolean hasLength;
031
032    // transient to be Serializable
033    protected transient CachingBinaryManager cbm;
034
035    public LazyBinary(String digest, String repoName, CachingBinaryManager cbm) {
036        super(digest, repoName);
037        this.cbm = cbm;
038    }
039
040    // because the class is Serializable, re-acquire the CachingBinaryManager
041    protected CachingBinaryManager getCachingBinaryManager() {
042        if (cbm == null) {
043            if (blobProviderId == null) {
044                throw new UnsupportedOperationException("Cannot find binary manager, no blob provider id");
045            }
046            BlobManager bm = Framework.getService(BlobManager.class);
047            BlobProvider bp = bm.getBlobProvider(blobProviderId);
048            cbm = (CachingBinaryManager) bp.getBinaryManager();
049        }
050        return cbm;
051    }
052
053    @Override
054    public InputStream getStream() throws IOException {
055        File file = getFile();
056        return file == null ? null : new FileInputStream(file);
057    }
058
059    @Override
060    public File getFile() {
061        if (file == null) {
062            try {
063                file = getCachingBinaryManager().getFile(digest);
064            } catch (IOException e) {
065                throw new RuntimeException(e);
066            }
067            if (file != null) {
068                length = file.length();
069                hasLength = true;
070            }
071        }
072        return file;
073    }
074
075    @Override
076    public long getLength() {
077        if (!hasLength) {
078            Long len;
079            try {
080                len = getCachingBinaryManager().getLength(digest);
081            } catch (IOException e) {
082                throw new RuntimeException(e);
083            }
084            length = len == null ? 0 : len.longValue();
085            hasLength = true;
086        }
087        return length;
088    }
089
090}