package net.pterodactylus.sonitus.data.sink;
-import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Logger;
-import net.pterodactylus.sonitus.data.ConnectException;
-import net.pterodactylus.sonitus.data.Connection;
-import net.pterodactylus.sonitus.data.Sink;
-import net.pterodactylus.sonitus.data.Source;
-
-import com.google.common.base.Preconditions;
+import net.pterodactylus.sonitus.data.AbstractFilter;
+import net.pterodactylus.sonitus.data.DataPacket;
+import net.pterodactylus.sonitus.data.Filter;
+import net.pterodactylus.sonitus.data.Metadata;
/**
- * {@link Sink} that writes all received data into a file.
+ * {@link Filter} that writes all received data into a file.
*
* @author <a href="mailto:bombe@pterodactylus.net">David ‘Bombe’ Roden</a>
*/
-public class FileSink implements Sink {
+public class FileSink extends AbstractFilter {
/** The logger. */
private static final Logger logger = Logger.getLogger(FileSink.class.getName());
/** The path of the file to write to. */
private final String path;
+ /** The output stream writing to the file. */
+ private FileOutputStream fileOutputStream;
+
/**
* Creates a new file sink that will write to the given path.
*
* The path of the file to write to
*/
public FileSink(String path) {
+ super(path);
this.path = path;
}
+ //
+ // FILTER METHODS
+ //
+
@Override
- public void connect(Source source) throws ConnectException {
- Preconditions.checkNotNull(source, "source must not be null");
+ public void open(Metadata metadata) throws IOException {
+ fileOutputStream = new FileOutputStream(path);
+ metadataUpdated(metadata);
+ }
+ @Override
+ public void close() {
try {
- final FileOutputStream fileOutputStream = new FileOutputStream(path);
- new Thread(new Connection(source) {
-
- @Override
- protected int bufferSize() {
- return 65536;
- }
-
- @Override
- protected void feed(byte[] buffer) throws IOException {
- fileOutputStream.write(buffer);
- logger.finest(String.format("FileSink: Wrote %d Bytes.", buffer.length));
- }
-
- @Override
- protected void finish() throws IOException {
- fileOutputStream.close();
- }
- }).start();
- } catch (FileNotFoundException fnfe1) {
- throw new ConnectException(fnfe1);
+ fileOutputStream.close();
+ } catch (IOException e) {
+ /* ignore. */
}
}
@Override
- public void metadataUpdated() {
- /* ignore. */
+ public void process(DataPacket dataPacket) throws IOException {
+ fileOutputStream.write(dataPacket.buffer());
+ logger.finest(String.format("FileSink: Wrote %d Bytes.", dataPacket.buffer().length));
}
}