001/**
002 * Java Web Archive Toolkit - Software to read and validate ARC, WARC
003 * and GZip files. (http://jwat.org/)
004 * Copyright 2011-2012 Netarkivet.dk (http://netarkivet.dk/)
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * 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.jwat.common;
019
020import java.io.IOException;
021import java.io.InputStream;
022import java.security.DigestInputStream;
023import java.security.MessageDigest;
024
025/**
026 * The standard <code>DigestInputStream</code> does not update the digest
027 * when performing a skip operation. Since this is completely useless in
028 * most situations, the following implementation remedies this.
029 *
030 * @author nicl
031 */
032public class DigestInputStreamNoSkip extends DigestInputStream {
033
034    /** Buffer size to use when read skipping. */
035    public static final int SKIP_READ_BUFFER_SIZE = 8192;
036
037    /** Read buffer used by the skip method. */
038    protected byte[] skip_read_buffer = new byte[SKIP_READ_BUFFER_SIZE];
039
040    /**
041     * Construct a <code>DigestInputStream</code> with the skip method
042     * overridden.
043     * @param stream input stream to digest
044     * @param digest digest implementation to use
045     */
046    public DigestInputStreamNoSkip(InputStream stream, MessageDigest digest) {
047        super(stream, digest);
048    }
049
050    @Override
051    public boolean markSupported() {
052        return false;
053    }
054
055    @Override
056    public synchronized void mark(int readlimit) {
057    }
058
059    @Override
060    public synchronized void reset() throws IOException {
061        throw new UnsupportedOperationException();
062    }
063
064    @Override
065    public long skip(long n) throws IOException {
066        long remaining = n;
067        long skipped = 0;
068        long readLast = 0;
069        while (remaining > 0 && readLast != -1) {
070            remaining -= readLast;
071            skipped += readLast;
072            readLast = read(skip_read_buffer, 0, (int) Math.min(remaining,
073                                                      SKIP_READ_BUFFER_SIZE));
074        }
075        return skipped;
076    }
077
078}