001/****************************************************************
002 * Licensed to the Apache Software Foundation (ASF) under one   *
003 * or more contributor license agreements.  See the NOTICE file *
004 * distributed with this work for additional information        *
005 * regarding copyright ownership.  The ASF licenses this file   *
006 * to you under the Apache License, Version 2.0 (the            *
007 * "License"); you may not use this file except in compliance   *
008 * 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,   *
013 * software distributed under the License is distributed on an  *
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
015 * KIND, either express or implied.  See the License for the    *
016 * specific language governing permissions and limitations      *
017 * under the License.                                           *
018 ****************************************************************/
019
020
021package org.apache.james.mime4j.io;
022
023import java.io.FilterInputStream;
024import java.io.InputStream;
025import java.io.IOException;
026
027public class PositionInputStream extends FilterInputStream {
028
029    protected long position = 0;
030    private long markedPosition = 0;
031
032    public PositionInputStream(InputStream inputStream) {
033        super(inputStream);
034    }
035
036    public long getPosition() {
037        return position;
038    }
039
040    @Override
041    public int available() throws IOException {
042        return in.available();
043    }
044
045    @Override
046    public int read() throws IOException {
047        int b = in.read();
048        if (b != -1)
049            position++;
050        return b;
051    }
052
053    @Override
054    public void close() throws IOException {
055        in.close();
056    }
057
058    @Override
059    public void reset() throws IOException {
060        in.reset();
061        position = markedPosition;
062    }
063
064    @Override
065    public boolean markSupported() {
066        return in.markSupported();
067    }
068
069    @Override
070    public void mark(int readlimit) {
071        in.mark(readlimit);
072        markedPosition = position;
073    }
074
075    @Override
076    public long skip(long n) throws IOException {
077        final long c = in.skip(n);
078        if (c > 0)
079            position += c;
080        return c;
081    }
082
083    @Override
084    public int read(byte b[], int off, int len) throws IOException {
085        final int c = in.read(b, off, len);
086        if (c > 0)
087            position += c;
088        return c;
089    }
090
091}