org.dragoneronca.util.Configuration.java Source code

Java tutorial

Introduction

Here is the source code for org.dragoneronca.util.Configuration.java

Source

/*
 * Copyright Paolo Dragone 2014.
 * Copyright Alessandro Ronca 2014.
 *
 * This file is part of Wiktionary Ontology.
 *
 * Wiktionary Ontology is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Wiktionary Ontology is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Wiktionary Ontology. If not, see <http://www.gnu.org/licenses/>.
 */

package org.dragoneronca.util;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Static configuration class for the Wol project.
 * <p/>
 * Main tasks: <ul> <li> gives you the value of the variable <tt>environment</tt></li> <li> gives
 * you all the configuration files</li> </ul>
 *
 * @author Paolo Dragone
 * @author Alessandro Ronca
 */
public class Configuration {

    private static final String PRODUCT_LOG_CONFIG = "log4j.properties";
    private static final String DEVELOP_LOG_CONFIG = "log4j-debug.properties";

    private static final Pattern CONF_PATTERN = Pattern.compile("(?:(?<name>.+)\\.properties)");

    private static final Logger LOG = Logger.getLogger(Configuration.class);

    private static final Hashtable<String, PropertiesConfiguration> configurationMap = new Hashtable<>();

    private static final String ENV_CONF = "environment";
    private static final String ENV_VAR = "environment";
    private static Environment environment;

    /**
     * Init logger and configuration properties.
     * <p/>
     * The configuration directory should contain at least: <ul> <li>file
     * &quot;environment.properties&quot;</li> <li>file &quot;log4j.properties&quot;</li> <li>file
     * &quot;log4j-debug.properties&quot;</li> </ul>
     *
     * @param confDir path to the configuration directory
     */
    public Configuration(Path confDir) {

        String productLogConfig = confDir.toAbsolutePath().toString() + File.separator + PRODUCT_LOG_CONFIG;
        String developLogConfig = confDir.toAbsolutePath().toString() + File.separator + DEVELOP_LOG_CONFIG;

        // default configuration for log4j
        LogManager.resetConfiguration();
        if (Files.exists(Paths.get(productLogConfig))) {
            PropertyConfigurator.configure(productLogConfig);
        } else {
            BasicConfigurator.configure();
            Logger.getRootLogger().setLevel(Level.INFO);
            LOG.warn("Impossible to load configuration for log4j: " + productLogConfig);
            LOG.warn("Using basic configuration for log4j");
        }

        try {
            Files.walkFileTree(confDir, new SimpleFileVisitor<Path>() {

                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Matcher confMatcher = CONF_PATTERN.matcher(file.getFileName().toString());
                    if (confMatcher.matches()) {

                        LOG.info("Loading configuration file: " + file.toAbsolutePath().toString());

                        try {
                            configurationMap.put(confMatcher.group("name"),
                                    new PropertiesConfiguration(file.toAbsolutePath().toString()));
                        } catch (ConfigurationException e) {
                            LOG.warn("Exception while loading: " + file.getFileName().toString());
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }

            });
        } catch (IOException e) {
            LOG.error("Impossible to load configuration files", e);
            System.exit(-1);
        }

        PropertiesConfiguration envConf = configurationMap.get(ENV_CONF);
        if (envConf != null) {
            String envVar = envConf.getString(ENV_VAR);
            if (envVar != null) {
                Environment tmpEnv = Environment.getByName(envVar);
                if (tmpEnv != null) {
                    environment = tmpEnv;
                } else {
                    environment = Environment.PRODUCTION;
                    LOG.warn("Invalid value for the environment variable in configuration file: "
                            + "config/environment.properties "
                            + "- Only \"development\" and \"production\" are allowed");
                }
            } else {
                environment = Environment.PRODUCTION;
                LOG.warn("Missing environment variable in configuration file: " + "config/environment.properties");
            }
        } else {
            environment = Environment.PRODUCTION;
            LOG.warn("Missing environment configuration file, create: " + "config/environment.properties");
        }

        // advanced logger configuration
        if (environment.equals(Environment.DEVELOPMENT)) {
            LogManager.resetConfiguration();
            if (Files.exists(Paths.get(developLogConfig))) {
                PropertyConfigurator.configure(developLogConfig);
            } else {
                LOG.warn("Impossible to load development configuration for log4j: " + developLogConfig);
                LOG.warn("Using the previous configuration for log4j");
            }
        }
    }

    /**
     * Init logger and configuration properties.
     */

    @SuppressWarnings("unused")
    private void configureLog4j() {

        Logger rootLogger = Logger.getRootLogger();
        rootLogger.getLoggerRepository().resetConfiguration();

        PatternLayout logFormat = new PatternLayout("[ %-5p ] %d{HH:mm:ss} %c{1} - %m%n");

        // console appender
        ConsoleAppender console = new ConsoleAppender();

        console.setName("ConsoleLogger");
        console.setLayout(logFormat);
        console.setThreshold((environment.equals(Environment.DEVELOPMENT) ? Level.DEBUG : Level.INFO));
        console.activateOptions();

        rootLogger.addAppender(console);

        // file appender
        FileAppender fa = new FileAppender();
        fa.setName("InfoFileLogger");
        fa.setFile("Wol.log");
        fa.setLayout(logFormat);
        fa.setThreshold(Level.INFO);
        fa.setEncoding("UTF-8");
        fa.setAppend(true);
        fa.activateOptions();

        rootLogger.addAppender(fa);

        if (environment.equals(Environment.DEVELOPMENT)) {
            // debug file appender
            FileAppender debugFa = new FileAppender();
            debugFa.setName("DebugFileLogger");
            debugFa.setFile("Wol-debug.log");
            debugFa.setLayout(logFormat);
            debugFa.setThreshold(Level.DEBUG);
            debugFa.setEncoding("UTF-8");
            debugFa.setAppend(true);
            debugFa.activateOptions();

            rootLogger.addAppender(debugFa);
        }
    }

    /**
     * Get the environment variable.
     *
     * @return the value of the environment variable.
     */
    public Environment getEnvironment() {
        return environment;
    }

    /**
     * Get a specific configuration by identifier.
     *
     * @param name is the identifier, e.g. the file &quot;foo.properties&quot; has identifier
     *             &quot;foo&quot;.
     * @return a configuration.
     */
    public PropertiesConfiguration getConfiguration(String name) {
        return configurationMap.get(name);
    }

    /**
     * Values for the variable environment.
     */
    public static enum Environment {
        DEVELOPMENT("development"), PRODUCTION("production");

        private String name;

        private Environment(String name) {
            this.name = name;
        }

        public static Environment getByName(String name) {
            Environment[] values = Environment.values();
            String lowerName = name.toLowerCase();
            for (Environment value : values) {
                if (value.name.equals(lowerName)) {
                    return value;
                }
            }
            return null;
        }
    }
}