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.blob;
020
021import java.io.ByteArrayInputStream;
022import java.io.File;
023import java.io.IOException;
024import java.io.InputStream;
025
026import org.apache.logging.log4j.LogManager;
027import org.apache.logging.log4j.Logger;
028import org.nuxeo.ecm.core.api.Blob;
029import org.nuxeo.runtime.api.Framework;
030
031/**
032 * Interface for {@link Blob}s created and managed by the {@link BlobManager}.
033 *
034 * @since 7.2
035 */
036public interface ManagedBlob extends Blob {
037
038    /**
039     * Gets the id of the {@link BlobProvider} managing this blob.
040     *
041     * @return the blob provider id
042     */
043    String getProviderId();
044
045    /**
046     * Gets the stored representation of this blob.
047     *
048     * @return the stored representation
049     */
050    String getKey();
051
052    @Override
053    default InputStream getStream() throws IOException {
054        BlobManager blobManager = Framework.getService(BlobManager.class);
055        BlobProvider blobProvider = blobManager.getBlobProvider(this);
056        if (blobProvider == null) {
057            return null;
058        }
059        try {
060            return blobProvider.getStream(this);
061        } catch (IOException e) {
062            // we don't want to crash everything if the remote blob cannot be accessed
063            Logger log = LogManager.getLogger(ManagedBlob.class);
064            log.debug(e, e);
065            log.error("Failed to access file: {}", this::getKey);
066            return new ByteArrayInputStream(new byte[0]);
067        }
068    }
069
070    @Override
071    default File getFile() {
072        BlobManager blobManager = Framework.getService(BlobManager.class);
073        BlobProvider blobProvider = blobManager.getBlobProvider(this);
074        if (blobProvider == null) {
075            return null;
076        }
077        return blobProvider.getFile(this);
078    }
079
080}