com.ev.launch.Initializer.java Source code

Java tutorial

Introduction

Here is the source code for com.ev.launch.Initializer.java

Source

/*
 * Copyright 2007-2009 Alexander Fabisch
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.ev.launch;

import com.ev.datamodel.Profile;
import com.ev.global.*;
import com.ev.gui.MainFrame;

import org.apache.commons.cli.*;
import org.apache.log4j.*;

/**
 * Initializes the program.
 *
 * @author <a href="mailto:afabisch@tzi.de">Alexander Fabisch</a>
 * @since 0.8.2
 */
public final class Initializer {
    private static final String LOGGER_CONFIG_FILE = "logging.properties";
    private static final String CMD_HELP = "Prints this message.";
    private static final String CMD_PROFILE = "Defines the default profile.";
    private static final String CMD_LOG = "Here you can define the log level, possible values are:\n"
            + " ALL > TRACE > DEBUG > WARN > ERROR > FATAL > OFF.";

    private static CommandLineWrapper cmdWrapper = new CommandLineWrapper();

    private Initializer() {
        throw new AssertionError("Constructur invokation not allowed!");
    }

    public static void initProgram(String[] args) {
        parseCommandLineAndShutdownOnFailure(args);
        initLogging();
        initConfiguration();
        initGUI();
    }

    static void parseCommandLineAndShutdownOnFailure(String[] args) {
        try {
            cmdWrapper.parseCommandLine(args);
        } catch (ParseException e) {
            e.printStackTrace();
        } finally {
            cmdWrapper.printHelpMessageAndShutdownIfNeeded();
        }
    }

    public static void initLogging() {
        if (!Logger.getRootLogger().getAllAppenders().hasMoreElements()) {
            PropertyConfigurator.configure(LOGGER_CONFIG_FILE);
        }
        if (cmdWrapper.isLogLevelDefined()) {
            Logger.getRootLogger().setLevel(cmdWrapper.getLogLevel());
        }
    }

    public static void initConfiguration() {
        if (cmdWrapper.isDefaultProfileDefined()) {
            GlobalConfiguration.init(cmdWrapper.getDefaultProfile());
        } else {
            GlobalConfiguration.init();
        }
    }

    static void initGUI() {
        MainFrame.getInstance();
    }

    static final class CommandLineWrapper {
        private CommandLine cmd;
        private Options options;

        CommandLineWrapper() {
            options = defineCommandLineOptions();
        }

        Options defineCommandLineOptions() {
            Options result = new Options();
            result.addOption("h", "help", false, CMD_HELP);
            result.addOption("p", "profile", true, CMD_PROFILE);
            result.addOption("l", "log-level", true, CMD_LOG);
            return result;
        }

        void parseCommandLine(String args[]) throws ParseException {
            options = defineCommandLineOptions();
            cmd = new PosixParser().parse(options, args);
            printHelpMessageAndShutdownIfNeeded();
        }

        void printHelpMessageAndShutdownIfNeeded() {
            if (cmd == null) {
                throw new IllegalStateException("parseCommandLine() not invoked yet");
            }
            if (cmd.hasOption("h")) {
                new HelpFormatter().printHelp("Energy Consumption", options);
                System.exit(0);
            }
        }

        boolean isLogLevelDefined() {
            return cmd != null && cmd.hasOption("l");
        }

        /**
         * If the log level is defined by the command line ({@link #isLogLevelDefined}), the parsed level
         * will be returned. If parsing fails, the current Level will be returned.
         * @return The parsed log level.
         */
        Level getLogLevel() {
            if (cmd == null) {
                throw new IllegalStateException("parseCommandLine() not invoked yet");
            }
            String logLevelOption = cmd.getOptionValue("l");
            Level defaultLevel = Logger.getRootLogger().getLevel();
            return Level.toLevel(logLevelOption, defaultLevel);
        }

        boolean isDefaultProfileDefined() {
            return cmd != null && cmd.hasOption("p");
        }

        Profile getDefaultProfile() {
            if (cmd == null) {
                throw new IllegalStateException("parseCommandLine() not invoked yet");
            }
            return new Profile(cmd.getOptionValue("p"));
        }

    }

}