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