001/*
002 * JPPF.
003 * Copyright (C) 2005-2018 JPPF Team.
004 * http://www.jppf.org
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 */
018
019package org.jppf.utils.streams;
020
021import java.io.*;
022
023/**
024 * Input stream that delegates read and skip operations to an underlying stream,
025 * and sends notifications of how many bytes were read or skipped via a callback.
026 * @see org.jppf.utils.streams.NotifyingStreamCallback
027 * @see org.jppf.utils.streams.NotifyingOutputStream
028 * @author Laurent Cohen
029 */
030public class NotifyingInputStream extends InputStream {
031  /**
032   * The input stream to which operations are delegated.
033   */
034  private InputStream delegate;
035  /**
036   * The callback to notify of stream operations.
037   */
038  private NotifyingStreamCallback callback;
039
040  /**
041   * Initialize this stream with the specified input stream.
042   * @param delegate the input stream to which operations are delegated.
043   * @param callback the callback to notify of stream operations.
044   */
045  public NotifyingInputStream(final InputStream delegate, final NotifyingStreamCallback callback) {
046    if (delegate == null) throw new IllegalArgumentException("input stream cannot be null");
047    if (callback == null) throw new IllegalArgumentException("the callback cannot be null");
048    this.delegate = delegate;
049    this.callback = callback;
050  }
051
052  @Override
053  public int read() throws IOException {
054    final int n = delegate.read();
055    if (n >= 0) callback.bytesNotification(1);
056    return n;
057  }
058
059  @Override
060  public int read(final byte[] b) throws IOException {
061    return read(b, 0, b.length);
062  }
063
064  @Override
065  public int read(final byte[] b, final int off, final int len) throws IOException {
066    final int n = delegate.read(b, off, len);
067    if (n >= 0) callback.bytesNotification(n);
068    return n;
069  }
070
071  @Override
072  public long skip(final long n) throws IOException {
073    final long l = delegate.skip(n);
074    if (l >= 0) callback.bytesNotification(l);
075    return l;
076  }
077
078  @Override
079  public void close() throws IOException {
080    delegate.close();
081    super.close();
082  }
083}