ren.hankai.cordwood.core.util.RuntimeVariables.java Source code

Java tutorial

Introduction

Here is the source code for ren.hankai.cordwood.core.util.RuntimeVariables.java

Source

/*******************************************************************************
 * Copyright (C) 2018 hankai
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ******************************************************************************/

package ren.hankai.cordwood.core.util;

import org.apache.commons.io.output.FileWriterWithEncoding;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ren.hankai.cordwood.core.Preferences;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * ?????????
 *
 * @author hankai
 * @version 1.0.0
 * @since Jun 21, 2016 4:12:14 PM
 */
public final class RuntimeVariables {

    private static final Logger logger = LoggerFactory.getLogger(RuntimeVariables.class);
    private static Map<String, String> variables = null;
    /**
     * ????
     */
    public static final String savePath = Preferences.getDataDir() + "/runtime.properties";
    // 
    private static long cacheSeconds = 60 * 2;
    // ??
    private static long lastScanTimestamp = -1;

    private RuntimeVariables() {
    }

    /**
     * ????
     *
     * @return ???
     * @author hankai
     * @since Nov 22, 2018 3:46:56 PM
     */
    private static Map<String, String> getVariables() {
        // ??
        if (cacheSeconds > 0) {
            final long timestamp = System.currentTimeMillis() / 1000;
            if ((timestamp - lastScanTimestamp) > cacheSeconds) {
                variables = null;
            }
        }
        if (variables == null) {
            variables = new HashMap<>();
            try {
                final Properties props = new Properties();
                final File file = getVariablesFile();
                if (file.exists()) {
                    props.load(new FileReader(file));
                    final Set<String> keyset = props.stringPropertyNames();
                    for (final String key : keyset) {
                        variables.put(key, props.getProperty(key));
                    }
                }
                lastScanTimestamp = System.currentTimeMillis() / 1000;
            } catch (final FileNotFoundException ex) {
                logger.error(String.format("Runtime variables file \"%s\" not found!", savePath), ex);
            } catch (final IOException ex) {
                logger.error(String.format("Failed to load runtime variables from file \"%s\"!", savePath), ex);
            }
        }
        return variables;
    }

    /**
     * ????
     *
     * @param seconds 
     * @author hankai
     * @since Apr 25, 2017 5:13:45 PM
     */
    public static void setCacheSeconds(long seconds) {
        seconds = (seconds > (60 * 60 * 24)) ? 60 * 60 * 24 : seconds; // 1
        cacheSeconds = seconds;
    }

    /**
     * ?????
     *
     * @return ??
     * @author hankai
     * @since Apr 25, 2017 5:11:37 PM
     */
    public static File getVariablesFile() {
        return new File(savePath);
    }

    /**
     * ????
     *
     * @author hankai
     * @since Oct 25, 2016 10:45:14 AM
     */
    public static void saveVariables() {
        if ((variables == null) || variables.isEmpty()) {
            return;
        }
        try {
            final String header = "These are the runtime variables for the application, do not change it manually!";
            final Properties props = new Properties();
            props.putAll(variables);
            props.store(new FileWriterWithEncoding(savePath, "UTF-8"), header);
        } catch (final IOException ex) {
            logger.error(String.format("Failed to save runtime variables to file \"%s\"!", savePath), ex);
        }
    }

    public static void setVariable(String key, String value) {
        getVariables().put(key, value);
    }

    /**
     * ????
     *
     * @param key ??
     * @return ??
     * @author hankai
     * @since Apr 28, 2017 7:16:18 PM
     */
    public static String getVariable(String key) {
        return getVariables().get(key);
    }

    /**
     * ? boolean ??
     *
     * @param key ????
     * @return ??
     * @author hankai
     * @since Oct 25, 2016 10:45:33 AM
     */
    public static boolean getBool(String key) {
        final String value = getVariable(key);
        try {
            return Boolean.parseBoolean(value);
        } catch (final Exception ex) {
            logger.warn(String.format("Failed to get boolean variable \"%s\"", key), ex);
        }
        return false;
    }

    /**
     * ???
     *
     * @param key ????
     * @return ??
     * @author hankai
     * @since Oct 25, 2016 10:46:11 AM
     */
    public static int getInt(String key) {
        final String value = getVariable(key);
        try {
            return Integer.parseInt(value);
        } catch (final Exception ex) {
            logger.warn(String.format("Failed to get int variable \"%s\"", key), ex);
        }
        return 0;
    }

    /**
     * ???????????
     *
     * @return ??
     * @author hankai
     * @since Oct 25, 2016 10:46:40 AM
     */
    public static Map<String, String> getAllVariables() {
        final Map<String, String> map = new HashMap<>();
        map.putAll(variables);
        return map;
    }

    /**
     * ??
     *
     * @param map ??
     * @author hankai
     * @since Oct 25, 2016 10:46:54 AM
     */
    public static void setAllVariables(Map<String, String> map) {
        if ((map != null) && (map.size() > 0)) {
            variables = map;
        }
    }

    /**
     * ????
     *
     * @author hankai
     * @since Apr 28, 2017 7:17:20 PM
     */
    public static void reloadVariables() {
        variables = null;
        getVariables();
    }

    /**
     * ???
     *
     * @param key ????
     * @author hankai
     * @since Sep 5, 2017 5:45:44 PM
     */
    public static void removeVariable(String key) {
        variables.remove(key);
    }
}