diff --git a/src/main/java/com/hms_networks/americas/sc/extensions/config/ConfigUpdater.java b/src/main/java/com/hms_networks/americas/sc/extensions/config/ConfigUpdater.java new file mode 100644 index 00000000..552041ac --- /dev/null +++ b/src/main/java/com/hms_networks/americas/sc/extensions/config/ConfigUpdater.java @@ -0,0 +1,72 @@ +package com.hms_networks.americas.sc.extensions.config; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; + +import com.hms_networks.americas.sc.extensions.json.JSONException; +import com.hms_networks.americas.sc.extensions.json.JSONObject; + +public class ConfigUpdater { + + private JSONObject config; + private ArrayList steps; + private String applicationJsonKey; + private String configVersionJsonKey; + + public ConfigUpdater(JSONObject config, String applicationJsonKey, String configVersionJsonKey) + { + this.config = config; + steps = new ArrayList(); + this.applicationJsonKey = applicationJsonKey; + this.configVersionJsonKey = configVersionJsonKey; + } + + public JSONObject getConfig(){ + return config; + } + + private ConfigFileVersion getConfigFileVersion(){ + String versionString; + try { + versionString = config.getJSONObject(applicationJsonKey).getString(configVersionJsonKey); + } catch (JSONException e) { + versionString = "0.0.0"; + } + return new ConfigFileVersion(versionString); + } + + private void setConfigFileVersion(ConfigFileVersion version){ + try { + config.getJSONObject(applicationJsonKey).put(configVersionJsonKey, version.getVersionString()); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + public void addStep(ConfigFileUpdateStep step){ + steps.add(step); + } + + public boolean updateConfig(){ + boolean success = true; + Collections.sort(steps); + for (int i = 0; i < steps.size(); i++){ + ConfigFileUpdateStep step = (ConfigFileUpdateStep) steps.get(i); + if (step.isCompatibleWithVersion(getConfigFileVersion())){ + success = success && step.updateConfig(config); + if (success){ + setConfigFileVersion(step.getStepVersion()); + } + else { + break; + } + } + else { + success = false; + break; + } + } + return success; + } +}