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 */
017package org.apache.camel.converter.stream;
018
019import java.io.ByteArrayInputStream;
020import java.io.ByteArrayOutputStream;
021import java.io.FilterInputStream;
022import java.io.IOException;
023import java.io.OutputStream;
024
025import org.apache.camel.StreamCache;
026import org.apache.camel.util.IOHelper;
027
028/**
029 * A {@link StreamCache} for {@link java.io.ByteArrayInputStream}
030 */
031public class ByteArrayInputStreamCache extends FilterInputStream implements StreamCache {
032
033    private final int length;
034    private byte[] byteArrayForCopy;
035
036    public ByteArrayInputStreamCache(ByteArrayInputStream in) {
037        super(in);
038        this.length = in.available();
039    }
040
041    @Override
042    public void reset() {
043        try {
044            super.reset();
045        } catch (IOException e) {
046            // ignore
047        }
048    }
049
050    public void writeTo(OutputStream os) throws IOException {
051        IOHelper.copyAndCloseInput(in, os);
052    }
053
054    public StreamCache copy() throws IOException {
055        if (byteArrayForCopy == null) {
056            ByteArrayOutputStream baos = new ByteArrayOutputStream(in.available());
057            IOHelper.copy(in, baos);
058            // reset so that the stream can be reused
059            reset();
060            // cache the byte array, in order not to copy the byte array in the next call again
061            byteArrayForCopy = baos.toByteArray();
062        }
063        return new InputStreamCache(byteArrayForCopy);
064    }
065
066    public boolean inMemory() {
067        return true;
068    }
069
070    @Override
071    public long length() {
072        return length;
073    }
074}