/*
 * Java Network Programming, Second Edition
 * Merlin Hughes, Michael Shoffner, Derek Hamner
 * Manning Publications Company; ISBN 188477749X
 *
 * http://nitric.com/jnp/
 *
 * Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner;
 * all rights reserved; see license.txt for details.
 */

import java.io.*;
import java.util.*;

public class TeeOutputStream extends OutputStream {
  protected Vector outVector;
  
  public TeeOutputStream (OutputStream out0, OutputStream out1) {
    outVector = new Vector ();
    outVector.addElement (out0);
    outVector.addElement (out1);
  }

  public TeeOutputStream (Enumeration outs) {
    outVector = new Vector ();
    while (outs.hasMoreElements ())
      outVector.addElement (outs.nextElement ());
  }

  public void flush () throws MultiIOException {
    MultiIOException problems =
      new MultiIOException ("Flush exceptions");
    for (int i = 0; i < outVector.size (); ++ i) {
      OutputStream out = (OutputStream) outVector.elementAt (i);
      try {
        out.flush ();
      } catch (IOException ex) {
        problems.addException (new OutputStreamException (out, ex));
      }
    }
    if (problems.hasMoreExceptions ())
      throw problems;
  }

  public void close () throws MultiIOException {
    MultiIOException problems =
      new MultiIOException ("Close exceptions");
    for (int i = 0; i < outVector.size (); ++ i) {
      OutputStream out = (OutputStream) outVector.elementAt (i);
      try {
        out.close ();
      } catch (IOException ex) {
        problems.addException (new OutputStreamException (out, ex));
      }
    }
    if (problems.hasMoreExceptions ())
      throw problems;
  }

  public void write (int datum) throws MultiIOException {
    MultiIOException problems =
      new MultiIOException ("Write exceptions");
    for (int i = 0; i < outVector.size (); ++ i) {
      OutputStream out = (OutputStream) outVector.elementAt (i);
      try {
        out.write (datum);
      } catch (IOException ex) {
        problems.addException (new OutputStreamException (out, ex));
      }
    }
    if (problems.hasMoreExceptions ())
      throw problems;
  }

  public void write (byte[] data, int offset, int length) throws MultiIOException {
    MultiIOException problems =
      new MultiIOException("Write exceptions");
    for (int i = 0; i < outVector.size (); ++ i) {
      OutputStream out = (OutputStream) outVector.elementAt (i);
      try {
        out.write (data, offset, length);
      } catch (IOException ex) {
        problems.addException (new OutputStreamException (out, ex));
      }
    }
    if (problems.hasMoreExceptions ())
      throw problems;
  }
}
