001/**
002 * Logback: the reliable, generic, fast and flexible logging framework.
003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
004 *
005 * This program and the accompanying materials are dual-licensed under
006 * either the terms of the Eclipse Public License v1.0 as published by
007 * the Eclipse Foundation
008 *
009 *   or (per the licensee's choosing)
010 *
011 * under the terms of the GNU Lesser General Public License version 2.1
012 * as published by the Free Software Foundation.
013 */
014package ch.qos.logback.core.testUtil;
015
016import java.io.ByteArrayOutputStream;
017import java.io.IOException;
018import java.io.OutputStream;
019import java.io.PrintStream;
020
021/**
022 * This stream writes its output to the target PrintStream supplied to its
023 * constructor. At the same time, all the available bytes are collected and
024 * returned by the toString() method.
025 * 
026 * @author Ceki Gulcu
027 */
028public class TeeOutputStream extends OutputStream {
029
030    final PrintStream targetPS;
031    public final ByteArrayOutputStream baos = new ByteArrayOutputStream();
032
033    public TeeOutputStream(PrintStream targetPS) {
034        // allow for null arguments
035        this.targetPS = targetPS;
036    }
037
038    public void write(int b) throws IOException {
039        baos.write(b);
040        if (targetPS != null) {
041            targetPS.write(b);
042        }
043    }
044
045    public String toString() {
046        return baos.toString();
047    }
048
049    public byte[] toByteArray() {
050        return baos.toByteArray();
051    }
052}