net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxMySqlLoaderCLI.CFAsteriskSaxMySqlLoaderCLI.java Source code

Java tutorial

Introduction

Here is the source code for net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxMySqlLoaderCLI.CFAsteriskSaxMySqlLoaderCLI.java

Source

// Description: Java 8 XML SAX Loader CLI persisting as MySql 5.5 for CFAsterisk.

/*
 *   Code Factory Asterisk 11 Configuration Model
 *
 *   Copyright (c) 2014-2015 Mark Sobkow
 *   
 *   This program is available as free software under the GNU GPL v3, or
 *   under a commercial license from Mark Sobkow.  For commercial licensing
 *   details, please contact msobkow@sasktel.net.
 *   
 *   Under the terms of the GPL:
 *   
 *      This program is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU 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 Public License for more details.
 *     
 *      You should have received a copy of the GNU General Public License
 *      along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *   
 */

package net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxMySqlLoaderCLI;

import org.apache.log4j.*;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import net.sourceforge.msscodefactory.cflib.v2_3.CFLib.*;
import net.sourceforge.msscodefactory.cfsecurity.v2_4.CFSecurity.*;
import net.sourceforge.msscodefactory.cfinternet.v2_4.CFInternet.*;
import net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsterisk.*;
import net.sourceforge.msscodefactory.cfsecurity.v2_4.CFSecurityObj.*;
import net.sourceforge.msscodefactory.cfinternet.v2_4.CFInternetObj.*;
import net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskObj.*;
import net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskMySql.*;
import net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSaxLoader.*;

public class CFAsteriskSaxMySqlLoaderCLI extends CFAsteriskSaxLoaderCLI {
    private static ICFLibMessageLog log = new CFLibMessageLogWrapper();

    // Constructors

    public CFAsteriskSaxMySqlLoaderCLI() {
        super(log);
    }

    // main() entry point

    public static void main(String args[]) {
        final String S_ProcName = "CFAsteriskSaxMySqlLoaderCLI.main() ";
        initConsoleLog();
        int numArgs = args.length;
        if (numArgs >= 2) {
            String homeDirName = System.getProperty("HOME");
            if (homeDirName == null) {
                homeDirName = System.getProperty("user.home");
                if (homeDirName == null) {
                    log.message(S_ProcName + "ERROR: Home directory not set");
                    return;
                }
            }
            File homeDir = new File(homeDirName);
            if (!homeDir.exists()) {
                log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" does not exist");
                return;
            }
            if (!homeDir.isDirectory()) {
                log.message(S_ProcName + "ERROR: Home directory \"" + homeDirName + "\" is not a directory");
                return;
            }
            CFAsteriskConfigurationFile cFAsteriskConfig = new CFAsteriskConfigurationFile();
            String cFAsteriskConfigFileName = homeDir.getPath() + File.separator + ".cfasteriskmysqlrc";
            cFAsteriskConfig.setFileName(cFAsteriskConfigFileName);
            File cFAsteriskConfigFile = new File(cFAsteriskConfigFileName);
            if (!cFAsteriskConfigFile.exists()) {
                cFAsteriskConfig.setDbServer("127.0.0.1");
                cFAsteriskConfig.setDbPort(3306);
                cFAsteriskConfig.setDbDatabase("CFAst24");
                cFAsteriskConfig.setDbUserName("root");
                cFAsteriskConfig.setDbPassword("edit-me-please");
                cFAsteriskConfig.save();
                log.message(S_ProcName + "INFO: Created configuration file " + cFAsteriskConfigFileName
                        + ", please edit configuration and restart.");
                return;
            }
            if (!cFAsteriskConfigFile.isFile()) {
                log.message(S_ProcName + "ERROR: Proposed configuration file " + cFAsteriskConfigFileName
                        + " is not a file.");
                return;
            }
            if (!cFAsteriskConfigFile.canRead()) {
                log.message(S_ProcName + "ERROR: Permission denied attempting to read configuration file "
                        + cFAsteriskConfigFileName);
                return;
            }
            cFAsteriskConfig.load();
            boolean fastExit = false;
            CFAsteriskClientConfigurationFile cFDbTestClientConfig = new CFAsteriskClientConfigurationFile();
            String cFDbTestClientConfigFileName = homeDir.getPath() + File.separator + ".cfdbtestclientrc";
            cFDbTestClientConfig.setFileName(cFDbTestClientConfigFileName);
            File cFDbTestClientConfigFile = new File(cFDbTestClientConfigFileName);
            if (!cFDbTestClientConfigFile.exists()) {
                String cFDbTestKeyStoreFileName = homeDir.getPath() + File.separator + ".msscfjceks";
                cFDbTestClientConfig.setKeyStore(cFDbTestKeyStoreFileName);
                InetAddress localHost;
                try {
                    localHost = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    localHost = null;
                }
                if (localHost == null) {
                    log.message(S_ProcName + "ERROR: LocalHost is null");
                    return;
                }
                String hostName = localHost.getHostName();
                if ((hostName == null) || (hostName.length() <= 0)) {
                    log.message("ERROR: LocalHost.HostName is null or empty");
                    return;
                }
                String userName = System.getProperty("user.name");
                if ((userName == null) || (userName.length() <= 0)) {
                    log.message("ERROR: user.name is null or empty");
                    return;
                }
                String deviceName = hostName.replaceAll("[^\\w]", "_").toLowerCase() + "-"
                        + userName.replaceAll("[^\\w]", "_").toLowerCase();
                cFDbTestClientConfig.setDeviceName(deviceName);
                cFDbTestClientConfig.save();
                log.message(S_ProcName + "INFO: Created CFAsterisk client configuration file "
                        + cFDbTestClientConfigFileName);
                fastExit = true;
            }
            if (!cFDbTestClientConfigFile.isFile()) {
                log.message(S_ProcName + "ERROR: Proposed client configuration file " + cFDbTestClientConfigFileName
                        + " is not a file.");
                fastExit = true;
            }
            if (!cFDbTestClientConfigFile.canRead()) {
                log.message(S_ProcName + "ERROR: Permission denied attempting to read client configuration file "
                        + cFDbTestClientConfigFileName);
                fastExit = true;
            }
            cFDbTestClientConfig.load();

            if (fastExit) {
                return;
            }

            // Configure logging
            Properties sysProps = System.getProperties();
            sysProps.setProperty("log4j.rootCategory", "WARN");
            sysProps.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

            Logger httpLogger = Logger.getLogger("org.apache.http");
            httpLogger.setLevel(Level.WARN);

            ICFAsteriskSchema cFAsteriskSchema = new CFAsteriskMySqlSchema();
            cFAsteriskSchema.setConfigurationFile(cFAsteriskConfig);
            ICFAsteriskSchemaObj cFAsteriskSchemaObj = new CFAsteriskSchemaObj();
            cFAsteriskSchemaObj.setBackingStore(cFAsteriskSchema);
            CFAsteriskSaxLoaderCLI cli = new CFAsteriskSaxMySqlLoaderCLI();
            CFAsteriskSaxLoader loader = cli.getSaxLoader();
            loader.setSchemaObj(cFAsteriskSchemaObj);
            cFAsteriskSchema.connect();
            String url = args[1];
            if (numArgs >= 5) {
                cli.setClusterName(args[2]);
                cli.setTenantName(args[3]);
                cli.setSecUserName(args[4]);
            } else {
                cli.setClusterName("default");
                cli.setTenantName("system");
                cli.setSecUserName("system");
            }
            loader.setUseCluster(cli.getClusterObj());
            loader.setUseTenant(cli.getTenantObj());
            try {
                cFAsteriskSchema.beginTransaction();
                cFAsteriskSchemaObj.setSecCluster(cli.getClusterObj());
                cFAsteriskSchemaObj.setSecTenant(cli.getTenantObj());
                cFAsteriskSchemaObj.setSecUser(cli.getSecUserObj());
                cFAsteriskSchemaObj.setSecSession(cli.getSecSessionObj());
                CFSecurityAuthorization auth = new CFSecurityAuthorization();
                auth.setSecCluster(cFAsteriskSchemaObj.getSecCluster());
                auth.setSecTenant(cFAsteriskSchemaObj.getSecTenant());
                auth.setSecSession(cFAsteriskSchemaObj.getSecSession());
                cFAsteriskSchemaObj.setAuthorization(auth);
                applyLoaderOptions(loader, args[0]);
                if (numArgs >= 5) {
                    cli.evaluateRemainingArgs(args, 5);
                } else {
                    cli.evaluateRemainingArgs(args, 2);
                }
                loader.parseFile(url);
                cFAsteriskSchema.commit();
                cFAsteriskSchema.disconnect(true);
            } catch (Exception e) {
                log.message(S_ProcName + "EXCEPTION: Could not parse XML file \"" + url + "\": " + e.getMessage());
                e.printStackTrace(System.out);
            } catch (Error e) {
                log.message(S_ProcName + "ERROR: Could not parse XML file \"" + url + "\": " + e.getMessage());
                e.printStackTrace(System.out);
            } finally {
                if (cFAsteriskSchema.isConnected()) {
                    cFAsteriskSchema.rollback();
                    cFAsteriskSchema.disconnect(false);
                }
            }
        } else {
            log.message(S_ProcName
                    + "ERROR: Expected at least two argument specifying the loader options and the name of the XML file to parse.  The first argument may be empty.");
        }
    }

    // Initialize the console log

    protected static void initConsoleLog() {
        Layout layout = new PatternLayout("%d{ISO8601}" // Start with a timestamp
                + " %-5p" // Include the severity
                + " %C.%M" // pkg.class.method()
                + " %F[%L]" // File[lineNumber]
                + ": %m\n"); // Message text
        BasicConfigurator.configure(new ConsoleAppender(layout, "System.out"));
    }

    // Evaluate remaining arguments

    public void evaluateRemainingArgs(String[] args, int consumed) {
        // There are no extra arguments for the RAM "database" instance
        if (args.length > consumed) {
            log.message(
                    "CFAsteriskSaxMySqlLoaderCLI.evaluateRemainingArgs() WARNING No extra arguments are expected for a RAM database instance, but "
                            + Integer.toString(args.length - consumed)
                            + " extra arguments were specified.  Extra arguments ignored.");
        }
    }

}