<commit_before>/*
 * Copyright 2006 Wyona
 *
 *  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.wyona.org/licenses/APACHE-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 org.wyona.yanel.core.map;

import java.io.File;
import java.io.IOException;
import java.lang.ClassNotFoundException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Properties;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationUtil;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.configuration.DefaultConfigurationSerializer;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.wyona.commons.io.FileUtil;
import org.wyona.yanel.core.ConfigurationException;
import org.wyona.yanel.core.Yanel;
import org.wyona.yarep.core.RepositoryFactory;

/**
 * Class managing registration of realms (adding, updating, copying, deleting, ...)
 */
public class RealmManager {

    private static Logger log = LogManager.getLogger(RealmManager.class);

    private static String YANEL_CONFIGURATION_FILE = Yanel.DEFAULT_CONFIGURATION_FILE;

    public static String REALM_DEFAULT_CONFIG_NAME = "realm.xml";

    private URL propertiesURL;
    private File yanelConfigFile;

    private File _realmsConfigFile; 

    private LinkedHashMap _realms = new LinkedHashMap();
    private Realm rootRealm = null;

    /**
     *
     */
    public RealmManager() throws ConfigurationException {
        this(Yanel.DEFAULT_CONFIGURATION_FILE_XML);
    }

    /**
     * Initializes realms
     * @param yanelConfigurationFilename Yanel configuration filename, either 'yanel.xml' or 'yanel.properties'
     */
    public RealmManager(String yanelConfigurationFilename) throws ConfigurationException {
        log.debug("Yanel Configuration Filename: " + yanelConfigurationFilename);
        File realmsConfigFile = getRealmsConfigFile(yanelConfigurationFilename);
        // INFO: Set private realms config file
        _realmsConfigFile = realmsConfigFile;
        log.debug("Realms Configuration: " + realmsConfigFile);
        readRealms(realmsConfigFile);
    }

    /**
     * Get realms configuration file (either based on yanel configuration or based on environment variable)
     * @param yanelConfigurationFilename Yanel configuration filename, either 'yanel.xml' or 'yanel.properties'
     * @return Realms configuration file, either something like /usr/local/tomcat/webapps/yanel/WEB-INF/classes/realms.xml or /home/foo/realms.xml
     */
    private File getRealmsConfigFile(String yanelConfigurationFilename) throws ConfigurationException {

        // 1.) Getting realms.xml from environment variable YANEL_REALMS_HOME
        java.util.Map<String, String> env = System.getenv();
        for (java.util.Map.Entry envEntry : env.entrySet()) {
            if (((String) envEntry.getKey()).equals("YANEL_REALMS_HOME")) {
                File yanelRealmsHome = new File((String) envEntry.getValue());
                if (yanelRealmsHome.isDirectory()) {
                    File envRealmsConfigFile = new File(yanelRealmsHome, "realms.xml");
                    if (envRealmsConfigFile.isFile()) {
                        log.warn("Use environment variable YANEL_REALMS_HOME '" + yanelRealmsHome + "' in order to load realms configuration.");
                        return envRealmsConfigFile;
                    } else {
                        log.warn("No realms configuration found: " + envRealmsConfigFile.getAbsolutePath());
                    }
                    break;
                }
            }
        }


        // 2.) Getting realms.xml from user home directory
        log.debug("User home directory: " + System.getProperty("user.home"));
        File userHomeRealmsConfigFile = new File(System.getProperty("user.home"), "realms.xml");
        if (userHomeRealmsConfigFile.isFile()) {
            log.warn("Use user home directory: " + System.getProperty("user.home"));
            return userHomeRealmsConfigFile;
        } else {
            log.warn("No realms configuration found within user home directory: " + userHomeRealmsConfigFile.getAbsolutePath());
        }


        // 3.) Getting realms.xml from http://tomcat.apache.org/tomcat-5.5-doc/config/context.html#Environment_Entries
        String envEntryPath = "java:comp/env/yanel/realms-config-file";
        try {
            javax.naming.InitialContext ic = new javax.naming.InitialContext();
            if (ic.lookup(envEntryPath) != null) {
                log.warn("realms.xml set as environment entry: " + (String) ic.lookup(envEntryPath));
                return new File((String) ic.lookup(envEntryPath));
            } else {
                log.info("No enviroment entry '" + envEntryPath + "' set.");
            }
        } catch (Exception e) {
            log.info("No enviroment entry '" + envEntryPath + "' set.");
        }


        // 4.) Getting realms.xml from yanel.xml<commit_msg>hidden folder implemented<commit_after>/*
 * Copyright 2006 Wyona
 *
 *  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.wyona.org/licenses/APACHE-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 org.wyona.yanel.core.map;

import java.io.File;
import java.io.IOException;
import java.lang.ClassNotFoundException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.util.LinkedHashMap;
import java.util.Properties;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import org.apache.avalon.framework.configuration.Configuration;
import org.apache.avalon.framework.configuration.ConfigurationUtil;
import org.apache.avalon.framework.configuration.DefaultConfigurationBuilder;
import org.apache.avalon.framework.configuration.DefaultConfigurationSerializer;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.wyona.commons.io.FileUtil;
import org.wyona.yanel.core.ConfigurationException;
import org.wyona.yanel.core.Yanel;
import org.wyona.yarep.core.RepositoryFactory;

/**
 * Class managing registration of realms (adding, updating, copying, deleting, ...)
 */
public class RealmManager {

    private static Logger log = LogManager.getLogger(RealmManager.class);

    private static String YANEL_CONFIGURATION_FILE = Yanel.DEFAULT_CONFIGURATION_FILE;

    public static String REALM_DEFAULT_CONFIG_NAME = "realm.xml";

    private URL propertiesURL;
    private File yanelConfigFile;

    private File _realmsConfigFile; 

    private LinkedHashMap _realms = new LinkedHashMap();
    private Realm rootRealm = null;

    /**
     *
     */
    public RealmManager() throws ConfigurationException {
        this(Yanel.DEFAULT_CONFIGURATION_FILE_XML);
    }

    /**
     * Initializes realms
     * @param yanelConfigurationFilename Yanel configuration filename, either 'yanel.xml' or 'yanel.properties'
     */
    public RealmManager(String yanelConfigurationFilename) throws ConfigurationException {
        log.debug("Yanel Configuration Filename: " + yanelConfigurationFilename);
        File realmsConfigFile = getRealmsConfigFile(yanelConfigurationFilename);
        // INFO: Set private realms config file
        _realmsConfigFile = realmsConfigFile;
        log.debug("Realms Configuration: " + realmsConfigFile);
        readRealms(realmsConfigFile);
    }

    /**
     * Get realms configuration file (either based on yanel configuration or based on environment variable)
     * @param yanelConfigurationFilename Yanel configuration filename, either 'yanel.xml' or 'yanel.properties'
     * @return Realms configuration file, either something like /usr/local/tomcat/webapps/yanel/WEB-INF/classes/realms.xml or /home/foo/realms.xml
     */
    private File getRealmsConfigFile(String yanelConfigurationFilename) throws ConfigurationException {

        // 1.) Getting realms.xml from environment variable YANEL_REALMS_HOME
        java.util.Map<String, String> env = System.getenv();
        for (java.util.Map.Entry envEntry : env.entrySet()) {
            if (((String) envEntry.getKey()).equals("YANEL_REALMS_HOME")) {
                File yanelRealmsHome = new File((String) envEntry.getValue());
                if (yanelRealmsHome.isDirectory()) {
                    File envRealmsConfigFile = new File(yanelRealmsHome, "realms.xml");
                    if (envRealmsConfigFile.isFile()) {
                        log.warn("Use environment variable YANEL_REALMS_HOME '" + yanelRealmsHome + "' in order to load realms configuration.");
                        return envRealmsConfigFile;
                    } else {
                        log.warn("No realms configuration found: " + envRealmsConfigFile.getAbsolutePath());
                    }
                    break;
                }
            }
        }


        // 2.) Getting realms.xml from user home directory or rather hidden yanel directory inside user home directory
        log.debug("User home directory: " + System.getProperty("user.home"));

        File userHomeDotYanelRealmsConfigFile = new File(System.getProperty("user.home") + "/.yanel", "realms.xml");
        if (userHomeDotYanelRealmsConfigFile.isFile()) {
            log.warn("DEBUG: Use hidden folder inside user home directory: " + userHomeDotYanelRealmsConfigFile.getParentFile().getAbsolutePath());
            return userHomeDotYanelRealmsConfigFile;
        } else {
            log.warn("No realms configuration found inside hidden folder at user home directory: " + userHomeDotYanelRealmsConfigFile.getAbsolutePath());
        }

        File userHomeRealmsConfigFile = new File(System.getProperty("user.home"), "realms.xml");
        if (userHomeRealmsConfigFile.isFile()) {
            log.warn("DEPRECATED: Use user home directory: " + System.getProperty("user.home"));
            return userHomeRealmsConfigFile;
        } else {
            log.warn("No realms configuration found within user home directory: " + userHomeRealmsConfigFile.getAbsolutePath());
        }


        // 3.) Getting realms.xml from http://tomcat.apache.org/tomcat-5.5-doc/config/context.html#Environment_Entries
        String envEntryPath = "java:comp/env/yanel/realms-config-file";
        try {
            javax.naming.InitialContext ic = new javax.naming.InitialContext();
            if (ic.lookup(envEntryPath) != null) {
                log.warn("realms.xml set as environment entry: " + (String) ic.lookup(envEntryPath));
                return new File((String) ic.lookup(envEntryPath));
            } else {
                log.info("No enviroment entry '" + envEntryPath + "' set.");
            }
        } catch (Exception e) {
            log.info("No enviroment entry '" + envEntryPath + "' set.");
        }


        // 4.) Getting realms.xml from yanel.xml
{'fraction_non_alphanumeric': 0.09741784037558686, 'fraction_numerical': 0.0031857813547954395, 'mean_word_length': 3.0084005376344085, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 27}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1214308', 'n_tokens_mistral': 3270, 'n_tokens_neox': 3236, 'n_words': 809}