001/*
002 * JPPF.
003 * Copyright (C) 2005-2016 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  /**
033   * The output stream to which operations are delegated.
034   */
035  private final OutputStream delegate;
036  /**
037   * The callback to notify of stream operations.
038   */
039  private final NotifyingStreamCallback callback;
040
041  /**
042   * Initialize this stream with the specified input stream.
043   * @param delegate the input stream to which operations are delegated.
044   * @param callback the callback to notify of stream operations.
045   */
046  public NotifyingOutputStream(final OutputStream delegate, final NotifyingStreamCallback callback)
047  {
048    if (delegate == null) throw new IllegalArgumentException("output stream cannot be null");
049    if (callback == null) throw new IllegalArgumentException("the callback cannot be null");
050    this.delegate = delegate;
051    this.callback = callback;
052  }
053
054  @Override
055  public void write(final int n) throws IOException
056  {
057    delegate.write(n);
058    callback.bytesNotification(1);
059  }
060
061  @Override
062  public void write(final byte[] b) throws IOException
063  {
064    write(b, 0, b.length);
065  }
066
067  @Override
068  public void write(final byte[] b, final int off, final int len) throws IOException
069  {
070    delegate.write(b, off, len);
071    callback.bytesNotification(len);
072  }
073
074  @Override
075  public void close() throws IOException
076  {
077    delegate.close();
078    super.close();
079  }
080
081  @Override
082  public void flush() throws IOException
083  {
084    delegate.flush();
085  }
086}