Bug 1109361 - Handle empty files when loading ProfileInformationCache. r=mcomella

This commit is contained in:
Richard Newman 2014-12-23 14:28:46 -08:00
parent af9ea30eac
commit cf06fe7534
3 changed files with 29 additions and 5 deletions

View File

@ -70,11 +70,15 @@ public class ProfileInformationCache implements ProfileInformationProvider {
private volatile JSONObject addons = null;
public ProfileInformationCache(String profilePath) {
file = new File(profilePath + File.separator + CACHE_FILE);
protected ProfileInformationCache(final File f) {
file = f;
Logger.pii(LOG_TAG, "Using " + file.getAbsolutePath() + " for profile information cache.");
}
public ProfileInformationCache(final String profilePath) {
this(new File(profilePath + File.separator + CACHE_FILE));
}
public synchronized void beginInitialization() {
initialized = false;
needsWrite = true;
@ -109,6 +113,11 @@ public class ProfileInformationCache implements ProfileInformationProvider {
* @return false if there's a version mismatch or an error, true on success.
*/
private boolean fromJSON(JSONObject object) throws JSONException {
if (object == null) {
Logger.debug(LOG_TAG, "Can't load restore PIC from null JSON object.");
return false;
}
int version = object.optInt("version", 1);
switch (version) {
case FORMAT_VERSION:
@ -130,9 +139,11 @@ public class ProfileInformationCache implements ProfileInformationProvider {
protected JSONObject readFromFile() throws FileNotFoundException, JSONException {
Scanner scanner = null;
try {
scanner = new Scanner(file, "UTF-8");
final String contents = scanner.useDelimiter("\\A").next();
return new JSONObject(contents);
scanner = new Scanner(file, "UTF-8").useDelimiter("\\A");
if (!scanner.hasNext()) {
return null;
}
return new JSONObject(scanner.next());
} finally {
if (scanner != null) {
scanner.close();

View File

@ -16,6 +16,10 @@ public class MockProfileInformationCache extends ProfileInformationCache {
super(profilePath);
}
public MockProfileInformationCache(File mockFile) {
super(mockFile);
}
public boolean isInitialized() {
return this.initialized;
}

View File

@ -12,6 +12,15 @@ import org.mozilla.gecko.background.helpers.FakeProfileTestCase;
public class TestProfileInformationCache extends FakeProfileTestCase {
public final void testEmptyFile() throws Exception {
// createTempFile creates an empty file on disk.
final File emptyFile = File.createTempFile("empty", "pic", this.fakeProfileDirectory);
final MockProfileInformationCache cache = new MockProfileInformationCache(emptyFile);
// Should not throw.
assertNull(cache.readJSON());
}
public final void testInitState() throws IOException {
MockProfileInformationCache cache = new MockProfileInformationCache(this.fakeProfileDirectory.getAbsolutePath());
assertFalse(cache.isInitialized());