All Downloads are FREE. Search and download functionalities are using the official Maven repository.

co.easimart.EasimartCurrentConfigController Maven / Gradle / Ivy

package co.easimart;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.Callable;

import bolts.Task;

/** package */ class EasimartCurrentConfigController {

  private final Object currentConfigMutex = new Object();
  /* package for test */ EasimartConfig currentConfig;
  private File currentConfigFile;

  public EasimartCurrentConfigController(File currentConfigFile) {
    this.currentConfigFile = currentConfigFile;
  }

  public Task setCurrentConfigAsync(final EasimartConfig config) {
    return Task.call(new Callable() {
      @Override
      public Void call() throws Exception {
        synchronized (currentConfigMutex) {
          currentConfig = config;
          saveToDisk(config);
        }
        return null;
      }
    }, EasimartExecutors.io());
  }

  public Task getCurrentConfigAsync() {
    return Task.call(new Callable() {
      @Override
      public EasimartConfig call() throws Exception {
        synchronized (currentConfigMutex) {
          if (currentConfig == null) {
            EasimartConfig config = getFromDisk();
            currentConfig = (config != null) ? config : new EasimartConfig();
          }
        }
        return currentConfig;
      }
    }, EasimartExecutors.io());
  }

  /**
   * Retrieves a {@code EasimartConfig} from a file on disk.
   *
   * @return The {@code EasimartConfig} that was retrieved. If the file wasn't found, or the contents
   *          of the file is an invalid {@code EasimartConfig}, returns null.
   */
  /* package for test */ EasimartConfig getFromDisk() {
    JSONObject json;
    try {
      json = EasimartFileUtils.readFileToJSONObject(currentConfigFile);
    } catch (IOException | JSONException e) {
      return null;
    }
    return new EasimartConfig(json, EasimartDecoder.get());
  }

  /* package */ void clearCurrentConfigForTesting() {
    synchronized (currentConfigMutex) {
      currentConfig = null;
    }
  }

  /**
   * Saves the {@code EasimartConfig} to the a file on disk as JSON.
   *
   * @param config
   *          The EasimartConfig which needs to be saved.
   */
  /* package for test */ void saveToDisk(EasimartConfig config) {
    JSONObject object = new JSONObject();
    try {
      JSONObject jsonParams = (JSONObject) NoObjectsEncoder.get().encode(config.getParams());
      object.put("params", jsonParams);
    } catch (JSONException e) {
      throw new RuntimeException("could not serialize config to JSON");
    }
    try {
      EasimartFileUtils.writeJSONObjectToFile(currentConfigFile, object);
    } catch (IOException e) {
      //TODO (grantland): We should do something if this fails...
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy