com.barclays.dfe.fw.DFEWatcher.java Source code

Java tutorial

Introduction

Here is the source code for com.barclays.dfe.fw.DFEWatcher.java

Source

/*
Copyright 2014 the original author or authors
    
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.apache.org/licenses/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 com.barclays.dfe.fw;

import java.awt.EventQueue;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Properties;
import java.util.regex.Pattern;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;

import org.apache.commons.cli.Options;

import org.apache.commons.cli.PosixParser;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.util.StatusPrinter;

// TODO: Auto-generated Javadoc
/**
 * (C) Barclays 2014 - Main Entry point for Watched folder DFE Client
 * 
 * Called by java class loader - parses arguments and kicks off the service.
 */

public class DFEWatcher {

    /** The alpha numeric. */
    Pattern alphaNumeric = Pattern.compile("([^a-zA-z0-9])");

    /** The line. */
    static CommandLine line; // Must be shared across the class

    /** The System running. */
    static int SystemRunning = 0; // Flag to control system status

    /**
     * Main entry point for application.
     *
     * @param args the arguments
     * @throws DFEException the DFE exception
     */

    public static void main(String[] args) throws DFEException {

        Properties properties = System.getProperties();
        String usage;

        //Package pkg = org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.class.getPackage();
        //Package pkg = DFEWatcher.class.getPackage().getImplementationTitle();

        //String ver = pkg.getImplementationVersion();
        String impVer = DFEWatcher.class.getPackage().getImplementationVersion();
        String impTitle = DFEWatcher.class.getPackage().getImplementationTitle();
        String impVendor = DFEWatcher.class.getPackage().getImplementationVendor();
        String specVer = DFEWatcher.class.getPackage().getSpecificationVersion();
        String specTitle = DFEWatcher.class.getPackage().getSpecificationTitle();
        String specVendor = DFEWatcher.class.getPackage().getSpecificationVendor();

        //String ver = pkg.getImplementationVersion();

        usage = "\nProduct: " + impTitle + "\nVersion: " + impVer + "\nVendor:" + impVendor;

        System.out.println("Barclays DTU File Express (DFE) (C) 2014 - Designed and Written by Barclays GTIS");
        System.out.println(usage);

        System.out.printf("DFE is using Java Runtime Version: %s VM: %s Runtime:%s\n\n",
                properties.getProperty("java.version"), properties.getProperty("java.vm.version"),
                properties.getProperty("java.runtime.version"));

        // Run the main class here - start logging here

        // Load the config file - mandatory - should also contain the name of the XML for the props
        DFEProps.getDFEProps();

        Logger logger = LoggerFactory.getLogger(DFEWatcher.class);

        logger.debug("Thread mulitplier {}", DFEProps.DFEThreadMultipler);

        DFEShutdownGraceful gs = new DFEShutdownGraceful();

        gs.attachShutDownHook();

        // create the command line parser - this is the main entry point to detect how we want to invoke the client
        CommandLineParser parser = new PosixParser();

        // create the Options
        Options options = new Options();

        // boolean options
        options.addOption("h", "help", false, "General Help Page - this screen!");
        options.addOption("wm", "WaitMode", false, "Run the DFE Client as a service and watched folder mode");
        options.addOption("j", "TestJython", false, "Test a Jython Script");
        options.addOption("sf", "SourceFile", false, "Test a Jython Script - Source File");
        options.addOption("tf", "TargetFile", false, "Test a Jython Script - Target File");
        options.addOption("lc", "LogConfig", false,
                "Print out the full log, system and DFE configuration for the client");
        options.addOption("v", "version", false, "Build version of this client Major.Minor.Build");
        options.addOption("jetty", "jetty", false, "Start the Jetty Server for testing");

        if (args.length == 0) {
            printUsage("DFEclient" + " (Posix)", options, System.out);
            printHelp(options);
            System.exit(0);
        }

        try {

            int argsfound = 0;

            // parse the command line arguments

            line = parser.parse(options, args, true); // Pass down all the options

            if (line.hasOption("help") && args.length == 1) {

                printUsage("DFEclient" + " (Posix)", options, System.out);
                printHelp(options);
                System.exit(0);
            }

            if (line.hasOption("jetty")) {

                LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
                StatusPrinter.print(lc); // Out put logging capability

                logger.info("System Config {} ", properties);

                //logger.info("DFE Client Config {} ",props.toString());

                Server server = new Server(Integer.parseInt(DFEProps.getDFEAdminPort()));

                ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
                context.setContextPath("/util");
                server.setHandler(context);

                context.addServlet(new ServletHolder(new DFEServlet()), "/*");
                context.addServlet(new ServletHolder(new DFEServlet("stop")), "/start/*");
                context.addServlet(new ServletHolder(new DFEServlet("start")), "/stop/*");
                context.addServlet(new ServletHolder(new DFEServlet("status")), "/status/*");

                try {
                    server.start();
                    server.join();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                logger.debug("Completed");

                System.exit(0);
            }

            if (line.hasOption("lc")) {

                LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
                StatusPrinter.print(lc); // Out put logging capability

                logger.info("System Config {} ", properties);
                DFEProps props = new DFEProps();
                logger.info("DFE Client Config {} ", props.toString());

                System.exit(0);
            }

            // Launch a Jython script to test the engine 
            if (line.hasOption("j")) {

                DFETransferContext DFE = new DFETransferContext();

                String sf = line.getOptionValue("sf");
                String tf = line.getOptionValue("tf");
                logger.info("System Config {} ", properties);
                DFEProps props = new DFEProps();
                logger.info("DFE Client Config {} ", props.toString());

                DFE.setDFESourceFile(sf);
                DFE.setDFETransferMode("put");
                DFE.setDFETargetFileName(tf);

                String scriptName = line.getOptionValue("j");

                argsfound++;
                logger.debug("Jython Script now executed {}", scriptName);

                DFEScriptEngine se = new DFEScriptEngine();

                int result = se.RunPython(scriptName, DFE);

                logger.debug("Result from Jython Script {}", result);

                System.exit(0);
            }

            if (line.hasOption("v")) {

                logger.info(usage);

                System.exit(0);
            }

            //
            // Call this by default - this will be the main folder watcher
            //
            if (line.hasOption("wm")) {

                // Chek the status of the hub - and fail if we dont see it TODO - something better
                try {
                    DFEUtils.DFECheckHub(); // Check the hub - if we get a fauilure - we   
                } catch (Exception e) {

                    System.exit(DFEProps.getDFEErrorReturnCode("DFE_HUB_ATTACH_ERROR"));
                }

                logger.info("All active propserties from DFE.properties");
                DFEProps.printActiveProperties();
                logger.info("End of Property List");

                DFETransferContext dtx = new DFETransferContext();
                DFEStatus stat = new DFEStatus();

                logger.debug("Starting watched folder mode as a service");
                argsfound++;

                try {

                    // Shift the args to the left and remove -wm
                    String[] newArgs;
                    newArgs = new String[args.length - 1];
                    int i;
                    for (i = 0; i < args.length - 1; i++) {

                        newArgs[i] = args[i + 1];

                    }

                    // Start the jetty server if admin port is non zero
                    if (Integer.parseInt(DFEProps.DFEAdminPort) != 0) {
                        // Start the Jetty server here
                        logger.info("Starting Embedded JETTY server on {} /util ", DFEProps.DFEAdminPort);

                        DFEJetty jettyServer = new DFEJetty();

                        EventQueue.invokeLater(jettyServer);

                    }

                    DFEScriptEngine se = new DFEScriptEngine();

                    logger.info("Starting startup.py script");
                    //String scriptName = DFEProps.DFEStartupScript;

                    // Add the startup script location
                    String scriptName = DFEProps.getDFEScriptsDir() + "//" + DFEProps.getDFEStartupScript();
                    //String scriptName = "startup.py";

                    dtx.setDFETransferMode("startup");
                    int result = se.RunPython(scriptName, dtx);

                    //int result=0;

                    if (result != 0) {
                        logger.info("Startup script has terminated the application with error code {}", result);
                        System.exit(0);
                    }

                    logger.info("Registering startup on log");
                    stat.registerStartup(true); // register the startup in log file

                    logger.info("Starting watcher service");

                    DFEMasterRunState.startWatcher(); // Set the state flag
                    try {
                        JFileWatcherService.runWaitMode(newArgs);
                    } catch (Exception e) {
                        System.out.println("Exit from watcher");
                        logger.info("Graceful exit");
                    }

                    logger.info("Terminating Watcher Service");
                    System.exit(0);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    logger.error("Cannot start File Watcher Service: ", e);
                    System.exit(-10);
                }

                logger.debug("Wait mode complete - exiting DFE Java Client");

            }

            if (line.hasOption("im")) {

                logger.debug("Interactive mode complete - exiting DFE Java Client");

            }

            if (argsfound == 0)

            {

                logger.error("Error: Unknown argument");
                printUsage("DFEclient" + " (Posix)", options, System.out);
                printHelp(options);
                System.exit(0);

                System.exit(-8);
            }

        }

        // Catch the argument parser - here - only on a start 
        catch (Exception exp) {
            logger.warn("Error in argument parsing {}", exp.toString());
            System.exit(-9);
        }

    }

    /**
     * Prints the usage.
     *
     * @param applicationName the application name
     * @param options the options
     * @param out the out
     */
    public static void printUsage(final String applicationName, final Options options, final OutputStream out) {
        final PrintWriter writer = new PrintWriter(out);
        final HelpFormatter usageFormatter = new HelpFormatter();
        usageFormatter.printUsage(writer, 80, applicationName, options);
        writer.flush();
    }

    /**
     * Write "help" to the provided OutputStream.
     *
     * @param options the options
     */

    public static void printHelp(final Options options) {

        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DFEclient", options);
    }

    /**
     * Display example application header.
     *
     * @param out the out
     * @out OutputStream to which header should be written.
     */
    public static void displayHeader(final OutputStream out) {
        final String header = "[Apache Commons CLI Example from Dustin's Software Development "
                + "Cogitations and Speculations Blog]\n";
        try {
            out.write(header.getBytes());
        } catch (IOException ioEx) {
            System.out.println(header);
        }
    }

    /**
     * Write the provided number of blank lines to the provided OutputStream.
     * 
     * @param numberBlankLines Number of blank lines to write.
     * @param out OutputStream to which to write the blank lines.
     */
    public static void displayBlankLines(final int numberBlankLines, final OutputStream out) {
        try {
            for (int i = 0; i < numberBlankLines; ++i) {
                out.write("\n".getBytes());
            }
        } catch (IOException ioEx) {
            for (int i = 0; i < numberBlankLines; ++i) {
                System.out.println();
            }
        }
    }

    /**
     * Escape.
     *
     * @param subjectString the subject string
     * @return the string
     */
    private String escape(String subjectString) {
        return alphaNumeric.matcher(subjectString).replaceAll("\\\\$1");
    }

}