PluginConsumer: when writing to files, serialize directly
Rather than serializing to RAM first.
@@ -12,6 +12,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
+import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
@@ -299,20 +300,29 @@ public abstract class PluginConsumer implements IPluginConsumer {
}
}
+ /** Serializes the given object to a file with the given output name, using GZIP compression. */
public void serializeObject(Serializable object, Path outputFile) {
try {
- byte[] data = toGzipData(object);
- Files.write(outputFile, data);
+ try (OutputStream out = Files.newOutputStream(outputFile)) {
+ serializeToGzipData(object, out);
+ }
} catch (IOException e) {
throw new BatfishException(
"Failed to serialize object to gzip output file: " + outputFile, e);
}
}
+ /** Serializes the given object to a GZIP-compressed byte[]. */
protected byte[] toGzipData(Serializable object) {
- try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- GZIPOutputStream gos = new GZIPOutputStream(baos);
+ serializeToGzipData(object, baos);
+ return baos.toByteArray();
+ }
+
+ /** Serializes the given object to the given stream, using GZIP compression. */
+ private void serializeToGzipData(Serializable object, OutputStream out) {
+ try {
+ GZIPOutputStream gos = new GZIPOutputStream(out);
ObjectOutputStream oos;
if (_serializeToText) {
XStream xstream = new XStream(new DomDriver("UTF-8"));
@@ -321,9 +331,8 @@ public abstract class PluginConsumer implements IPluginConsumer {
oos = new ObjectOutputStream(gos);
}
oos.writeObject(object);
- oos.close();
- byte[] data = baos.toByteArray();
- return data;
+ oos.flush();
+ gos.finish(); // close the GZIP file entry
} catch (IOException e) {
throw new BatfishException("Failed to convert object to gzip data", e);
}
