Last active
September 25, 2018 19:16
-
-
Save pocmo/fd5ffa0989e85103bec5033ba6165d87 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This Source Code Form is subject to the terms of the Mozilla Public | |
* License, v. 2.0. If a copy of the MPL was not distributed with this | |
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | |
package mozilla.components.service.fretboard.storage.flatfile | |
import android.util.AtomicFile | |
import mozilla.components.service.fretboard.ExperimentStorage | |
import mozilla.components.service.fretboard.ExperimentsSnapshot | |
import java.io.FileNotFoundException | |
import java.io.File | |
import java.io.IOException | |
/** | |
* Class which uses a flat JSON file as an experiment storage mechanism | |
* | |
* @param file file where to store experiments | |
*/ | |
class FlatFileExperimentStorage(file: File) : ExperimentStorage { | |
private val atomicFile: AtomicFile = AtomicFile(file) | |
override fun retrieve(): ExperimentsSnapshot { | |
return try { | |
val experimentsJson = String(atomicFile.readFully()) | |
ExperimentsSerializer().fromJson(experimentsJson) | |
} catch (e: FileNotFoundException) { | |
ExperimentsSnapshot(listOf(), null) | |
} | |
} | |
override fun save(snapshot: ExperimentsSnapshot) { | |
val experimentsJson = ExperimentsSerializer().toJson(snapshot) | |
val stream = atomicFile.startWrite() | |
try { | |
stream.writer().use { | |
it.append(experimentsJson) | |
} | |
atomicFile.finishWrite(stream) | |
} catch(e: IOException) { | |
atomicFile.failWrite(stream) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment