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

io.jsync.app.core.Config Maven / Gradle / Ivy

There is a newer version: 1.10.13
Show newest version
package io.jsync.app.core;

import io.jsync.buffer.Buffer;
import io.jsync.json.DecodeException;
import io.jsync.json.JsonObject;
import io.jsync.utils.CryptoUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

public class Config {

    private Logger logger = new Logger();

    private JsonObject config;

    private String configPath = "cluster.json";

    private Config(JsonObject jsonConfig) {
        this(jsonConfig, false);
    }

    private Config(JsonObject jsonConfig, boolean create) {
        if (jsonConfig == null) {
            throw new NullPointerException();
        }
        config = jsonConfig;
        if (create) {
            save();
            return;
        }
        logger.debug("Loaded config from " + configPath);
    }

    public Config() {
        config = new JsonObject();
    }

    public static Config bind(Cluster parent) {
        Config config = new Config();
        parent.config = config;
        return config;
    }

    public Config create(String configPath) {
        this.configPath = configPath;
        save();
        return this;
    }

    public Config open(String configPath) {
        this.configPath = configPath;
        reload();
        return this;
    }

    public Config open(JsonObject jsonConfig) {
        if (jsonConfig == null) {
            throw new NullPointerException();
        }

        config = jsonConfig;
        save();
        return this;
    }

    public JsonObject rawConfig() {
        return config;
    }

    public boolean containsKey(String key) {
        return config.containsField(key);
    }

    public Object getValue(String key) {
        if (config.containsField(key)) {
            return config.getValue(key);
        }
        return null;
    }

    public void setValue(String key, Object value) {
        config.putValue(key, value);
    }

    private JsonObject clusterConfig() {
        return config.getObject("cluster");
    }

    public String clusterRole() {
        return clusterConfig().getString("role");
    }

    public String clusterHost() {
        return clusterConfig().containsField("host") ? clusterConfig().getString("host") : "";
    }

    public String clusterName() {
        return clusterConfig().containsField("name") ? clusterConfig().getString("name") : "";
    }

    public String clusterPassword() {
        return clusterConfig().containsField("password") ? clusterConfig().getString("password") : "";
    }

    public boolean isDebug() {
        if (getValue("debug") != null) {
            if (getValue("debug").equals(true)) {
                return true;
            }
        }
        return false;
    }

    public boolean isAll() {
        return clusterRole().equals("all");
    }

    public boolean isDefault() {
        return clusterRole().equals("default");
    }

    public boolean isRole(String role) {
        return clusterRole().equals(role);
    }

    public void setRole(String role) {
        clusterConfig().putString("role", role);
    }

    private boolean validate() {

        boolean success = true;
        // Check the configuration for a clustered server
        if (!clusterConfig().containsField("role")) {
            logger.error("Missing role in cluster config data");
            success = false;
        } else {
            if (!clusterRole().matches("default|client|all")) {
                logger.debug("Unknown or custom role " + clusterRole());
            }
        }
        if (!clusterConfig().containsField("host")) {
            logger.error("Missing host in cluster config data");
            success = false;
        }
        if (!clusterConfig().containsField("name")) {
            logger.error("Missing name in cluster config data");
            success = false;
        }
        if (!clusterConfig().containsField("password")) {
            logger.error("Missing password in cluster config data");
            success = false;
        }
        return success;
    }

    public void save() {
        logger.debug("Attempting to save config data to " + configPath);
        if (config.size() < 1) {
            saveDefault();
            return;
        }

        Path filePath = Paths.get(configPath);

        if (!Files.exists(filePath)) {
            logger.debug("Could not find " + configPath);
            try {
                Files.createFile(filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (!Files.exists(filePath)) {
                logger.fatal("Could not create " + configPath);
                return;
            }
            saveDefault();
            return;
        }

        try {
            Files.write(filePath, config.encode(false).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!Files.exists(filePath)) {
            logger.fatal("Could not write " + configPath);
            return;
        }

        logger.debug("Successfully saved config data to " + configPath);
        reload();
    }

    private void saveDefault() {
        logger.debug("Saving default config.");
        config = getDefaultConfig();
        save();
    }

    private void reload() {
        logger.debug("Attempting to reload config data from " + configPath);

        Path filePath = Paths.get(configPath);

        if (!Files.exists(filePath)) {
            logger.error("Could not find " + configPath);
            save();
            return;
        }

        Buffer fileBuffer = null;
        try {
            fileBuffer = new Buffer(Files.readAllBytes(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (fileBuffer == null) {
            logger.error("Could not read " + configPath);
            save();
            return;
        }

        if (fileBuffer.toString().trim().equals("")) {
            logger.error("The config data is empty");
            saveDefault();
            return;
        }

        try {

            JsonObject jsonData = getDefaultConfig();
            jsonData.mergeIn(new JsonObject(fileBuffer.toString()));

            config = jsonData;

            if (!validate()) {
                logger.fatal("Could not validate the config..");
            }

        } catch (DecodeException e) {
            // TODO -- Why does this save?
            save();
        }
    }

    private JsonObject getDefaultConfig() {
        JsonObject defaultConfig = new JsonObject();
        String tmpClusterKey = CryptoUtils.calculateHmacSHA1(UUID.randomUUID().toString(), UUID.randomUUID().toString());

        String clusterName = "hz-" + tmpClusterKey;
        String clusterPassword = io.jsync.utils.UUID.generate();

        JsonObject clusterConfig = new JsonObject();

        clusterConfig.putString("name", clusterName);
        clusterConfig.putString("password", clusterPassword);
        clusterConfig.putString("role", "default"); // api, job, data, and all
        clusterConfig.putString("host", "0.0.0.0");

        defaultConfig.putObject("cluster", clusterConfig);

        defaultConfig.putBoolean("debug", true);

        return defaultConfig;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy