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

jaxx.demo.DemoConfig Maven / Gradle / Ivy

There is a newer version: 3.0-alpha-6
Show newest version
/*
 * #%L
 * JAXX :: Demo
 * %%
 * Copyright (C) 2008 - 2014 Code Lutin, Tony Chemit
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of the 
 * License, or (at your option) any later version.
 * 
 * This program 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 Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public 
 * License along with this program.  If not, see
 * .
 * #L%
 */

package jaxx.demo;

import com.google.common.base.Supplier;
import jaxx.demo.component.swing.JButtonDemo;
import jaxx.runtime.JAXXUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdesktop.beans.AbstractBean;
import org.nuiton.config.ApplicationConfig;
import org.nuiton.config.ArgumentsParserException;
import org.nuiton.config.ConfigOptionDef;
import org.nuiton.version.Version;
import org.nuiton.version.Versions;

import javax.swing.KeyStroke;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.Locale;
import java.util.Properties;

import static org.nuiton.i18n.I18n.t;

/**
 * La configuration de l'application.
 *
 * Il s'agit de l'objet partagé par toutes les démos.
 *
 * @author Tony Chemit - [email protected]
 * @since 1.7.2
 */
public class DemoConfig extends AbstractBean implements Supplier {

    /** Logger */
    private static final Log log = LogFactory.getLog(DemoConfig.class);

    /**
     * le fichier de configuration de l'application avec les informations sur
     * le projet (version, license,...) et la configuration des ui (icons, ...)
     */
    public static final String APPLICATION_PROPERTIES = "/jaxx-demo.properties";

    public static final String PROPERTY_FULLSCREEN = "fullscreen";

    public static final String PROPERTY_LOCALE = "locale";

    public static final String PROPERTY_FONT_SIZE = "fontSize";

    public static final String PROPERTY_DEMO_COLOR = "demoColor";

    public static final String PROPERTY_DEMO_CLASS = "demoClass";

    public static final String PROPERTY_LOG_LEVEL = "logLevel";

    public static final String PROPERTY_LOG_PATTERN_LAYOUT = "logPatternLayout";

    public static final String PROPERTY_KEY_OPEN_CONFIG = "keyOpenConfig";

    private final ApplicationConfig applicationConfig;

    @Override
    public ApplicationConfig get() {
        return applicationConfig;
    }

    public DemoConfig(String... args) {

        applicationConfig = new ApplicationConfig();
        applicationConfig.setConfigFileName(Option.CONFIG_FILE.defaultValue);

        // chargement de la configuration interne

        InputStream stream =
                getClass().getResourceAsStream(APPLICATION_PROPERTIES);

        Properties p = new Properties();
        try {
            p.load(stream);
            for (Object k : p.keySet()) {
                String key = k + "";
                Object value = p.get(k);
                if (log.isDebugEnabled()) {
                    log.debug("install properties " + k + " : " + value);
                }
                applicationConfig.setDefaultOption(key, "" + value);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        applicationConfig.loadDefaultOptions(Option.values());

        String sVersion = applicationConfig.getOption("application.version");
        Version version = Versions.valueOf(sVersion);
        if (version.isSnapshot()) {
            // on supprime le stamp de snapshot s'il existe
            version = Versions.removeSnapshot(version);
        }
        applicationConfig.setDefaultOption("version", version.getVersion());

        installSaveUserAction(PROPERTY_FULLSCREEN,
                              PROPERTY_FONT_SIZE,
                              PROPERTY_LOCALE,
                              PROPERTY_DEMO_CLASS,
                              PROPERTY_DEMO_COLOR);

        try {
            applicationConfig.parse(args);
        } catch (ArgumentsParserException e) {
            throw new IllegalStateException("Could not parse configuration", e);
        }
    }

    /**
     * TODO Remove this when the method in ApplicationConfig will be public
     *
     * Action to save user configuration.
     *
     * Add it as a listener of the configuration for a given property.
     *
     * Note: Will not save if {@link ApplicationConfig#isAdjusting()} is {@code true}.
     *
     * @since 2.5.4
     */
    private final PropertyChangeListener saveUserAction =
            new PropertyChangeListener() {

                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (applicationConfig.isAdjusting()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Skip save while adjusting");
                        }
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("Saving configuration fired by property [" +
                                      evt.getPropertyName() + "] at " +
                                      new Date());
                        }
                        saveForUser();
                    }
                }
            };

    /**
     * TODO Remove this when the method in ApplicationConfig will be public
     *
     * Install the {@link #saveUserAction} on givne {@code properties}.
     *
     * @param properties properties on which insalls the saveUserAction
     */
    protected void installSaveUserAction(String... properties) {

        // pass in adjusting state
        applicationConfig.setAdjusting(true);

        try {
            // ajout de tous les listeners pour sauver la configuration
            // lors de la modification des options de la configuration
            for (String propertyKey : properties) {
                // add a listener
                if (log.isDebugEnabled()) {
                    log.debug("register saveUserAction on property [" +
                              propertyKey + ']');
                }
                addPropertyChangeListener(propertyKey, saveUserAction);
            }
        } finally {

            // ok back to normal adjusting state
            applicationConfig.setAdjusting(false);
        }
    }

    public String getCopyrightText() {
        return "Version " + getVersion() + " Codelutin @ 2008-2009";
    }

    /** @return la version de l'application. */
    public Version getVersion() {
        Version option = applicationConfig.getOption(Version.class, "version");
        return option;
    }

    public boolean isFullScreen() {
        boolean result = applicationConfig.getOptionAsBoolean(Option.FULL_SCREEN.key);
        return result;
    }

    public Locale getLocale() {
        Locale result = applicationConfig.getOption(Locale.class, Option.LOCALE.key);
        return result;
    }

    public String getDemoPath() {
        String result = applicationConfig.getOption(Option.DEMO_PATH.key);
        return result;
    }

    public Float getFontSize() {
        Float result = applicationConfig.getOption(Float.class, Option.FONT_SIZE.key);
        return result;
    }

    public Color getDemoColor() {
        Color result = applicationConfig.getOptionAsColor(Option.DEMO_COLOR.key);
        return result;
    }

    public Class getDemoClass() {
        Class result = applicationConfig.getOptionAsClass(Option.DEMO_CLASS.key);
        return result;
    }

    public String getLogLevel() {
        String level = applicationConfig.getOption(Option.LOG_LEVEL.key);
        return level;
    }

    public String getLogPatternLayout() {
        String result = applicationConfig.getOption(Option.LOG_PATTERN_LAYOUT.key);
        return result;
    }

    public KeyStroke getKeyOpenConfig() {
        return applicationConfig.getOptionAsKeyStroke(Option.KEY_OPEN_CONFIG.key);
    }

    public void setFullscreen(boolean fullscreen) {
        applicationConfig.setOption(Option.FULL_SCREEN.key, fullscreen + "");
        firePropertyChange(PROPERTY_FULLSCREEN, null, fullscreen);
    }

    public void setLocale(Locale newLocale) {
        applicationConfig.setOption(Option.LOCALE.key, newLocale.toString());
        firePropertyChange(PROPERTY_LOCALE, null, newLocale);
    }

    public void setFontSize(Float newFontSize) {
        Float oldValue = getFontSize();
        if (log.isDebugEnabled()) {
            log.debug("changing font-size to " + newFontSize);
        }
        applicationConfig.setOption(Option.FONT_SIZE.key, newFontSize.toString());
        firePropertyChange(PROPERTY_FONT_SIZE, oldValue, newFontSize);
    }

    public void setDemoColor(Color color) {
        Color oldValue = getDemoColor();
        if (log.isDebugEnabled()) {
            log.debug("changing demo-color to " + color);
        }
        applicationConfig.setOption(Option.DEMO_COLOR.key, color.toString());
        firePropertyChange(PROPERTY_DEMO_COLOR, oldValue, color);
    }

    public void setDemoClass(Class newClass) {
        Class oldValue = getDemoClass();
        if (log.isDebugEnabled()) {
            log.debug("changing demo-class to " + newClass);
        }
        applicationConfig.setOption(Option.DEMO_CLASS.key, newClass.getName());
        firePropertyChange(PROPERTY_DEMO_CLASS, oldValue, newClass);
    }

    public void setLogLevel(String logLevel) {
        String oldValue = getLogLevel();
        applicationConfig.setOption(Option.LOG_LEVEL.key, logLevel);
        firePropertyChange(PROPERTY_LOG_LEVEL, oldValue, logLevel);
    }

    public void setLogPatternLayout(String logPatternLayout) {
        String oldValue = getLogPatternLayout();
        applicationConfig.setOption(Option.LOG_PATTERN_LAYOUT.key, logPatternLayout);
        firePropertyChange(PROPERTY_LOG_PATTERN_LAYOUT, oldValue, logPatternLayout);
    }

    public void setKeyOpenConfig(KeyStroke keyStroke) {
        KeyStroke oldValue = getKeyOpenConfig();
        applicationConfig.setOption(Option.KEY_OPEN_CONFIG.key, keyStroke.toString());
        firePropertyChange(PROPERTY_KEY_OPEN_CONFIG, oldValue, keyStroke);
    }


    public void saveForUser() {
        // shoudl we never save any conf ?
        applicationConfig.saveForUser();
    }

    public static final String[] DEFAULT_JAXX_PCS = {
            PROPERTY_FULLSCREEN,
            PROPERTY_LOCALE,
            PROPERTY_FONT_SIZE,
            ApplicationConfig.ADJUSTING_PROPERTY
    };

    public void removeJaxxPropertyChangeListener() {
        PropertyChangeListener[] toRemove;
        toRemove = JAXXUtil.findJaxxPropertyChangeListener(
                DEFAULT_JAXX_PCS,
                applicationConfig.getPropertyChangeListeners());
        if (toRemove == null || toRemove.length == 0) {
            return;
        }
        if (log.isDebugEnabled()) {
            log.debug("before remove : " + applicationConfig.getPropertyChangeListeners().length);
            log.debug("toRemove : " + toRemove.length);
        }
        for (PropertyChangeListener listener : toRemove) {
            removePropertyChangeListener(listener);
        }
        if (log.isDebugEnabled()) {
            log.debug("after remove : " + getPropertyChangeListeners().length);
        }
    }

    public URL getApplicationSiteUrl() {
        return applicationConfig.getOptionAsURL("application.site.url");
    }

    public String getIconPath() {
        return applicationConfig.getOption("application.icon.path");
    }

    public String getLicensePath() {
        return applicationConfig.getOption("application.license.path");
    }

    public String getThirdParty() {
        return applicationConfig.getOption("application.third-party.path");
    }

    public String getHelpLocation() {
        return applicationConfig.getOption("application.help.path");
    }

    public String getHelpResourceWithLocale(String value) {
        String result = getHelpLocation() + "/" +
                        getLocale().getLanguage() + "/" +
                        value;
        return result;
    }

    //////////////////////////////////////////////////
    // Toutes les options disponibles
    //////////////////////////////////////////////////

    public enum Option implements ConfigOptionDef {

        CONFIG_FILE(
                ApplicationConfig.CONFIG_FILE_NAME,
                t("jaxxdemo.config.configFileName.description"),
                "jaxxdemo",
                String.class,
                true,
                true),
        FULL_SCREEN(
                "ui.fullscreen",
                t("jaxxdemo.config.ui.fullscreen"),
                "false",
                Boolean.class,
                false,
                false),
        LOCALE(
                "ui." + PROPERTY_LOCALE,
                t("jaxxdemo.config.ui.locale"),
                Locale.FRANCE.toString(),
                Locale.class,
                false,
                false),
        FONT_SIZE(
                "ui." + PROPERTY_FONT_SIZE,
                t("jaxxdemo.config.ui.fontSize"),
                "10f",
                Float.class,
                false,
                false),
        DEMO_COLOR(
                "ui." + PROPERTY_DEMO_COLOR,
                t("jaxxdemo.config.ui.demoColor"),
                "#ffffff",
                Color.class,
                false,
                false),
        DEMO_CLASS(
                "ui." + PROPERTY_DEMO_CLASS,
                t("jaxxdemo.config.ui.demoClass"),
                "java.io.File",
                Class.class,
                false,
                false),

        LOG_LEVEL(
                "ui." + PROPERTY_LOG_LEVEL,
                t("jaxxdemo.config.ui.logLevel"),
                "INFO",
                String.class,
                false,
                false),
        LOG_PATTERN_LAYOUT(
                "ui." + PROPERTY_LOG_PATTERN_LAYOUT,
                t("jaxxdemo.config.ui.logPatternLayout"),
                "%5p [%t] (%F:%L) %M - %m%n",
                String.class,
                false,
                false),
        KEY_OPEN_CONFIG(
                "ui." + PROPERTY_KEY_OPEN_CONFIG,
                t("jaxxdemo.config.ui.keyOpenConfig"),
                "ctrl alt pressed S",
                KeyStroke.class,
                false,
                false),
        DEMO_PATH(
                "ui.demo.path",
                t("jaxxdemo.config.ui.demo.path"),
                "jaxxdemo.tree/jaxxdemo.component.swing/jaxxdemo.component.swing.buttons/" + JButtonDemo.class.getSimpleName(),
                String.class,
                false,
                true);

        public final String key;

        public final String description;

        public String defaultValue;

        public final Class type;

        public boolean _transient;

        public boolean _final;

        Option(String key,
               String description,
               String defaultValue,
               Class type,
               boolean _transient,
               boolean _final) {
            this.key = key;
            this.description = description;
            this.defaultValue = defaultValue;
            this.type = type;
            this._final = _final;
            this._transient = _transient;
        }

        @Override
        public boolean isFinal() {
            return _final;
        }

        @Override
        public void setDefaultValue(String defaultValue) {
            this.defaultValue = defaultValue;
        }

        @Override
        public void setTransient(boolean _transient) {
            this._transient = _transient;
        }

        @Override
        public void setFinal(boolean _final) {
            this._final = _final;
        }

        @Override
        public boolean isTransient() {
            return _transient;
        }

        @Override
        public String getDefaultValue() {
            return defaultValue;
        }

        @Override
        public String getDescription() {
            return description;
        }

        @Override
        public String getKey() {
            return key;
        }

        @Override
        public Class getType() {
            return type;
        }

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy