001/*
002 * (C) Copyright 2006-2008 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 *     Nuxeo - initial API and implementation
018 *
019 * $Id$
020 *
021 */
022package org.nuxeo.ecm.platform.pictures.tiles.api.imageresource;
023
024import java.io.IOException;
025import java.io.InputStream;
026import java.util.Calendar;
027
028import org.apache.commons.codec.digest.DigestUtils;
029import org.apache.commons.io.IOUtils;
030import org.nuxeo.ecm.core.api.Blob;
031
032/**
033 * Blob based implementation of the ImageResource Because ImageResource will be cached this Implementation is not
034 * optimal (Blob digest is not compulsory and the modification date is not set).
035 * <p>
036 * This implementation is mainly used for unit testing.
037 *
038 * @author tiry
039 */
040public class BlobResource implements ImageResource {
041
042    private static final long serialVersionUID = 1L;
043
044    protected Blob blob;
045
046    protected String hash;
047
048    protected Calendar modified;
049
050    public BlobResource(Blob blob) {
051        this.blob = blob;
052        if (blob.getDigest() != null) {
053            hash = blob.getDigest();
054        } else {
055            hash = getMD5Digest();
056        }
057
058        modified = Calendar.getInstance();
059    }
060
061    public Blob getBlob() {
062        return blob;
063    }
064
065    public String getHash() {
066        return hash;
067    }
068
069    public Calendar getModificationDate() {
070        return modified;
071    }
072
073    private String getMD5Digest() {
074        try (InputStream in = blob.getStream()) {
075            return DigestUtils.md5Hex(in);
076        } catch (IOException e) {
077            return blob.hashCode() + "fakeHash";
078        }
079    }
080
081}