001/*
002 * HA-JDBC: High-Availability JDBC
003 * Copyright (C) 2013  Paul Ferraro
004 *
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Lesser General Public License as published by
007 * the Free Software Foundation, either version 3 of the License, or
008 * (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Lesser General Public License for more details.
014 *
015 * You should have received a copy of the GNU Lesser General Public License
016 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
017 */
018package net.sf.hajdbc.io.file;
019
020import java.io.BufferedInputStream;
021import java.io.File;
022import java.io.FileInputStream;
023import java.io.FileOutputStream;
024import java.io.IOException;
025import java.io.InputStream;
026import java.nio.ByteBuffer;
027import java.nio.channels.Channels;
028import java.nio.channels.FileChannel;
029import java.nio.channels.ReadableByteChannel;
030
031import net.sf.hajdbc.io.InputSinkChannel;
032import net.sf.hajdbc.util.Files;
033import net.sf.hajdbc.util.Resources;
034
035/**
036 * Input stream channel for writing to, and reading from, a file sink.
037 * @author Paul Ferraro
038 */
039public class FileInputStreamSinkChannel implements InputSinkChannel<InputStream, File>
040{
041        @Override
042        public File write(InputStream input) throws IOException
043        {
044                File file = Files.createTempFile(FileInputSinkStrategy.TEMP_FILE_SUFFIX);
045                FileOutputStream output = new FileOutputStream(file);
046                try
047                {
048                        FileChannel fileChannel = output.getChannel();
049                        ReadableByteChannel inputChannel = Channels.newChannel(input);
050                        
051                        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
052                        
053                        while (inputChannel.read(buffer) > 0)
054                        {
055                                buffer.flip();
056                                fileChannel.write(buffer);
057                                buffer.compact();
058                        }
059                        
060                        return file;
061                }
062                finally
063                {
064                        Resources.close(output);
065                }
066        }
067
068        @Override
069        public InputStream read(File sink) throws IOException
070        {
071                return new BufferedInputStream(new FileInputStream(sink), BUFFER_SIZE);
072        }
073}