001/** 002 * Copyright 2014 DuraSpace, Inc. 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 */ 016package org.fcrepo.kernel.impl.utils; 017 018import com.google.common.collect.ImmutableSet; 019import org.apache.commons.io.IOUtils; 020import org.fcrepo.kernel.utils.CacheEntry; 021import org.fcrepo.kernel.utils.ContentDigest; 022import org.fcrepo.kernel.utils.FixityResult; 023import org.slf4j.Logger; 024 025import javax.jcr.RepositoryException; 026import java.io.IOException; 027import java.net.URI; 028import java.security.MessageDigest; 029import java.security.NoSuchAlgorithmException; 030import java.util.Collection; 031 032import static com.google.common.base.Throwables.propagate; 033import static org.apache.commons.io.output.NullOutputStream.NULL_OUTPUT_STREAM; 034import static org.slf4j.LoggerFactory.getLogger; 035 036/** 037 * Cache entry that wraps a binary stream and provides 038 * fixity methods against it 039 * 040 * @author fasseg 041 */ 042public abstract class BasicCacheEntry implements CacheEntry { 043 044 private static final Logger LOGGER = getLogger(BasicCacheEntry.class); 045 046 /** 047 * Calculate the fixity of a CacheEntry by piping it through 048 * a simple fixity-calculating InputStream 049 * 050 * @return the fixity of this cache entry 051 * @throws RepositoryException 052 */ 053 @Override 054 public Collection<FixityResult> checkFixity(final String digest) 055 throws RepositoryException { 056 057 try (FixityInputStream fixityInputStream = new FixityInputStream(this.getInputStream(), 058 MessageDigest.getInstance(digest))) { 059 060 IOUtils.copy(fixityInputStream, NULL_OUTPUT_STREAM); 061 062 final URI calculatedChecksum = ContentDigest.asURI(digest, 063 fixityInputStream.getMessageDigest().digest()); 064 final FixityResult result = 065 new FixityResultImpl(this, 066 fixityInputStream.getByteCount(), 067 calculatedChecksum); 068 069 LOGGER.debug("Got {}", result.toString()); 070 071 return ImmutableSet.of(result); 072 } catch (final IOException e) { 073 LOGGER.debug("Got error closing input stream: {}", e); 074 throw propagate(e); 075 } catch (final NoSuchAlgorithmException e1) { 076 throw propagate(e1); 077 } 078 079 } 080}