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.camel.converter.stream;
018    
019    import java.io.File;
020    import java.io.FileInputStream;
021    import java.io.FileNotFoundException;
022    import java.io.IOException;
023    import java.io.InputStream;
024    import java.io.OutputStream;
025    
026    import org.apache.camel.RuntimeCamelException;
027    import org.apache.camel.StreamCache;
028    import org.apache.camel.util.IOHelper;
029    
030    public class FileInputStreamCache extends InputStream implements StreamCache {
031        private InputStream stream;
032        private File file;
033    
034        public FileInputStreamCache(File file) throws FileNotFoundException {
035            this.file = file;
036            this.stream = IOHelper.buffered(new FileInputStream(file));
037        }
038        
039        @Override
040        public void close() {
041            if (stream != null) {
042                IOHelper.close(stream);
043            }
044        }
045    
046        @Override
047        public void reset() {
048            try {
049                // reset by closing and creating a new stream based on the file
050                close();
051                // reset by creating a new stream based on the file
052                stream = IOHelper.buffered(new FileInputStream(file));
053            } catch (FileNotFoundException e) {
054                throw new RuntimeCamelException("Cannot reset stream from file " + file, e);
055            }            
056        }
057    
058        public void writeTo(OutputStream os) throws IOException {
059            IOHelper.copy(getInputStream(), os);
060        }
061    
062        @Override
063        public int available() throws IOException {
064            return getInputStream().available();
065        }
066    
067        @Override
068        public int read() throws IOException {
069            return getInputStream().read();
070        }
071    
072        protected InputStream getInputStream() {
073            return stream;
074        }
075    }