001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.servicemix.jbi.audit.file;
018
019 import java.io.FilterInputStream;
020 import java.io.IOException;
021 import java.io.InputStream;
022 import java.io.OutputStream;
023
024 /**
025 * {@link FilterInputStream} implementation that sends a copy of all data being processed to the specified OutputStream.
026 *
027 * @author Gert Vanthienen (gertv)
028 * @since 3.2
029 */
030 public class TeeInputStream extends FilterInputStream {
031
032 private final OutputStream os;
033
034 /**
035 * Create a new TeeInputStream
036 *
037 * @param is the InputStream to read from
038 * @param os the OuputStream to copy data to
039 */
040 public TeeInputStream(InputStream is, OutputStream os) {
041 super(is);
042 this.os = os;
043 }
044
045 /**
046 * Reads a single byte from the underlying InputStream. In addition, it also write the same byte to the OutputStream.
047 */
048 @Override
049 public int read() throws IOException {
050 int read = super.read();
051 if (read != -1) {
052 os.write(read);
053 }
054 return read;
055 }
056
057 /**
058 * Read a block of bytes from the underlying InputStream. In addition, write the same data to the OutputStream.
059 */
060 @Override
061 public int read(byte[] bytes, int offset, int length) throws IOException {
062 int read = super.read(bytes, offset, length);
063 if (read != -1) {
064 os.write(bytes, offset, read);
065 }
066 return read;
067 }
068
069 /**
070 * Close the underlying InputStream. Also, flush and close the underlying OutputStream.
071 */
072 @Override
073 public void close() throws IOException {
074 super.close();
075 os.flush();
076 os.close();
077 }
078 }