/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library 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 2.1 of the License, or any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: ClusterDaemonConfigurationManager.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.deployment.clusterd.lib;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

import org.ow2.jonas.deployment.clusterd.ClusterDaemonConfiguration;
import org.ow2.jonas.deployment.clusterd.ClusterDaemonConfigurationException;
import org.ow2.jonas.deployment.clusterd.ClusterDaemonSchemas;
import org.ow2.jonas.deployment.clusterd.rules.ClusterDaemonRuleSet;
import org.ow2.jonas.deployment.clusterd.xml.ClusterDaemon;
import org.ow2.jonas.deployment.common.DeploymentDescException;
import org.ow2.jonas.deployment.common.digester.JDigester;
import org.ow2.jonas.deployment.common.lib.AbsDeploymentDescManager;
import org.ow2.jonas.lib.util.Log;


import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * Description of the cluster daemon configuration
 * @author Benoit Pelletier
 */
public class ClusterDaemonConfigurationManager extends AbsDeploymentDescManager {

    /**
     * Path of the clusterd.xml configuration file
     */
    public static final String CLUSTERD_FILE_NAME = "clusterd.xml";

    /**
     * Digester used to parse clusterd.xml
     */
    private static JDigester clusterDaemonDigester = null;

    /**
     * Rules to parse the application.xml
     */
    private static ClusterDaemonRuleSet clusterDaemonRuleSet = new ClusterDaemonRuleSet();

    /**
     * logger
     */
    private static Logger logger = Log.getLogger(Log.JONAS_CLUSTER_DAEMON);

    /**
     * Flag for parser validation
     */
    private static boolean parsingWithValidation = true;
    /**
     * Private Empty constructor for utility class
     */
    private ClusterDaemonConfigurationManager() {
    }

    /**
     * Get an instance of a ClusterDaemonConfiguration by parsing the clusterd.xml configuration file.
     * @param clusterDaemonFileName used when specific cluster daemon configuration file name has to be used
     * @param classLoaderForCls the classloader for the classes.
     * @return a ClusterDaemonConfiguration instance by parsing the clusterd.xml file
     * @throws ClusterDaemonConfigurationException if the clusterd.xml file is corrupted.
     */
    public static ClusterDaemonConfiguration getClusterDaemonConfiguration(String clusterDaemonFileName, ClassLoader classLoaderForCls)
    throws ClusterDaemonConfigurationException {

        //Input Stream
        InputStream is = null;
        String fileName = null;
        if (clusterDaemonFileName == null) {
        // clusterd.xml in JONAS_BASE/conf
            fileName = System.getProperty("jonas.base") + File.separator
            + "conf" + File.separator
            + CLUSTERD_FILE_NAME;
        } else {
           fileName = clusterDaemonFileName;
        }
        // load clusterd.xml
        File clusterDaemonFile = new File(fileName);
        if (!clusterDaemonFile.exists()) {
            is = classLoaderForCls.getResourceAsStream(CLUSTERD_FILE_NAME);
            if (is == null) {
                throw new ClusterDaemonConfigurationException("Cannot read the " + fileName + " and " + CLUSTERD_FILE_NAME + " is not accessible in the classpath");
            }
        } else {
            try {
                is = new FileInputStream(clusterDaemonFile);
            } catch (Exception e) {
                throw new ClusterDaemonConfigurationException("Cannot read the " + CLUSTERD_FILE_NAME, e);
            }
        }
        ClusterDaemon clusterDaemon = loadClusterDaemon(new InputStreamReader(is), CLUSTERD_FILE_NAME);
        try {
            is.close();
        } catch (IOException e) {
            // Can't close the file
            logger.log(BasicLevel.WARN, "Cannot close InputStream for " + CLUSTERD_FILE_NAME);
        }

        // instantiate the domain map
        ClusterDaemonConfiguration clusterDaemonConfiguration = new ClusterDaemonConfiguration(clusterDaemon);
        return clusterDaemonConfiguration;
    }
    /**
     * Gets the cluster daemon config file. Default is clusterd.xml
     * @param clusterDaemonFileName
     * @return cluster daemon configuration file name.
     */
    public static String getClusterDaemonFileName(String clusterDaemonFileName) {
        String fileName = null;
        if (clusterDaemonFileName == null) {
        // clusterd.xml in JONAS_BASE/conf
        fileName = System.getProperty("jonas.base") + File.separator
            + "conf" + File.separator
            + CLUSTERD_FILE_NAME;
        } else {
           fileName = clusterDaemonFileName;
        }
        return fileName;

    }

    /**
     * Load the clusterd.xml file.
     * @param reader the Reader of the XML file.
     * @param fileName the name of the file (clusterd.xml).
     * @throws ClusterDaemonConfigurationException if the file is corrupted.
     * @return a ClusterDaemon object.
     */
    public static ClusterDaemon loadClusterDaemon(Reader reader, String fileName) throws ClusterDaemonConfigurationException {

        ClusterDaemon clusterDaemon = new ClusterDaemon();
        // Create if domainDigester is null
        if (clusterDaemonDigester == null) {
            try {
                // Create and initialize the digester

                clusterDaemonDigester = new JDigester(clusterDaemonRuleSet, getParsingWithValidation(), true, null,
                        new ClusterDaemonSchemas());
            } catch (DeploymentDescException e) {
                throw new ClusterDaemonConfigurationException(e);
            }
        }

        try {
            clusterDaemonDigester.parse(reader, fileName, clusterDaemon);
        } catch (DeploymentDescException e) {
            throw new ClusterDaemonConfigurationException(e);
        } finally {
            clusterDaemonDigester.push(null);
        }

        return clusterDaemon;
    }

    /**
     * Controls whether the parser is reporting all validity errors.
     * @return if true, all external entities will be read.
     */
    public static boolean getParsingWithValidation() {
        return parsingWithValidation;
    }

    /**
     * Controls whether the parser is reporting all validity errors.
     * @param validation if true, all external entities will be read.
     */
    public static void setParsingWithValidation(boolean validation) {
        ClusterDaemonConfigurationManager.parsingWithValidation = validation;
    }
}