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