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.BufferedReader;
021import java.io.File;
022import java.io.FileReader;
023import java.io.FileWriter;
024import java.io.IOException;
025import java.io.Reader;
026import java.io.Writer;
027import java.nio.CharBuffer;
028
029import net.sf.hajdbc.io.InputSinkChannel;
030import net.sf.hajdbc.util.Files;
031import net.sf.hajdbc.util.Resources;
032
033/**
034 * Reader channel for writing to, and reading from, a file sink..
035 * @author Paul Ferraro
036 */
037public class FileReaderSinkChannel implements InputSinkChannel<Reader, File>
038{
039        @Override
040        public File write(Reader reader) throws IOException
041        {
042                File file = Files.createTempFile(FileInputSinkStrategy.TEMP_FILE_SUFFIX);
043                Writer writer = new FileWriter(file);
044                try
045                {
046                        CharBuffer buffer = CharBuffer.allocate(BUFFER_SIZE);
047                        
048                        while (reader.read(buffer) > 0)
049                        {
050                                buffer.flip();
051                                writer.append(buffer);
052                                buffer.clear();
053                        }
054                        
055                        return file;
056                }
057                finally
058                {
059                        Resources.close(writer);
060                }
061        }
062
063        @Override
064        public Reader read(File sink) throws IOException
065        {
066                return new BufferedReader(new FileReader(sink), BUFFER_SIZE);
067        }
068}