001/* 002 * Copyright (c) 2006-2014 Nuxeo SA (http://nuxeo.com/) and others. 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.IOException; 016import java.io.InputStream; 017import java.io.Serializable; 018import java.util.Objects; 019 020import org.nuxeo.ecm.core.api.Blob; 021import org.nuxeo.ecm.core.api.impl.blob.AbstractBlob; 022import org.nuxeo.ecm.core.blob.ManagedBlob; 023 024/** 025 * A {@link Blob} wrapping a {@link Binary} value. 026 */ 027public class BinaryBlob extends AbstractBlob implements ManagedBlob, Serializable { 028 029 private static final long serialVersionUID = 1L; 030 031 protected final Binary binary; 032 033 /** 034 * The key, which is the binary's digest but may in addition be prefixed by a blob provider id. 035 */ 036 protected final String key; 037 038 protected final long length; 039 040 public BinaryBlob(Binary binary, String key, String filename, String mimeType, String encoding, String digest, 041 long length) { 042 this.binary = binary; 043 this.key = key; 044 this.length = length; 045 setFilename(filename); 046 setMimeType(mimeType); 047 setEncoding(encoding); 048 setDigest(digest); 049 } 050 051 @Override 052 public long getLength() { 053 return length; 054 } 055 056 @Override 057 public InputStream getStream() throws IOException { 058 return binary.getStream(); 059 } 060 061 /** 062 * Gets the {@link Binary} attached to this blob. 063 * 064 * @since 5.9.4 065 * @return the binary 066 */ 067 public Binary getBinary() { 068 return binary; 069 } 070 071 @Override 072 public String getDigestAlgorithm() { 073 return Objects.equals(binary.getDigest(), getDigest()) ? binary.getDigestAlgorithm() : null; 074 } 075 076 @Override 077 public String getDigest() { 078 String digest = super.getDigest(); 079 if (digest == null) { 080 return binary.getDigest(); 081 } else { 082 return digest; 083 } 084 } 085 086 @Override 087 public String getKey() { 088 return key; 089 } 090 091 @Override 092 public String getProviderId() { 093 return binary.getBlobProviderId(); 094 } 095 096 @Override 097 public File getFile() { 098 return binary.getFile(); 099 } 100 101 /* 102 * Optimized stream comparison method. 103 */ 104 @Override 105 protected boolean equalsStream(Blob blob) { 106 if (!(blob instanceof BinaryBlob)) { 107 return super.equalsStream(blob); 108 } 109 BinaryBlob other = (BinaryBlob) blob; 110 if (binary == null) { 111 return other.binary == null; 112 } else if (other.binary == null) { 113 return false; 114 } else { 115 return binary.getDigest().equals(other.binary.getDigest()); 116 } 117 } 118 119}