@Override public synchronized <E> void insert(String key, E value) { assertInit(); final ObjectEntity<E> objectEntity = new ObjectEntity<>(value); objectEntity.removeReferences(); final File originalFile = getOriginalFile(key); final File backupFile = makeBackupFile(originalFile); // Rename the current file so it may be used as a backup during the next read if (originalFile.exists()) { // Rename original to backup if (!backupFile.exists()) { if (!originalFile.renameTo(backupFile)) { throw new PaperDbException( "Couldn't rename file " + originalFile + " to backup file " + backupFile); } } else { // Backup exist -> original file is broken and must be deleted //noinspection ResultOfMethodCallIgnored originalFile.delete(); } } writeTableFile(key, objectEntity, originalFile, backupFile); objectEntity.restoreReferences(); }
private <E> E readTableFile(String key, File originalFile) { try { final Input i = new Input(new FileInputStream(originalFile)); final Kryo kryo = getKryo(); //noinspection unchecked final ObjectEntity<E> objectEntity = kryo.readObject(i, ObjectEntity.class); objectEntity.restoreReferences(); i.close(); return objectEntity.getContent(); } catch (FileNotFoundException | KryoException e) { // Clean up an unsuccessfully written file if (originalFile.exists()) { if (!originalFile.delete()) { throw new PaperDbException( "Couldn't clean up broken/unserializable file " + originalFile, e); } } throw new PaperDbException( "Couldn't read/deserialize file " + originalFile + " for table " + key, e); } }