001/*
002 * (C) Copyright 2006-2011 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 *     Thierry Delprat
018 *     Florent Guillaume
019 */
020
021package org.nuxeo.ecm.core.api.blobholder;
022
023import java.io.IOException;
024import java.io.InputStream;
025import java.util.ArrayList;
026import java.util.Calendar;
027import java.util.List;
028
029import org.apache.commons.codec.digest.DigestUtils;
030import org.nuxeo.ecm.core.api.Blob;
031import org.nuxeo.ecm.core.api.NuxeoException;
032
033/**
034 * Base class for {@link BlobHolder} implementers
035 */
036public abstract class AbstractBlobHolder implements BlobHolder {
037
038    @Override
039    public abstract Blob getBlob();
040
041    @Override
042    public void setBlob(Blob blob) {
043        throw new UnsupportedOperationException();
044    }
045
046    @Override
047    public List<Blob> getBlobs() {
048        List<Blob> blobs = null;
049
050        Blob blob = getBlob();
051        if (blob != null) {
052            blobs = new ArrayList<>();
053            blobs.add(blob);
054        }
055
056        return blobs;
057    }
058
059    protected abstract String getBasePath();
060
061    @Override
062    public String getFilePath() {
063        String path = getBasePath();
064
065        Blob blob = getBlob();
066        if (blob != null) {
067            path = path + "/" + blob.getFilename();
068        }
069
070        return path;
071    }
072
073    @Override
074    public String getHash() {
075
076        Blob blob = getBlob();
077        if (blob != null) {
078            String h = blob.getDigest();
079            if (h == null) {
080                h = getMD5Digest();
081                blob.setDigest(h);
082            }
083            return h;
084        }
085        return "NullBlob";
086    }
087
088    protected String getMD5Digest() {
089        try (InputStream in = getBlob().getStream()) {
090            return DigestUtils.md5Hex(in);
091        } catch (IOException e) {
092            throw new NuxeoException(e);
093        }
094    }
095
096    @Override
097    public abstract Calendar getModificationDate();
098
099}