br.com.objectos.way.base.io.DataFileOutputStream Maven / Gradle / Ivy
/*
* Copyright 2014 Objectos, Fábrica de Software LTDA.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package br.com.objectos.way.base.io;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
/**
* @author [email protected] (Marcio Endo)
*/
abstract class DataFileOutputStream {
final DataFile file;
public DataFileOutputStream(DataFile file) {
this.file = file;
}
public static DataFileOutputStream valid(DataFile file, FileOutputStream os) {
return new Valid(file, os);
}
public static DataFileOutputStream invalid(DataFile file, FileNotFoundException e) {
return new Invalid(file, e);
}
abstract void transferFrom(ReadableByteChannel rbc);
private static class Valid extends DataFileOutputStream {
private final FileOutputStream os;
public Valid(DataFile file, FileOutputStream os) {
super(file);
this.os = os;
}
@Override
void transferFrom(ReadableByteChannel rbc) {
try {
FileChannel channel = os.getChannel();
channel.transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (IOException e) {
DataFileLog log = DataFileLog.of(file);
log.error("Could not write to %s", e, file.getPath());
} finally {
try {
os.close();
} catch (IOException e) {
}
}
}
}
private static class Invalid extends DataFileOutputStream {
private final IOException e;
public Invalid(DataFile file, IOException e) {
super(file);
this.e = e;
}
@Override
void transferFrom(ReadableByteChannel rbc) {
DataFileLog log = DataFileLog.of(file);
log.error("Could not open %s", e, file.getPath());
}
}
}