/* HeliDB -- A simple database for Java, http://www.helidb.org
* Copyright (C) 2008, 2009 Karl Gustafsson
*
* This file is a part of HeliDB.
*
* HeliDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeliDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.helidb.impl.txn.sc;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Random;
import org.entityfs.DirectoryView;
import org.entityfs.EFile;
import org.entityfs.ETFile;
import org.entityfs.ReadWritableFile;
import org.entityfs.support.exception.WrappedIOException;
import org.entityfs.support.io.StreamUtil;
/**
* Abstract base class for {@link ShadowCopyTxnDatabaseFileManager}
* implementations.
* @author Karl Gustafsson
* @since 1.0
*/
public abstract class AbstractFileManager implements ShadowCopyTxnDatabaseFileManager
{
private static final Random RANDOM = new Random(System.currentTimeMillis());
private static final int BUFFER_SIZE = 16384;
/**
* Copy the contents of the supplied file to a new file in the temporary
* directory.
* @param f The file to copy.
* @param tmpDir The directory where the new file should be created.
* @return The copy.
*/
protected EFile copyToTempFile(ReadWritableFile f, DirectoryView tmpDir)
{
EFile res = (EFile) tmpDir.newEntity(ETFile.TYPE, "sctxdb." + RANDOM.nextInt(Integer.MAX_VALUE), null);
try
{
WritableByteChannel wbc = res.openChannelForWrite();
try
{
ReadableByteChannel rbc = f.openChannelForRead();
try
{
// The buffer size should not matter for
// file-backed files which is probably the most
// common case.
StreamUtil.copyChannels(rbc, wbc, BUFFER_SIZE);
}
finally
{
rbc.close();
}
}
finally
{
wbc.close();
}
}
catch (IOException e)
{
throw new WrappedIOException(e);
}
return res;
}
}