001/* 002 * Licensed to DuraSpace under one or more contributor license agreements. 003 * See the NOTICE file distributed with this work for additional information 004 * regarding copyright ownership. 005 * 006 * DuraSpace licenses this file to you under the Apache License, 007 * Version 2.0 (the "License"); you may not use this file except in 008 * compliance with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.fcrepo.kernel.modeshape.utils; 019 020import org.fcrepo.kernel.api.exception.RepositoryRuntimeException; 021import org.fcrepo.kernel.api.utils.CacheEntry; 022import org.fcrepo.kernel.api.utils.ContentDigest; 023import org.fcrepo.kernel.api.utils.FixityResult; 024 025import org.slf4j.Logger; 026 027import java.io.IOException; 028import java.net.URI; 029import java.security.MessageDigest; 030import java.security.NoSuchAlgorithmException; 031import java.util.Collection; 032 033import static java.util.Arrays.asList; 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 public static final int DEV_NULL_BUFFER_SIZE = 4096; 045 046 private static final byte[] devNull = new byte[DEV_NULL_BUFFER_SIZE]; 047 048 private static final Logger LOGGER = getLogger(BasicCacheEntry.class); 049 050 /** 051 * Calculate the fixity of a CacheEntry by piping it through 052 * a simple fixity-calculating InputStream 053 * 054 * @param digest the digest 055 * @return the fixity of this cache entry 056 */ 057 @Override 058 public Collection<FixityResult> checkFixity(final String digest) { 059 060 try (FixityInputStream fixityInputStream = new FixityInputStream(this.getInputStream(), 061 MessageDigest.getInstance(digest))) { 062 // exhaust our source 063 while (fixityInputStream.read(devNull) != -1) { } 064 065 final URI calculatedChecksum = ContentDigest.asURI(digest, 066 fixityInputStream.getMessageDigest().digest()); 067 final FixityResult result = 068 new FixityResultImpl(this, 069 fixityInputStream.getByteCount(), 070 calculatedChecksum); 071 072 LOGGER.debug("Got {}", result.toString()); 073 074 return asList(result); 075 } catch (final IOException e) { 076 LOGGER.debug("Got error closing input stream: {}", e); 077 throw new RepositoryRuntimeException(e); 078 } catch (final NoSuchAlgorithmException e1) { 079 throw new RepositoryRuntimeException(e1); 080 } 081 } 082}