Skip to content
This repository has been archived by the owner on Mar 5, 2023. It is now read-only.

Commit

Permalink
Reduced duplication between ConfigUtil and JsonUserPrefsStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
lejolly committed Oct 6, 2016
1 parent 386c3c1 commit 11e6837
Show file tree
Hide file tree
Showing 17 changed files with 161 additions and 156 deletions.
7 changes: 3 additions & 4 deletions src/main/java/seedu/address/MainApp.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,12 @@
import seedu.address.logic.Logic;
import seedu.address.logic.LogicManager;
import seedu.address.model.*;
import seedu.address.commons.util.ConfigUtil;
import seedu.address.storage.ConfigStorage;
import seedu.address.storage.Storage;
import seedu.address.storage.StorageManager;
import seedu.address.ui.Ui;
import seedu.address.ui.UiManager;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Optional;
Expand Down Expand Up @@ -107,7 +106,7 @@ protected Config initConfig(String configFilePath) {
logger.info("Using config file : " + configFilePathUsed);

try {
Optional<Config> configOptional = ConfigUtil.readConfig(configFilePathUsed);
Optional<Config> configOptional = ConfigStorage.readConfig(configFilePathUsed);
initializedConfig = configOptional.orElse(new Config());
} catch (DataConversionException e) {
logger.warning("Config file at " + configFilePathUsed + " is not in the correct format. " +
Expand All @@ -117,7 +116,7 @@ protected Config initConfig(String configFilePath) {

//Update config file in case it was missing to begin with or there are new/unused fields
try {
ConfigUtil.saveConfig(initializedConfig, configFilePathUsed);
ConfigStorage.saveConfig(initializedConfig, configFilePathUsed);
} catch (IOException e) {
logger.warning("Failed to save config file : " + StringUtil.getDetails(e));
}
Expand Down
4 changes: 3 additions & 1 deletion src/main/java/seedu/address/commons/core/Config.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package seedu.address.commons.core;

import seedu.address.storage.JsonFile;

import java.util.Objects;
import java.util.logging.Level;

/**
* Config values used by the app
*/
public class Config {
public class Config extends JsonFile {

public static final String DEFAULT_CONFIG_FILE = "config.json";

Expand Down
62 changes: 0 additions & 62 deletions src/main/java/seedu/address/commons/util/ConfigUtil.java

This file was deleted.

12 changes: 3 additions & 9 deletions src/main/java/seedu/address/commons/util/FileUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
import java.nio.file.Files;

/**
* Writes and reads file
* Writes and reads files, includes methods for reading and writing to
* preference/config json files
*/
public class FileUtil {

private static final String CHARSET = "UTF-8";

public static boolean isFileExists(File file) {
Expand Down Expand Up @@ -84,12 +86,4 @@ public static String getPath(String pathWithForwardSlash) {
return pathWithForwardSlash.replace("/", File.separator);
}

public static <T> void serializeObjectToJsonFile(File jsonFile, T objectToSerialize) throws IOException {
FileUtil.writeToFile(jsonFile, JsonUtil.toJsonString(objectToSerialize));
}

public static <T> T deserializeObjectFromJsonFile(File jsonFile, Class<T> classOfObjectToDeserialize)
throws IOException {
return JsonUtil.fromJsonString(FileUtil.readFromFile(jsonFile), classOfObjectToDeserialize);
}
}
63 changes: 63 additions & 0 deletions src/main/java/seedu/address/commons/util/JsonUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,77 @@
import com.fasterxml.jackson.databind.deser.std.FromStringDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.storage.JsonFile;

import java.io.File;
import java.io.IOException;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
* Converts a Java object instance to JSON and vice versa
*/
public class JsonUtil {

private static final Logger logger = LogsCenter.getLogger(JsonUtil.class);

public static <T> void serializeObjectToJsonFile(File jsonFile, T objectToSerialize) throws IOException {
FileUtil.writeToFile(jsonFile, toJsonString(objectToSerialize));
}

public static <T> T deserializeObjectFromJsonFile(File jsonFile, Class<T> classOfObjectToDeserialize)
throws IOException {
return fromJsonString(FileUtil.readFromFile(jsonFile), classOfObjectToDeserialize);
}

/**
* Returns the Json object from the given file or {@code Optional.empty()} object if the file is not found.
* If any values are missing from the file, default values will be used, as long as the file is a valid json file.
* @param filePath cannot be null.
* @param classOfObjectToDeserialize has to extend JsonFile.
* @throws DataConversionException if the file format is not as expected.
*/
public static <T extends JsonFile> Optional<T> readJsonFile(
String filePath, Class<T> classOfObjectToDeserialize) throws DataConversionException {

assert filePath != null;

File file = new File(filePath);

if (!file.exists()) {
logger.info("Config file " + file + " not found");
return Optional.empty();
}

T jsonFile;

try {
jsonFile = deserializeObjectFromJsonFile(file, classOfObjectToDeserialize);
} catch (IOException e) {
logger.warning("Error reading from jsonFile file " + file + ": " + e);
throw new DataConversionException(e);
}

return Optional.of(jsonFile);
}

/**
* Saves the Json object to the specified file.
* Overwrites existing file if it exists, creates a new file if it doesn't.
* @param jsonFile cannot be null
* @param filePath cannot be null
* @throws IOException if there was an error during writing to the file
*/
public static <T extends JsonFile> void saveJsonFile(T jsonFile, String filePath) throws IOException {
assert jsonFile != null;
assert filePath != null;

serializeObjectToJsonFile(new File(filePath), jsonFile);
}

private static class LevelDeserializer extends FromStringDeserializer<Level> {

protected LevelDeserializer(Class<?> vc) {
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/seedu/address/model/UserPrefs.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
package seedu.address.model;

import seedu.address.commons.core.GuiSettings;
import seedu.address.storage.JsonFile;

import java.util.Objects;

/**
* Represents User's preferences.
*/
public class UserPrefs {
public class UserPrefs extends JsonFile {

public GuiSettings guiSettings;

Expand Down
23 changes: 23 additions & 0 deletions src/main/java/seedu/address/storage/ConfigStorage.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package seedu.address.storage;

import seedu.address.commons.core.Config;
import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.commons.util.JsonUtil;

import java.io.IOException;
import java.util.Optional;

/**
* A class for accessing the Config File.
*/
public class ConfigStorage {

public static Optional<Config> readConfig(String configFilePath) throws DataConversionException {
return JsonUtil.readJsonFile(configFilePath, Config.class);
}

public static void saveConfig(Config config, String configFilePath) throws IOException {
JsonUtil.saveJsonFile(config, configFilePath);
}

}
14 changes: 14 additions & 0 deletions src/main/java/seedu/address/storage/JsonFile.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package seedu.address.storage;

/**
* Purely a marker for FileUtil.
*/
public abstract class JsonFile {

public abstract boolean equals(Object other);

public abstract int hashCode();

public abstract String toString();

}
50 changes: 6 additions & 44 deletions src/main/java/seedu/address/storage/JsonUserPrefsStorage.java
Original file line number Diff line number Diff line change
@@ -1,22 +1,17 @@
package seedu.address.storage;

import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.exceptions.DataConversionException;
import seedu.address.commons.util.FileUtil;
import seedu.address.commons.util.JsonUtil;
import seedu.address.model.UserPrefs;

import java.io.File;
import java.io.IOException;
import java.util.Optional;
import java.util.logging.Logger;

/**
* A class to access UserPrefs stored in the hard disk as a json file
*/
public class JsonUserPrefsStorage implements UserPrefsStorage{

private static final Logger logger = LogsCenter.getLogger(JsonUserPrefsStorage.class);

private String filePath;

public JsonUserPrefsStorage(String filePath){
Expand All @@ -28,46 +23,13 @@ public Optional<UserPrefs> readUserPrefs() throws DataConversionException, IOExc
return readUserPrefs(filePath);
}

@Override
public void saveUserPrefs(UserPrefs userPrefs) throws IOException {
saveUserPrefs(userPrefs, filePath);
}

/**
* Similar to {@link #readUserPrefs()}
* @param prefsFilePath location of the data. Cannot be null.
* @throws DataConversionException if the file format is not as expected.
*/
public Optional<UserPrefs> readUserPrefs(String prefsFilePath) throws DataConversionException {
assert prefsFilePath != null;

File prefsFile = new File(prefsFilePath);

if (!prefsFile.exists()) {
logger.info("Prefs file " + prefsFile + " not found");
return Optional.empty();
}

UserPrefs prefs;

try {
prefs = FileUtil.deserializeObjectFromJsonFile(prefsFile, UserPrefs.class);
} catch (IOException e) {
logger.warning("Error reading from prefs file " + prefsFile + ": " + e);
throw new DataConversionException(e);
}

return Optional.of(prefs);
return JsonUtil.readJsonFile(prefsFilePath, UserPrefs.class);
}

/**
* Similar to {@link #saveUserPrefs(UserPrefs)}
* @param prefsFilePath location of the data. Cannot be null.
*/
public void saveUserPrefs(UserPrefs userPrefs, String prefsFilePath) throws IOException {
assert userPrefs != null;
assert prefsFilePath != null;

FileUtil.serializeObjectToJsonFile(new File(prefsFilePath), userPrefs);
@Override
public void saveUserPrefs(UserPrefs userPrefs) throws IOException {
JsonUtil.saveJsonFile(userPrefs, filePath);
}

}
26 changes: 0 additions & 26 deletions src/test/java/seedu/address/commons/util/FileUtilTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,12 @@
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import seedu.address.testutil.SerializableTestClass;
import seedu.address.testutil.TestUtil;

import java.io.File;
import java.io.IOException;

import static org.junit.Assert.assertEquals;

public class FileUtilTest {
private static final File SERIALIZATION_FILE = new File(TestUtil.getFilePathInSandboxFolder("serialize.json"));


@Rule
public ExpectedException thrown = ExpectedException.none();
Expand All @@ -34,25 +29,4 @@ public void getPath(){
FileUtil.getPath("folder");
}

@Test
public void serializeObjectToJsonFile_noExceptionThrown() throws IOException {
SerializableTestClass serializableTestClass = new SerializableTestClass();
serializableTestClass.setTestValues();

FileUtil.serializeObjectToJsonFile(SERIALIZATION_FILE, serializableTestClass);

assertEquals(FileUtil.readFromFile(SERIALIZATION_FILE), SerializableTestClass.JSON_STRING_REPRESENTATION);
}

@Test
public void deserializeObjectFromJsonFile_noExceptionThrown() throws IOException {
FileUtil.writeToFile(SERIALIZATION_FILE, SerializableTestClass.JSON_STRING_REPRESENTATION);

SerializableTestClass serializableTestClass = FileUtil
.deserializeObjectFromJsonFile(SERIALIZATION_FILE, SerializableTestClass.class);

assertEquals(serializableTestClass.getName(), SerializableTestClass.getNameTestValue());
assertEquals(serializableTestClass.getListOfLocalDateTimes(), SerializableTestClass.getListTestValues());
assertEquals(serializableTestClass.getMapOfIntegerToString(), SerializableTestClass.getHashMapTestValues());
}
}
Loading

0 comments on commit 11e6837

Please sign in to comment.