jp.co.acroquest.endosnipe.perfdoctor.rule.RuleManager.java Source code

Java tutorial

Introduction

Here is the source code for jp.co.acroquest.endosnipe.perfdoctor.rule.RuleManager.java

Source

/*******************************************************************************
 * ENdoSnipe 5.0 - (https://github.com/endosnipe)
 * 
 * The MIT License (MIT)
 * 
 * Copyright (c) 2012 Acroquest Technology Co.,Ltd.
 * 
 * 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 jp.co.acroquest.endosnipe.perfdoctor.rule;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import jp.co.acroquest.endosnipe.common.logger.ENdoSnipeLogger;
import jp.co.acroquest.endosnipe.perfdoctor.Messages;
import jp.co.acroquest.endosnipe.perfdoctor.PerformanceRule;
import jp.co.acroquest.endosnipe.perfdoctor.exception.RuleCreateException;
import jp.co.acroquest.endosnipe.perfdoctor.rule.def.RuleDef;
import jp.co.acroquest.endosnipe.perfdoctor.rule.def.RuleSetConfig;
import jp.co.acroquest.endosnipe.perfdoctor.rule.def.RuleSetDef;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.SerializationUtils;

/**
 * ???????
 * 
 * @author tanimoto
 * 
 */
public class RuleManager {
    private static final ENdoSnipeLogger LOGGER = ENdoSnipeLogger.getLogger(RuleManager.class);

    /** ?????????? */
    private static final String RULE_CREATE_ERROR = "RuleCreateError";

    /** ??ID */
    public static final String DEFAULT_RULESET_ID = "PERFDOCTOR_DEFAULT";

    /** ????? */
    private static final String DEFAULT_RULESET_NAME = Messages
            .getMessage("endosnipe.perfdoctor.rule.RuleManager.DefaultRuleSetName");

    /** ???? */
    private static final String DEFAULT_RULESET_FILE = "/perfdoctor_rule.xml";

    /** Java???ID */
    public static final String DEFAULT_JAVA_RULESET_ID = "PERFDOCTOR_JAVA_DEFAULT";

    /** Java?????? */
    private static final String DEFAULT_JAVA_RULESET_NAME = Messages
            .getMessage("endosnipe.perfdoctor.rule.RuleManager.DefaultJavaRuleSetName");

    /** Java????? */
    private static final String DEFAULT_JAVA_RULESET_FILE = "/perfdoctor_Java_rule.xml";

    /** DB???ID */
    public static final String DEFAULT_DB_RULESET_ID = "PERFDOCTOR_DB_DEFAULT";

    /** DB?????? */
    private static final String DEFAULT_DB_RULESET_NAME = Messages
            .getMessage("endosnipe.perfdoctor.rule.RuleManager.DefaultDBRuleSetName");

    /** DB????? */
    private static final String DEFAULT_DB_RULESET_FILE = "/perfdoctor_DB_rule.xml";

    /** HP-UX???ID */
    public static final String DEFAULT_HP_UX_RULESET_ID = "PERFDOCTOR_HP_UX_DEFAULT";

    /** HP-UX?????? */
    private static final String DEFAULT_HP_UX_RULESET_NAME = Messages
            .getMessage("endosnipe.perfdoctor.rule.RuleManager.DefaultHPUXRuleSetName");

    /** HP-UX????? */
    private static final String DEFAULT_HP_UX_RULESET_FILE = "/perfdoctor_HP_UX_rule.xml";

    /** ??? */
    private static RuleManager instance__;

    /** ? */
    private final RuleDefAccessor accessor_ = new XmlRuleDefAccessor();

    /** ? */
    private final Set<RuleChangeListener> listenerSet_ = new LinkedHashSet<RuleChangeListener>();

    // ?
    /**
     * ??RuleSetConfig???Map ?RuleSetConfig?ID??RuleSetConfig
     */
    private HashMap<String, RuleSetConfig> ruleSetConfigMap_;

    /**  */
    private List<RuleSetConfig> removeList_;

    // ?
    /**
     * RuleSetDef???Map ?RuleSetDef?ID??RuleSetDef
     */
    private HashMap<String, RuleSetDef> ruleSetMap_;

    /**
     * ??????ID
     */
    private String activeRuleSetId_;

    /**
     * ????ID?
     */
    private Set<String> dirtyRuleSetIds_;

    /**
     * RuleManager??
     * 
     * @return RuleManager
     */
    public static synchronized RuleManager getInstance() {
        if (instance__ == null) {
            instance__ = new RuleManager();
        }
        return instance__;
    }

    /**
     * ??????
     */
    private RuleManager() {
        initialize();
    }

    /**
     * ???
     */
    private void initialize() {
        this.ruleSetMap_ = new HashMap<String, RuleSetDef>();
        this.ruleSetConfigMap_ = loadConfigurations();
        this.activeRuleSetId_ = loadActiveRuleSetId();
        this.dirtyRuleSetIds_ = new HashSet<String>();
        this.removeList_ = Collections.synchronizedList(new ArrayList<RuleSetConfig>());
    }

    /**
     * ? ??ID??????????? ??
     * 
     * @return ???
     */
    private HashMap<String, RuleSetConfig> loadConfigurations() {
        HashMap<String, RuleSetConfig> map = createDefaultConfigMap();

        String[] ruleSetIds = RulePreferenceUtil.loadRuleSetIds();
        for (String ruleSetId : ruleSetIds) {
            RuleSetConfig config = RulePreferenceUtil.loadRuleSet(ruleSetId);
            map.put(ruleSetId, config);
        }

        return map;
    }

    /**
     * ???
     * 
     * @return ??
     */
    private HashMap<String, RuleSetConfig> createDefaultConfigMap() {
        HashMap<String, RuleSetConfig> map = new LinkedHashMap<String, RuleSetConfig>();
        RuleSetConfig config = new RuleSetConfig();
        RuleSetConfig hpUxRuleSetConfig = new RuleSetConfig();
        RuleSetConfig javaRuleSetConfig = new RuleSetConfig();
        RuleSetConfig dbRuleSetConfig = new RuleSetConfig();

        // ??
        config.setId(DEFAULT_RULESET_ID);
        config.setName(DEFAULT_RULESET_NAME);
        config.setFileName(DEFAULT_RULESET_FILE);
        map.put(DEFAULT_RULESET_ID, config);

        // HP_UX??
        hpUxRuleSetConfig.setId(DEFAULT_HP_UX_RULESET_ID);
        hpUxRuleSetConfig.setName(DEFAULT_HP_UX_RULESET_NAME);
        hpUxRuleSetConfig.setFileName(DEFAULT_HP_UX_RULESET_FILE);
        map.put(DEFAULT_HP_UX_RULESET_ID, hpUxRuleSetConfig);

        // java??
        javaRuleSetConfig.setId(DEFAULT_JAVA_RULESET_ID);
        javaRuleSetConfig.setName(DEFAULT_JAVA_RULESET_NAME);
        javaRuleSetConfig.setFileName(DEFAULT_JAVA_RULESET_FILE);
        map.put(DEFAULT_JAVA_RULESET_ID, javaRuleSetConfig);

        // DB??
        dbRuleSetConfig.setId(DEFAULT_DB_RULESET_ID);
        dbRuleSetConfig.setName(DEFAULT_DB_RULESET_NAME);
        dbRuleSetConfig.setFileName(DEFAULT_DB_RULESET_FILE);
        map.put(DEFAULT_DB_RULESET_ID, dbRuleSetConfig);

        return map;
    }

    /**
     * ??ID?? ???????ID?null????
     * ?0??????????ID?
     * 
     * @return ?ID
     */
    private String loadActiveRuleSetId() {
        String str = RulePreferenceUtil.loadActiveRuleSetId();

        if (str == null || str.length() == 0) {
            str = DEFAULT_RULESET_ID;
        }

        return str;
    }

    /**
     * (RuleSetConfig)????
     * 
     * @param config
     *            
     */
    public void addRuleSetConfig(final RuleSetConfig config) {
        this.ruleSetConfigMap_.put(config.getId(), config);
    }

    /**
     * (??)??
     * 
     * @return 
     */
    public RuleSetConfig[] getRuleSetConfigs() {
        RuleSetConfig[] array = new RuleSetConfig[this.ruleSetConfigMap_.size()];
        return this.ruleSetConfigMap_.values().toArray(array);
    }

    /**
     * ????
     * 
     * @param id
     *            ?ID
     */
    public synchronized void removeRuleSetConfig(final String id) {
        RuleSetConfig removeConfig = this.ruleSetConfigMap_.get(id);
        this.removeList_.add(removeConfig);
        this.ruleSetConfigMap_.remove(id);
    }

    /**
     * ??(RuleSetConfig)??
     * 
     * @return ?
     */
    public RuleSetConfig getActiveRuleSetConfig() {
        return this.ruleSetConfigMap_.get(this.activeRuleSetId_);
    }

    /**
     * ??
     * 
     * @param ruleSetConfig
     *            
     */
    public void setActiveRuleSetConfig(final RuleSetConfig ruleSetConfig) {
        this.activeRuleSetId_ = ruleSetConfig.getId();
    }

    /**
     * ???xml???
     */
    @SuppressWarnings("deprecation")
    public synchronized void commit() {
        // ?ID??
        RulePreferenceUtil.saveActiveRuleSetId(this.activeRuleSetId_);

        // ??
        List<String> ruleSetIdList = new ArrayList<String>();
        Collection<RuleSetConfig> ruleSetConfigs = this.ruleSetConfigMap_.values();

        for (RuleSetConfig config : ruleSetConfigs) {
            String id = config.getId();
            if (isDefaultRuleSet(id)) {
                continue;
            }

            RulePreferenceUtil.saveRuleSet(config);

            // 
            ruleSetIdList.add(id);
        }

        // ID??
        String[] ruleSetIds = ruleSetIdList.toArray(new String[ruleSetIdList.size()]);
        RulePreferenceUtil.saveRuleSetIds(ruleSetIds);

        // ??
        // ????????
        for (String ruleId : this.dirtyRuleSetIds_) {
            if (isDefaultRuleSet(ruleId)) {
                continue;
            }

            RuleSetConfig config = this.ruleSetConfigMap_.get(ruleId);
            if (config == null) {
                continue;
            }
            RuleSetDef def = this.ruleSetMap_.get(ruleId);
            this.accessor_.updateRuleSet(def, config.getFileName());
        }

        // ??
        // ?????????
        // ????
        for (RuleSetConfig config : ruleSetConfigs) {
            String id = config.getId();
            if (isDefaultRuleSet(id)) {
                continue;
            }

            File file = new File(config.getFileName());
            if (file.exists() && file.isFile()) {
                continue;
            }

            File parentFile = file.getParentFile();

            if (parentFile != null && parentFile.exists() == false) {
                try {
                    parentFile.mkdirs();
                } catch (SecurityException ex) {
                    LOGGER.error(ex.getMessage(), ex);
                }
            }

            // ?????
            try {
                RuleSetDef defaultRuleSetClone = new RuleSetDef(getRuleSetDef(DEFAULT_RULESET_ID));
                defaultRuleSetClone.setName(config.getName());
                this.accessor_.updateRuleSet(defaultRuleSetClone, config.getFileName());
            } catch (RuleCreateException ex) {
                LOGGER.error(ex.getMessage(), ex);
            }
        }

        // ?
        for (RuleSetConfig config : this.removeList_) {
            File file = new File(config.getFileName());
            if (file.exists()) {
                try {
                    file.delete();
                } catch (SecurityException ex) {
                    LOGGER.error(ex.getMessage(), ex);
                }
            }
        }
        this.removeList_ = Collections.synchronizedList(new ArrayList<RuleSetConfig>());
    }

    /**
     * ??<br>
     * ??ID??????????<br>
     * ???
     * 
     * @param id
     *            ID
     * @return 
     * @throws RuleCreateException
     *             ??????
     */
    public RuleSetDef getRuleSetDef(final String id) throws RuleCreateException {
        RuleSetDef def = this.ruleSetMap_.get(id);
        if (def != null) {
            return def;
        }

        if (id.equals(DEFAULT_RULESET_ID)) {
            def = this.accessor_.findRuleSet(DEFAULT_RULESET_FILE);
            def.setName(this.ruleSetConfigMap_.get(id).getName());
        } else if (id.equals(DEFAULT_HP_UX_RULESET_ID)) {
            def = this.accessor_.findRuleSet(DEFAULT_HP_UX_RULESET_FILE);
            def.setName(this.ruleSetConfigMap_.get(id).getName());
        } else if (id.equals(DEFAULT_JAVA_RULESET_ID)) {
            def = this.accessor_.findRuleSet(DEFAULT_JAVA_RULESET_FILE);
            def.setName(this.ruleSetConfigMap_.get(id).getName());
        } else if (id.equals(DEFAULT_DB_RULESET_ID)) {
            def = this.accessor_.findRuleSet(DEFAULT_DB_RULESET_FILE);
            def.setName(this.ruleSetConfigMap_.get(id).getName());
        } else {
            RuleSetConfig config = this.ruleSetConfigMap_.get(id);
            if (config == null) {
                throw new RuleCreateException("InvalidRuleSetDef", new Object[] { id });
            }
            String fileName = config.getFileName();
            def = this.accessor_.findRuleSet(fileName);
        }

        this.ruleSetMap_.put(id, def);

        return def;
    }

    /**
     * ???<br />
     * 
     * @param orgId
     *             ID
     * @param dstId
     *             ID
     * @param dstName
     *            ????
     * @throws RuleCreateException
     *             ??????
     */
    public void copyRuleSetDef(final String orgId, final String dstId, final String dstName)
            throws RuleCreateException {
        RuleSetDef orgDef = getRuleSetDef(orgId);
        RuleSetDef dstDef = new RuleSetDef(orgDef);
        dstDef.setName(dstName);
        this.ruleSetMap_.put(dstId, dstDef);
    }

    /**
     * ???<br>
     * rollbackRuleSet????????????
     * 
     * @return ??
     */
    public synchronized SerializedRules saveRuleSet() {
        byte[] ruleSetConfigMapData = SerializationUtils.serialize(this.ruleSetConfigMap_);
        byte[] ruleSetMapData = SerializationUtils.serialize(this.ruleSetMap_);
        return new SerializedRules(ruleSetConfigMapData, ruleSetMapData);
    }

    /**
     * ??<br>
     * 
     * @param serializedRules
     *            ??
     */
    @SuppressWarnings("unchecked")
    public synchronized void rollbackRuleSet(final SerializedRules serializedRules) {
        byte[] ruleSetConfigMapData = serializedRules.getRuleSetConfigMapData();
        byte[] ruleMapData = serializedRules.getRuleMapData();
        if (ruleSetConfigMapData == null || ruleSetConfigMapData.length == 0 || ruleMapData == null
                || ruleMapData.length == 0) {
            return;
        }

        this.ruleSetConfigMap_ = (HashMap<String, RuleSetConfig>) SerializationUtils
                .deserialize(ruleSetConfigMapData);
        this.ruleSetMap_ = (HashMap<String, RuleSetDef>) SerializationUtils.deserialize(ruleMapData);
        this.removeList_ = Collections.synchronizedList(new ArrayList<RuleSetConfig>());
    }

    /**
     * ????ID??<br>
     * commit??????????<br>
     * ID??????
     * 
     * @param ruleSetId
     *            ID
     */
    public void addDirty(final String ruleSetId) {
        this.dirtyRuleSetIds_.add(ruleSetId);
    }

    /**
     * ???
     * 
     * @return 
     * @throws RuleCreateException
     *             ????????
     */
    public RuleSetDef getActiveRuleSetDef() throws RuleCreateException {
        return getRuleSetDef(this.activeRuleSetId_);
    }

    /**
     * ???????? ???????????????
     * ????????RuleCreateException?
     * 
     * @return ?
     * @throws RuleCreateException
     *             ???????
     */
    public List<PerformanceRule> getActiveRules() throws RuleCreateException {
        List<PerformanceRule> ruleList = new ArrayList<PerformanceRule>();
        List<String> errorMessageList = new ArrayList<String>();

        RuleSetDef ruleSetDef = getActiveRuleSetDef();

        for (RuleDef ruleDef : ruleSetDef.getRuleDefs()) {
            try {
                PerformanceRule rule = RuleInstanceUtil.createRuleInstance(ruleDef);
                if (rule != null) {
                    ruleList.add(rule);
                }
            } catch (RuleCreateException ex) {
                errorMessageList.add(ex.getMessage());
            }
        }

        if (errorMessageList.size() > 0) {
            String[] messages = errorMessageList.toArray(new String[errorMessageList.size()]);
            throw new RuleCreateException(RULE_CREATE_ERROR, null, messages);
        }

        return ruleList;
    }

    /**
     * ?ID??
     * 
     * @return ID
     */
    public String createUniqueId() {
        String[] ruleSetIds = RulePreferenceUtil.loadRuleSetIds();

        String ruleSetId;
        do {
            ruleSetId = UUID.randomUUID().toString();
        } while (ArrayUtils.contains(ruleSetIds, ruleSetId));

        return ruleSetId;
    }

    /**
     * ??
     */
    public void setActiveRuleSetDefault() {
        this.activeRuleSetId_ = RuleManager.DEFAULT_RULESET_ID;
        RuleSetConfig config = this.ruleSetConfigMap_.get(RuleManager.DEFAULT_RULESET_ID);
        setActiveRuleSetConfig(config);
    }

    /**
     * ??????ID??
     * 
     * @return ?????ID
     */
    public String getActiveRuleSetID() {
        return this.activeRuleSetId_;
    }

    /**
     * ID??????????
     * 
     * @param ruleSetID
     *            ?ID
     */
    public void changeActiveRuleSetByID(final String ruleSetID) {
        RuleSetConfig config = this.ruleSetConfigMap_.get(ruleSetID);

        if (config != null) {
            setActiveRuleSetConfig(config);
        }
    }

    /**
     * ?
     * 
     * @param listener
     *            
     */
    public void addListener(final RuleChangeListener listener) {
        this.listenerSet_.add(listener);
    }

    /**
     * ?
     * 
     * @param listener
     *            
     */
    public void removeListener(final RuleChangeListener listener) {
        this.listenerSet_.remove(listener);
    }

    /**
     * ?
     */
    public void notifyChanged() {
        for (RuleChangeListener listener : this.listenerSet_) {
            listener.ruleChangePerformed();
        }
    }

    /**
     * ?? ID ??????????<br />
     * 
     * @param ruleId
     *             ID
     * @return ??? <code>true</code> ?????? <code>false</code>
     */
    private boolean isDefaultRuleSet(final String ruleId) {
        if (DEFAULT_RULESET_ID.equals(ruleId) || DEFAULT_HP_UX_RULESET_ID.equals(ruleId)
                || DEFAULT_JAVA_RULESET_ID.equals(ruleId) || DEFAULT_DB_RULESET_ID.equals(ruleId)) {
            return true;
        }
        return false;
    }

}