Skip to content

Instantly share code, notes, and snippets.

@pocmo
Last active September 25, 2018 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pocmo/fd5ffa0989e85103bec5033ba6165d87 to your computer and use it in GitHub Desktop.
Save pocmo/fd5ffa0989e85103bec5033ba6165d87 to your computer and use it in GitHub Desktop.
/* 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