001/*
002 * Copyright 2021 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.migration.handlers.ocfl;
017
018import java.io.IOException;
019import java.io.InputStream;
020
021import io.micrometer.core.instrument.Counter;
022import io.micrometer.core.instrument.Metrics;
023
024/**
025 * An class which tracks the amount of bytes read from an InputStream. As this is used primarily to transfer bytes to
026 * an OutputStream, we consider these 'bytes processed'.
027 *
028 * @author mikejritter
029 */
030public class CountingInputStream extends InputStream {
031
032    private static final Counter byteCounter = Metrics.counter("fcrepo.storage.bytes", "operation", "bytesProcessed");
033
034    private final InputStream inner;
035
036    public CountingInputStream(final InputStream inner) {
037        this.inner = inner;
038    }
039
040    @Override
041    public int read() throws IOException {
042        final var result = inner.read();
043        if (result != -1) {
044            byteCounter.increment(result);
045        }
046
047        return result;
048    }
049
050    @Override
051    public int read(final byte[] b, final int off, final int len) throws IOException {
052        final var result = inner.read(b, off, len);
053        if (result != -1) {
054            byteCounter.increment(result);
055        }
056        return result;
057    }
058}