001/* 002 * ModeShape (http://www.modeshape.org) 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.modeshape.common.util; 017 018import java.io.IOException; 019import java.io.InputStream; 020import java.util.concurrent.atomic.AtomicLong; 021 022/** 023 * An {@link InputStream} implementation that can wrap another input stream and determine the number of bytes read. 024 */ 025public class SizeMeasuringInputStream extends InputStream { 026 private final InputStream stream; 027 private final AtomicLong size; 028 029 public SizeMeasuringInputStream( InputStream stream, 030 AtomicLong size ) { 031 this.stream = stream; 032 this.size = size; 033 } 034 035 @Override 036 public int read() throws IOException { 037 int result = stream.read(); 038 if (result != -1) { 039 size.addAndGet(1); 040 } 041 return result; 042 } 043 044 @Override 045 public int read( byte[] b, 046 int off, 047 int len ) throws IOException { 048 // Read from the stream ... 049 int n = stream.read(b, off, len); 050 if (n != -1) { 051 size.addAndGet(n); 052 } 053 return n; 054 } 055 056 @Override 057 public int read( byte[] b ) throws IOException { 058 int n = stream.read(b); 059 if (n != -1) { 060 size.addAndGet(n); 061 } 062 return n; 063 } 064 065 @Override 066 public synchronized void mark( int readlimit ) { 067 stream.mark(readlimit); 068 } 069 070 @Override 071 public boolean markSupported() { 072 return stream.markSupported(); 073 } 074 075 @Override 076 public int available() throws IOException { 077 return stream.available(); 078 } 079 080 @Override 081 public synchronized void reset() throws IOException { 082 stream.reset(); 083 } 084 085 @Override 086 public void close() throws IOException { 087 stream.close(); 088 } 089}