001/* 002 * Copyright 2015 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.modeshape.utils; 017 018import org.fcrepo.kernel.api.exception.RepositoryRuntimeException; 019import org.fcrepo.kernel.api.utils.CacheEntry; 020import org.fcrepo.kernel.api.utils.ContentDigest; 021import org.fcrepo.kernel.api.utils.FixityResult; 022 023import org.slf4j.Logger; 024 025import java.io.IOException; 026import java.net.URI; 027import java.security.MessageDigest; 028import java.security.NoSuchAlgorithmException; 029import java.util.Collection; 030 031import static java.util.Arrays.asList; 032import static org.slf4j.LoggerFactory.getLogger; 033 034/** 035 * Cache entry that wraps a binary stream and provides 036 * fixity methods against it 037 * 038 * @author fasseg 039 */ 040public abstract class BasicCacheEntry implements CacheEntry { 041 042 public static final int DEV_NULL_BUFFER_SIZE = 4096; 043 044 private static final byte[] devNull = new byte[DEV_NULL_BUFFER_SIZE]; 045 046 private static final Logger LOGGER = getLogger(BasicCacheEntry.class); 047 048 /** 049 * Calculate the fixity of a CacheEntry by piping it through 050 * a simple fixity-calculating InputStream 051 * 052 * @param digest the digest 053 * @return the fixity of this cache entry 054 */ 055 @Override 056 public Collection<FixityResult> checkFixity(final String digest) { 057 058 try (FixityInputStream fixityInputStream = new FixityInputStream(this.getInputStream(), 059 MessageDigest.getInstance(digest))) { 060 // exhaust our source 061 while (fixityInputStream.read(devNull) != -1) { } 062 063 final URI calculatedChecksum = ContentDigest.asURI(digest, 064 fixityInputStream.getMessageDigest().digest()); 065 final FixityResult result = 066 new FixityResultImpl(this, 067 fixityInputStream.getByteCount(), 068 calculatedChecksum); 069 070 LOGGER.debug("Got {}", result.toString()); 071 072 return asList(result); 073 } catch (final IOException e) { 074 LOGGER.debug("Got error closing input stream: {}", e); 075 throw new RepositoryRuntimeException(e); 076 } catch (final NoSuchAlgorithmException e1) { 077 throw new RepositoryRuntimeException(e1); 078 } 079 } 080}