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 CachedOutputStream cachedOutputStream;
033 private File file;
034
035 public FileInputStreamCache(File file, CachedOutputStream cos) throws FileNotFoundException {
036 this.file = file;
037 this.cachedOutputStream = cos;
038 this.stream = new FileInputStream(file);
039 }
040
041 @Override
042 public void close() {
043 try {
044 getInputStream().close();
045 if (cachedOutputStream != null) {
046 cachedOutputStream.close();
047 }
048 } catch (Exception e) {
049 throw new RuntimeCamelException(e);
050 }
051 }
052
053 @Override
054 public void reset() {
055 try {
056 getInputStream().close();
057 // reset by creating a new stream based on the file
058 stream = new FileInputStream(file);
059 } catch (Exception e) {
060 throw new RuntimeCamelException(e);
061 }
062 }
063
064 public void writeTo(OutputStream os) throws IOException {
065 IOHelper.copy(getInputStream(), os);
066 }
067
068 @Override
069 public int available() throws IOException {
070 return getInputStream().available();
071 }
072
073 @Override
074 public int read() throws IOException {
075 return getInputStream().read();
076 }
077
078 protected InputStream getInputStream() {
079 return stream;
080 }
081
082 }