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 * Output stream that delegates write operations to an underlying stream,
025 * and sends notifications of how many bytes were written via a callback.
026 * @see org.jppf.utils.streams.NotifyingStreamCallback
027 * @see org.jppf.utils.streams.NotifyingOutputStream
028 * @author Laurent Cohen
029 */
030public class NotifyingOutputStream extends OutputStream {
031  /**
032   * The output stream to which operations are delegated.
033   */
034  private final OutputStream delegate;
035  /**
036   * The callback to notify of stream operations.
037   */
038  private final 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 NotifyingOutputStream(final OutputStream delegate, final NotifyingStreamCallback callback) {
046    if (delegate == null) throw new IllegalArgumentException("output 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 void write(final int n) throws IOException {
054    delegate.write(n);
055    callback.bytesNotification(1);
056  }
057
058  @Override
059  public void write(final byte[] b) throws IOException {
060    write(b, 0, b.length);
061  }
062
063  @Override
064  public void write(final byte[] b, final int off, final int len) throws IOException {
065    delegate.write(b, off, len);
066    callback.bytesNotification(len);
067  }
068
069  @Override
070  public void close() throws IOException {
071    delegate.close();
072    super.close();
073  }
074
075  @Override
076  public void flush() throws IOException {
077    delegate.flush();
078  }
079}