/*
 * Copyright (c) 2017, Apptentive, Inc. All Rights Reserved.
 * Please refer to the LICENSE file for the terms and conditions
 * under which redistribution and use of this file is permitted.
 */

package com.apptentive.android.sdk.storage;

import com.apptentive.android.sdk.util.Util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class FileSerializer implements Serializer {

	private final File file;

	public FileSerializer(File file) {
		if (file == null) {
			throw new IllegalArgumentException("'file' is null");
		}
		this.file = file;
	}

	@Override
	public void serialize(Object object) throws SerializerException {
		file.getParentFile().mkdirs();
		serialize(file, object);
	}

	@Override
	public Object deserialize() throws SerializerException {
		return deserialize(file);
	}

	protected void serialize(File file, Object object) throws SerializerException {
		FileOutputStream fos = null;
		ObjectOutputStream oos = null;
		try {
			fos = new FileOutputStream(file);
			oos = new ObjectOutputStream(fos);
			oos.writeObject(object);
		} catch (Exception e) {
			throw new SerializerException(e);
		} finally {
			Util.ensureClosed(fos);
			Util.ensureClosed(oos);
		}
	}

	protected Object deserialize(File file) throws SerializerException {
		FileInputStream fis = null;
		ObjectInputStream ois = null;
		try {
			fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			return ois.readObject();
		} catch (Exception e) {
			throw new SerializerException(e);
		} finally {
			Util.ensureClosed(fis);
			Util.ensureClosed(ois);
		}
	}
}

@@ -283,16 +283,54 @@
 .Util;%0A%0A
+import java.io.ByteArrayOutputStream;%0A
 import j
@@ -1026,20 +1026,25 @@
 ion %7B%0A%09%09
-File
+ByteArray
 OutputSt
@@ -1052,18 +1052,11 @@
 eam 
-f
+b
 os
- = null
 ;%0A%09%09
@@ -1078,32 +1078,63 @@
 eam oos = null;%0A
+%09%09FileOutputStream fos = null;%0A
 %09%09try %7B%0A%09%09%09fos =
@@ -1128,17 +1128,17 @@
 ry %7B%0A%09%09%09
-f
+b
 os = new
@@ -1138,20 +1138,25 @@
 s = new 
-File
+ByteArray
 OutputSt
@@ -1156,28 +1156,24 @@
 utputStream(
-file
 );%0A%09%09%09oos = 
@@ -1195,17 +1195,17 @@
 tStream(
-f
+b
 os);%0A%09%09%09
@@ -1229,16 +1229,86 @@
 bject);%0A
+%09%09%09fos = new FileOutputStream(file);%0A%09%09%09fos.write(bos.toByteArray());%0A
 %09%09%7D catc

Use a byte buffer for object file serialization to avoid data corruption on exceptions