Example usage for java.lang String split

List of usage examples for java.lang String split

Introduction

In this page you can find the example usage for java.lang String split.

Prototype

public String[] split(String regex) 

Source Link

Document

Splits this string around matches of the given regular expression.

Usage

From source file:com.oltpbenchmark.DBWorkload.java

/**
 * @param args//w  ww  .j  av  a 2s  . c om
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    // Initialize log4j
    String log4jPath = System.getProperty("log4j.configuration");
    if (log4jPath != null) {
        org.apache.log4j.PropertyConfigurator.configure(log4jPath);
    } else {
        throw new RuntimeException("Missing log4j.properties file");
    }

    // create the command line parser
    CommandLineParser parser = new PosixParser();
    XMLConfiguration pluginConfig = null;
    try {
        pluginConfig = new XMLConfiguration("config/plugin.xml");
    } catch (ConfigurationException e1) {
        LOG.info("Plugin configuration file config/plugin.xml is missing");
        e1.printStackTrace();
    }
    pluginConfig.setExpressionEngine(new XPathExpressionEngine());
    Options options = new Options();
    options.addOption("b", "bench", true,
            "[required] Benchmark class. Currently supported: " + pluginConfig.getList("/plugin//@name"));
    options.addOption("c", "config", true, "[required] Workload configuration file");
    options.addOption(null, "create", true, "Initialize the database for this benchmark");
    options.addOption(null, "clear", true, "Clear all records in the database for this benchmark");
    options.addOption(null, "load", true, "Load data using the benchmark's data loader");
    options.addOption(null, "execute", true, "Execute the benchmark workload");
    options.addOption(null, "runscript", true, "Run an SQL script");
    options.addOption(null, "upload", true, "Upload the result");

    options.addOption("v", "verbose", false, "Display Messages");
    options.addOption("h", "help", false, "Print this help");
    options.addOption("s", "sample", true, "Sampling window");
    options.addOption("ss", false, "Verbose Sampling per Transaction");
    options.addOption("o", "output", true, "Output file (default System.out)");
    options.addOption("d", "directory", true,
            "Base directory for the result files, default is current directory");
    options.addOption("t", "timestamp", false,
            "Each result file is prepended with a timestamp for the beginning of the experiment");
    options.addOption(null, "histograms", false, "Print txn histograms");
    options.addOption(null, "dialects-export", true, "Export benchmark SQL to a dialects file");

    // parse the command line arguments
    CommandLine argsLine = parser.parse(options, args);
    if (argsLine.hasOption("h")) {
        printUsage(options);
        return;
    } else if (argsLine.hasOption("c") == false) {
        LOG.error("Missing Configuration file");
        printUsage(options);
        return;
    } else if (argsLine.hasOption("b") == false) {
        LOG.fatal("Missing Benchmark Class to load");
        printUsage(options);
        return;
    }

    // If an output directory is used, store the information
    String outputDirectory = "";
    if (argsLine.hasOption("d")) {
        outputDirectory = argsLine.getOptionValue("d");
    }

    String timestampValue = "";
    if (argsLine.hasOption("t")) {
        timestampValue = String.valueOf(TimeUtil.getCurrentTime().getTime()) + "_";
    }

    //       -------------------------------------------------------------------
    //        GET PLUGIN LIST
    //       -------------------------------------------------------------------

    String plugins = argsLine.getOptionValue("b");

    String[] pluginList = plugins.split(",");
    List<BenchmarkModule> benchList = new ArrayList<BenchmarkModule>();

    // Use this list for filtering of the output
    List<TransactionType> activeTXTypes = new ArrayList<TransactionType>();

    String configFile = argsLine.getOptionValue("c");
    XMLConfiguration xmlConfig = new XMLConfiguration(configFile);
    xmlConfig.setExpressionEngine(new XPathExpressionEngine());
    int lastTxnId = 0;

    for (String plugin : pluginList) {

        // ----------------------------------------------------------------
        // WORKLOAD CONFIGURATION
        // ----------------------------------------------------------------

        String pluginTest = "";

        pluginTest = "[@bench='" + plugin + "']";

        WorkloadConfiguration wrkld = new WorkloadConfiguration();
        wrkld.setBenchmarkName(plugin);
        wrkld.setXmlConfig(xmlConfig);
        wrkld.setDBType(DatabaseType.get(xmlConfig.getString("dbtype")));
        wrkld.setDBDriver(xmlConfig.getString("driver"));
        wrkld.setDBConnection(xmlConfig.getString("DBUrl"));
        wrkld.setDBName(xmlConfig.getString("DBName"));
        wrkld.setDBUsername(xmlConfig.getString("username"));
        wrkld.setDBPassword(xmlConfig.getString("password"));
        int terminals = xmlConfig.getInt("terminals[not(@bench)]", 0);
        terminals = xmlConfig.getInt("terminals" + pluginTest, terminals);
        wrkld.setTerminals(terminals);
        wrkld.setIsolationMode(xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE"));
        wrkld.setScaleFactor(xmlConfig.getDouble("scalefactor", 1.0));
        wrkld.setRecordAbortMessages(xmlConfig.getBoolean("recordabortmessages", false));

        int size = xmlConfig.configurationsAt("/works/work").size();
        for (int i = 1; i < size + 1; i++) {
            SubnodeConfiguration work = xmlConfig.configurationAt("works/work[" + i + "]");
            List<String> weight_strings;

            // use a workaround if there multiple workloads or single
            // attributed workload
            if (pluginList.length > 1 || work.containsKey("weights[@bench]")) {
                weight_strings = get_weights(plugin, work);
            } else {
                weight_strings = work.getList("weights[not(@bench)]");
            }
            int rate = 1;
            boolean rateLimited = true;
            boolean disabled = false;

            // can be "disabled", "unlimited" or a number
            String rate_string;
            rate_string = work.getString("rate[not(@bench)]", "");
            rate_string = work.getString("rate" + pluginTest, rate_string);
            if (rate_string.equals(RATE_DISABLED)) {
                disabled = true;
            } else if (rate_string.equals(RATE_UNLIMITED)) {
                rateLimited = false;
            } else if (rate_string.isEmpty()) {
                LOG.fatal(String.format("Please specify the rate for phase %d and workload %s", i, plugin));
                System.exit(-1);
            } else {
                try {
                    rate = Integer.parseInt(rate_string);
                    if (rate < 1) {
                        LOG.fatal("Rate limit must be at least 1. Use unlimited or disabled values instead.");
                        System.exit(-1);
                    }
                } catch (NumberFormatException e) {
                    LOG.fatal(String.format("Rate string must be '%s', '%s' or a number", RATE_DISABLED,
                            RATE_UNLIMITED));
                    System.exit(-1);
                }
            }
            Phase.Arrival arrival = Phase.Arrival.REGULAR;
            String arrive = work.getString("@arrival", "regular");
            if (arrive.toUpperCase().equals("POISSON"))
                arrival = Phase.Arrival.POISSON;

            int activeTerminals;
            activeTerminals = work.getInt("active_terminals[not(@bench)]", terminals);
            activeTerminals = work.getInt("active_terminals" + pluginTest, activeTerminals);
            if (activeTerminals > terminals) {
                System.out.println("Configuration error in work " + i + ": number of active terminals" + ""
                        + "is bigger than the total number of terminals");
                System.exit(-1);
            }
            wrkld.addWork(work.getInt("/time"), rate, weight_strings, rateLimited, disabled, activeTerminals,
                    arrival);
        } // FOR

        int numTxnTypes = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/transactiontype")
                .size();
        if (numTxnTypes == 0 && pluginList.length == 1) {
            //if it is a single workload run, <transactiontypes /> w/o attribute is used
            pluginTest = "[not(@bench)]";
            numTxnTypes = xmlConfig.configurationsAt("transactiontypes" + pluginTest + "/transactiontype")
                    .size();
        }
        wrkld.setNumTxnTypes(numTxnTypes);

        // CHECKING INPUT PHASES
        int j = 0;
        for (Phase p : wrkld.getAllPhases()) {
            j++;
            if (p.getWeightCount() != wrkld.getNumTxnTypes()) {
                LOG.fatal(String.format(
                        "Configuration files is inconsistent, phase %d contains %d weights but you defined %d transaction types",
                        j, p.getWeightCount(), wrkld.getNumTxnTypes()));
                System.exit(-1);
            }
        } // FOR

        // Generate the dialect map
        wrkld.init();

        assert (wrkld.getNumTxnTypes() >= 0);
        assert (xmlConfig != null);

        // ----------------------------------------------------------------
        // BENCHMARK MODULE
        // ----------------------------------------------------------------

        String classname = pluginConfig.getString("/plugin[@name='" + plugin + "']");

        if (classname == null) {
            throw new ParseException("Plugin " + plugin + " is undefined in config/plugin.xml");
        }
        BenchmarkModule bench = ClassUtil.newInstance(classname, new Object[] { wrkld },
                new Class<?>[] { WorkloadConfiguration.class });
        assert (benchList.get(0) != null);

        Map<String, Object> initDebug = new ListOrderedMap<String, Object>();
        initDebug.put("Benchmark", String.format("%s {%s}", plugin.toUpperCase(), classname));
        initDebug.put("Configuration", configFile);
        initDebug.put("Type", wrkld.getDBType());
        initDebug.put("Driver", wrkld.getDBDriver());
        initDebug.put("URL", wrkld.getDBConnection());
        initDebug.put("Isolation", xmlConfig.getString("isolation", "TRANSACTION_SERIALIZABLE [DEFAULT]"));
        initDebug.put("Scale Factor", wrkld.getScaleFactor());
        INIT_LOG.info(SINGLE_LINE + "\n\n" + StringUtil.formatMaps(initDebug));
        INIT_LOG.info(SINGLE_LINE);

        // Load TransactionTypes
        List<TransactionType> ttypes = new ArrayList<TransactionType>();

        // Always add an INVALID type for Carlo
        ttypes.add(TransactionType.INVALID);
        int txnIdOffset = lastTxnId;
        for (int i = 1; i < wrkld.getNumTxnTypes() + 1; i++) {
            String key = "transactiontypes" + pluginTest + "/transactiontype[" + i + "]";
            String txnName = xmlConfig.getString(key + "/name");
            int txnId = i + 1;
            if (xmlConfig.containsKey(key + "/id")) {
                txnId = xmlConfig.getInt(key + "/id");
            }
            TransactionType tmpType = bench.initTransactionType(txnName, txnId + txnIdOffset);
            // Keep a reference for filtering
            activeTXTypes.add(tmpType);
            // Add a reference for the active TTypes in this benchmark
            ttypes.add(tmpType);
            lastTxnId = i;
        } // FOR
        TransactionTypes tt = new TransactionTypes(ttypes);
        wrkld.setTransTypes(tt);
        LOG.debug("Using the following transaction types: " + tt);

        benchList.add(bench);
    }

    // Export StatementDialects
    if (isBooleanOptionSet(argsLine, "dialects-export")) {
        BenchmarkModule bench = benchList.get(0);
        if (bench.getStatementDialects() != null) {
            LOG.info("Exporting StatementDialects for " + bench);
            String xml = bench.getStatementDialects().export(bench.getWorkloadConfiguration().getDBType(),
                    bench.getProcedures().values());
            System.out.println(xml);
            System.exit(0);
        }
        throw new RuntimeException("No StatementDialects is available for " + bench);
    }

    @Deprecated
    boolean verbose = argsLine.hasOption("v");

    // Create the Benchmark's Database
    if (isBooleanOptionSet(argsLine, "create")) {
        for (BenchmarkModule benchmark : benchList) {
            CREATE_LOG.info("Creating new " + benchmark.getBenchmarkName().toUpperCase() + " database...");
            runCreator(benchmark, verbose);
            CREATE_LOG.info("Finished!");
            CREATE_LOG.info(SINGLE_LINE);
        }
    } else if (CREATE_LOG.isDebugEnabled()) {
        CREATE_LOG.debug("Skipping creating benchmark database tables");
        CREATE_LOG.info(SINGLE_LINE);
    }

    // Clear the Benchmark's Database
    if (isBooleanOptionSet(argsLine, "clear")) {
        for (BenchmarkModule benchmark : benchList) {
            CREATE_LOG.info("Resetting " + benchmark.getBenchmarkName().toUpperCase() + " database...");
            benchmark.clearDatabase();
            CREATE_LOG.info("Finished!");
            CREATE_LOG.info(SINGLE_LINE);
        }
    } else if (CREATE_LOG.isDebugEnabled()) {
        CREATE_LOG.debug("Skipping creating benchmark database tables");
        CREATE_LOG.info(SINGLE_LINE);
    }

    // Execute Loader
    if (isBooleanOptionSet(argsLine, "load")) {
        for (BenchmarkModule benchmark : benchList) {
            LOAD_LOG.info("Loading data into " + benchmark.getBenchmarkName().toUpperCase() + " database...");
            runLoader(benchmark, verbose);
            LOAD_LOG.info("Finished!");
            LOAD_LOG.info(SINGLE_LINE);
        }
    } else if (LOAD_LOG.isDebugEnabled()) {
        LOAD_LOG.debug("Skipping loading benchmark database records");
        LOAD_LOG.info(SINGLE_LINE);
    }

    // Execute a Script
    if (argsLine.hasOption("runscript")) {
        for (BenchmarkModule benchmark : benchList) {
            String script = argsLine.getOptionValue("runscript");
            SCRIPT_LOG.info("Running a SQL script: " + script);
            runScript(benchmark, script);
            SCRIPT_LOG.info("Finished!");
            SCRIPT_LOG.info(SINGLE_LINE);
        }
    }

    // Execute Workload
    if (isBooleanOptionSet(argsLine, "execute")) {
        // Bombs away!
        Results r = null;
        try {
            r = runWorkload(benchList, verbose);
        } catch (Throwable ex) {
            LOG.error("Unexpected error when running benchmarks.", ex);
            System.exit(1);
        }
        assert (r != null);

        PrintStream ps = System.out;
        PrintStream rs = System.out;
        ResultUploader ru = new ResultUploader(r, xmlConfig, argsLine);

        if (argsLine.hasOption("o")) {
            // Check if directory needs to be created
            if (outputDirectory.length() > 0) {
                FileUtil.makeDirIfNotExists(outputDirectory.split("/"));
            }

            // Build the complex path
            String baseFile = timestampValue + argsLine.getOptionValue("o");

            // Increment the filename for new results
            String nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".res"));
            ps = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output into file: " + nextName);

            nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".raw"));
            rs = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output Raw data into file: " + nextName);

            nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".summary"));
            PrintStream ss = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output summary data into file: " + nextName);
            ru.writeSummary(ss);
            ss.close();

            nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".db.cnf"));
            ss = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output db config into file: " + nextName);
            ru.writeDBParameters(ss);
            ss.close();

            nextName = FileUtil.getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".ben.cnf"));
            ss = new PrintStream(new File(nextName));
            EXEC_LOG.info("Output benchmark config into file: " + nextName);
            ru.writeBenchmarkConf(ss);
            ss.close();
        } else if (EXEC_LOG.isDebugEnabled()) {
            EXEC_LOG.debug("No output file specified");
        }

        if (argsLine.hasOption("s")) {
            int windowSize = Integer.parseInt(argsLine.getOptionValue("s"));
            EXEC_LOG.info("Grouped into Buckets of " + windowSize + " seconds");
            r.writeCSV(windowSize, ps);

            if (isBooleanOptionSet(argsLine, "upload")) {
                ru.uploadResult();
            }

            // Allow more detailed reporting by transaction to make it easier to check
            if (argsLine.hasOption("ss")) {

                for (TransactionType t : activeTXTypes) {
                    PrintStream ts = ps;

                    if (ts != System.out) {
                        // Get the actual filename for the output
                        String baseFile = timestampValue + argsLine.getOptionValue("o") + "_" + t.getName();
                        String prepended = outputDirectory + timestampValue;
                        String nextName = FileUtil
                                .getNextFilename(FileUtil.joinPath(outputDirectory, baseFile + ".res"));
                        ts = new PrintStream(new File(nextName));
                        r.writeCSV(windowSize, ts, t);
                        ts.close();
                    }
                }
            }
        } else if (EXEC_LOG.isDebugEnabled()) {
            EXEC_LOG.warn("No bucket size specified");
        }
        if (argsLine.hasOption("histograms")) {
            EXEC_LOG.info(SINGLE_LINE);
            EXEC_LOG.info("Completed Transactions:\n" + r.getTransactionSuccessHistogram() + "\n");
            EXEC_LOG.info("Aborted Transactions:\n" + r.getTransactionAbortHistogram() + "\n");
            EXEC_LOG.info("Rejected Transactions:\n" + r.getTransactionRetryHistogram());
            EXEC_LOG.info("Unexpected Errors:\n" + r.getTransactionErrorHistogram());
            if (r.getTransactionAbortMessageHistogram().isEmpty() == false)
                EXEC_LOG.info(
                        "User Aborts:\n" + StringUtil.formatMaps(r.getTransactionAbortMessageHistogram()));
        } else if (EXEC_LOG.isDebugEnabled()) {
            EXEC_LOG.warn("No bucket size specified");
        }

        r.writeAllCSVAbsoluteTiming(rs);

        ps.close();
        rs.close();
    } else {
        EXEC_LOG.info("Skipping benchmark workload execution");
    }
}

From source file:com.hpe.nv.samples.advanced.AdvAllTestClassMethods.java

public static void main(String[] args) throws Exception {
    try {/*from w w  w.  ja va  2  s . c  o  m*/
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("t", "site-url", true,
                "[optional] Site under test URL. Default: Default: HPE Network Virtualization site URL. If you change this value, make sure to change the --xpath argument too");
        options.addOption("x", "xpath", true,
                "[optional] Parameter for ExpectedConditions.visibilityOfElementLocated(By.xpath(...)) method. Use an xpath expression of some element in the site. Default: //div[@id='content']");
        options.addOption("a", "active-adapter-ip", true,
                "[optional] Active adapter IP. Default: --server-ip argument");
        options.addOption("m", "mode", true, "[mandatory] Test mode - ntx or custom");
        options.addOption("n", "ntx-file-path", true,
                "[mandatory in ntx mode] File path of an .ntx/.ntxx file - used to start the test in ntx mode");
        options.addOption("z", "zip-result-file-path", true,
                "[optional] File path to store the analysis results as a .zip file");
        options.addOption("k", "analysis-ports", true,
                "[optional] A comma-separated list of ports for test analysis");
        options.addOption("p", "packet-list-id", true,
                "[optional] A packet list ID used for capturing a specific packet list and downloading its corresponding .shunra file");
        options.addOption("c", "packet-list-file-path", true,
                "[optional] .pcap file path - used to store all captured packet lists");
        options.addOption("s", "shunra-file-path", true, "[optional] .shunra file path for download");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("AdvAllTestClassMethods.java", options);
            return;
        }

        if (line.hasOption("mode")) {
            mode = ((String) line.getOptionValue("mode")).toLowerCase();
        } else {
            throw new Exception("Missing argument -m/--mode <mode>");
        }

        if (!mode.equals("custom") && !mode.equals("ntx")) {
            throw new Exception("Mode not supported. Supported modes are: ntx or custom");
        }

        if (mode.equals("ntx")) {
            if (line.hasOption("ntx-file-path")) {
                ntxFilePath = line.getOptionValue("ntx-file-path");
            } else {
                throw new Exception("Missing argument -n/--ntx-file-path <ntxFilePath>");
            }
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("zip-result-file-path")) {
            zipResultFilePath = line.getOptionValue("zip-result-file-path");
        }

        if (line.hasOption("packet-list-id")) {
            packetListId = line.getOptionValue("packet-list-id");
        }

        if (line.hasOption("packet-list-file-path")) {
            packetListFilePath = line.getOptionValue("packet-list-file-path");
        }

        if (line.hasOption("shunra-file-path")) {
            shunraFilePath = line.getOptionValue("shunra-file-path");
        }

        if (line.hasOption("site-url")) {
            siteUrl = line.getOptionValue("site-url");
        } else {
            siteUrl = "http://www8.hp.com/us/en/software-solutions/network-virtualization/index.html";
        }

        if (line.hasOption("xpath")) {
            xpath = line.getOptionValue("xpath");
        } else {
            xpath = "//div[@id='content']";
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("active-adapter-ip")) {
            activeAdapterIp = line.getOptionValue("active-adapter-ip");
        } else {
            activeAdapterIp = serverIp;
        }

        if (line.hasOption("analysis-ports")) {
            String analysisPortsStr = line.getOptionValue("analysis-ports");
            analysisPorts = analysisPortsStr.split(",");
        } else {
            analysisPorts = new String[] { "80", "8080" };
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates all of the Test class APIs except for the                      ***"
                + newLine
                + "***   real-time update API, which is demonstrated in AdvRealtimeUpdate.java.                  ***"
                + newLine
                + "***   You can start the test in this sample using either the NTX or Custom modes.             ***"
                + newLine
                + "***                                                                                           ***"
                + newLine
                + "***   You can view the actual steps of this sample in the AdvAllTestClassMethods.java file.   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Initialize the TestManager object to pass logon credentials, the NV Test Manager IP, the port, and so on                                                      *****/
        printPartDescription(
                "\b------    Part 1 - Initialize the TestManager object to pass logon credentials, the NV Test Manager IP, the port, and so on");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Set the active adapter and start the NV test                                                                                                                  *****/
        printPartDescription("------    Part 2 - Set the active adapter and start the NV test");
        setActiveAdapter();
        startTest();
        testRunning = true;
        connectToTransactionManager();
        printPartSeparator();
        /*****    Part 3 - Start packet list capture, get the packet list information and print it to the console (if the --debug argument is set to true)                               *****/
        printPartDescription(
                "------    Part 3 - Start packet list capture, get the packet list information and print it to the console (if the --debug argument is set to true)");
        startPacketListCapture();
        getPacketListInfo();
        printPartSeparator();
        /*****    Part 4 - Start the NV transaction and navigate to the site                                                                                                             *****/
        printPartDescription("------    Part 4 - Start the NV transaction and navigate to the site");
        startTransaction();
        transactionInProgress = true;
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        printPartSeparator();
        /*****    Part 5 - Get the NV test statistics and print the Client-in statistics to the console (if the --debug argument is set to true)                                         *****/
        printPartDescription(
                "------    Part 5 - Get the NV test statistics and print the Client-in statistics to the console (if the --debug argument is set to true)");
        getTestStatistics();
        printPartSeparator();
        /*****    Part 6 - Stop the NV transaction and the packet list capture, get the packet list information and print it to the console (if the --debug argument is set to true)     *****/
        printPartDescription(
                "------    Part 6 - Stop the NV transaction and the packet list capture, get the packet list information and print it to the console (if the --debug argument is set to true)");
        stopTransaction();
        transactionInProgress = false;
        stopPacketListCapture();
        getPacketListInfo();
        printPartSeparator();
        /*****    Part 7 - Disconnect from the transaction manager and stop the NV test                                                                                                  *****/
        printPartDescription("------    Part 7 - Disconnect from the transaction manager and stop the NV test");
        disconnectFromTransactionManager();
        stopTest();
        testRunning = false;
        printPartSeparator();
        /*****    Part 8 - Analyze the NV test and print the results to the console                                                                                                      *****/
        printPartDescription("------    Part 8 - Analyze the NV test and print the results to the console");
        analyzeTest();
        printPartSeparator();
        /*****    Part 9 - Download the specified packet list and the .shunra file                                                                                                      *****/
        printPartDescription("------    Part 9 - Download the specified packet list and the .shunra file");
        downloadPacketList();
        downloadShunra();
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:com.joliciel.lefff.Lefff.java

/**
 * @param args/*w  ww  .ja  va2s .c om*/
 */
public static void main(String[] args) throws Exception {
    long startTime = (new Date()).getTime();
    String command = args[0];

    String memoryBaseFilePath = "";
    String lefffFilePath = "";
    String posTagSetPath = "";
    String posTagMapPath = "";
    String word = null;
    List<String> categories = null;
    int startLine = -1;
    int stopLine = -1;

    boolean firstArg = true;
    for (String arg : args) {
        if (firstArg) {
            firstArg = false;
            continue;
        }
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        if (argName.equals("memoryBase"))
            memoryBaseFilePath = argValue;
        else if (argName.equals("lefffFile"))
            lefffFilePath = argValue;
        else if (argName.equals("startLine"))
            startLine = Integer.parseInt(argValue);
        else if (argName.equals("stopLine"))
            stopLine = Integer.parseInt(argValue);
        else if (argName.equals("posTagSet"))
            posTagSetPath = argValue;
        else if (argName.equals("posTagMap"))
            posTagMapPath = argValue;
        else if (argName.equals("word"))
            word = argValue;
        else if (argName.equals("categories")) {
            String[] parts = argValue.split(",");
            categories = new ArrayList<String>();
            for (String part : parts) {
                categories.add(part);
            }
        } else
            throw new RuntimeException("Unknown argument: " + argName);
    }

    final LefffServiceLocator locator = new LefffServiceLocator();
    locator.setDataSourcePropertiesFile("jdbc-live.properties");

    TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance();

    final LefffService lefffService = locator.getLefffService();
    if (command.equals("load")) {
        if (lefffFilePath.length() == 0)
            throw new RuntimeException("Required argument: lefffFile");
        final LefffLoader loader = lefffService.getLefffLoader();
        File file = new File(lefffFilePath);
        if (startLine > 0)
            loader.setStartLine(startLine);
        if (stopLine > 0)
            loader.setStopLine(stopLine);

        loader.LoadFile(file);
    } else if (command.equals("serialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");
        if (posTagSetPath.length() == 0)
            throw new RuntimeException("Required argument: posTagSet");
        if (posTagMapPath.length() == 0)
            throw new RuntimeException("Required argument: posTagMap");

        PosTaggerServiceLocator posTaggerServiceLocator = talismaneServiceLocator.getPosTaggerServiceLocator();
        PosTaggerService posTaggerService = posTaggerServiceLocator.getPosTaggerService();
        File posTagSetFile = new File(posTagSetPath);
        PosTagSet posTagSet = posTaggerService.getPosTagSet(posTagSetFile);

        File posTagMapFile = new File(posTagMapPath);
        LefffPosTagMapper posTagMapper = lefffService.getPosTagMapper(posTagMapFile, posTagSet);

        Map<PosTagSet, LefffPosTagMapper> posTagMappers = new HashMap<PosTagSet, LefffPosTagMapper>();
        posTagMappers.put(posTagSet, posTagMapper);

        LefffMemoryLoader loader = new LefffMemoryLoader();
        LefffMemoryBase memoryBase = loader.loadMemoryBaseFromDatabase(lefffService, posTagMappers, categories);
        File memoryBaseFile = new File(memoryBaseFilePath);
        memoryBaseFile.delete();
        loader.serializeMemoryBase(memoryBase, memoryBaseFile);
    } else if (command.equals("deserialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");

        LefffMemoryLoader loader = new LefffMemoryLoader();
        File memoryBaseFile = new File(memoryBaseFilePath);
        LefffMemoryBase memoryBase = loader.deserializeMemoryBase(memoryBaseFile);

        String[] testWords = new String[] { "avoir" };
        if (word != null) {
            testWords = word.split(",");
        }

        for (String testWord : testWords) {
            Set<PosTag> possiblePosTags = memoryBase.findPossiblePosTags(testWord);
            LOG.debug("##### PosTags for '" + testWord + "': " + possiblePosTags.size());
            int i = 1;
            for (PosTag posTag : possiblePosTags) {
                LOG.debug("### PosTag " + (i++) + ":" + posTag);
            }

            List<? extends LexicalEntry> entriesForWord = memoryBase.getEntries(testWord);
            LOG.debug("##### Entries for '" + testWord + "': " + entriesForWord.size());
            i = 1;
            for (LexicalEntry entry : entriesForWord) {
                LOG.debug("### Entry " + (i++) + ":" + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
            }

            List<? extends LexicalEntry> entriesForLemma = memoryBase.getEntriesForLemma(testWord, "");
            LOG.debug("##### Entries for '" + testWord + "' lemma: " + entriesForLemma.size());
            for (LexicalEntry entry : entriesForLemma) {
                LOG.debug("### Entry " + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
                for (PredicateArgument argument : entry.getPredicateArguments()) {
                    LOG.debug("Argument: " + argument.getFunction() + ",Optional? " + argument.isOptional());
                    for (String realisation : argument.getRealisations()) {
                        LOG.debug("Realisation: " + realisation);
                    }
                }
            }
        }

    } else {
        System.out.println("Usage : Lefff load filepath");
    }
    long endTime = (new Date()).getTime() - startTime;
    LOG.debug("Total runtime: " + ((double) endTime / 1000) + " seconds");
}

From source file:com.hpe.nv.samples.advanced.AdvAllTestManagerClassMethods.java

public static void main(String[] args) throws Exception {
    try {//from  ww w .j  ava  2  s  .  c om
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("t", "site-url", true,
                "[optional] Site under test URL. Default: HPE Network Virtualization site URL. If you change this value, make sure to change the --xpath argument too");
        options.addOption("x", "xpath", true,
                "[optional] Parameter for ExpectedConditions.visibilityOfElementLocated(By.xpath(...)) method. Use an xpath expression of some element in the site. Default: //div[@id='content']");
        options.addOption("a", "active-adapter-ip", true,
                "[optional] Active adapter IP. Default: --server-ip argument");
        options.addOption("s", "shunra-file-path", true,
                "[optional] File path for the .shunra file to analyze");
        options.addOption("z", "zip-result-file-path", true,
                "[optional] File path to store the analysis results as a .zip file");
        options.addOption("k", "analysis-ports", true,
                "[optional] A comma-separated list of ports for test analysis");
        options.addOption("f", "first-test-flow-tcp-port", true,
                "[optional] TCP port for the flow of the first test");
        options.addOption("g", "second-test-flow-tcp-port", true,
                "[optional] TCP port for the flow of the second test");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("AdvAllTestManagerClassMethods.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("site-url")) {
            siteUrl = line.getOptionValue("site-url");
        } else {
            siteUrl = "http://www8.hp.com/us/en/software-solutions/network-virtualization/index.html";
        }

        if (line.hasOption("xpath")) {
            xpath = line.getOptionValue("xpath");
        } else {
            xpath = "//div[@id='content']";
        }

        if (line.hasOption("zip-result-file-path")) {
            zipResultFilePath = line.getOptionValue("zip-result-file-path");
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("active-adapter-ip")) {
            activeAdapterIp = line.getOptionValue("active-adapter-ip");
        } else {
            activeAdapterIp = serverIp;
        }

        if (line.hasOption("analysis-ports")) {
            String analysisPortsStr = line.getOptionValue("analysis-ports");
            analysisPorts = analysisPortsStr.split(",");
        } else {
            analysisPorts = new String[] { "80", "8080" };
        }

        if (line.hasOption("shunra-file-path")) {
            shunraFilePath = line.getOptionValue("shunra-file-path");
        }

        if (line.hasOption("firstTestFlowTcpPort")) {
            firstTestFlowTcpPort = Integer.parseInt(line.getOptionValue("firstTestFlowTcpPort"));
        } else {
            firstTestFlowTcpPort = 8080;
        }

        if (line.hasOption("secondTestFlowTcpPort")) {
            secondTestFlowTcpPort = Integer.parseInt(line.getOptionValue("secondTestFlowTcpPort"));
        } else {
            secondTestFlowTcpPort = 80;
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates all of the TestManager class APIs. These APIs let you:                                 ***"
                + newLine
                + "***   * initialize the TestManager object to pass logon credentials, the NV Test Manager IP, the port, and so on      ***"
                + newLine
                + "***   * set/get the NV configuration and active adapter                                                               ***"
                + newLine
                + "***   * get the running tests tokens                                                                                  ***"
                + newLine
                + "***   * start/stop packet list capture                                                                                ***"
                + newLine
                + "***   * get packet list information                                                                                   ***"
                + newLine
                + "***   * stop a specified array of tests or all of the running tests                                                   ***"
                + newLine
                + "***   * analyze a .shunra file, which is a compressed file that includes an events file, metadata, and packet lists   ***"
                + newLine
                + "***                                                                                                                   ***"
                + newLine
                + "***   You can view the actual steps of this sample in the AdvAllTestManagerClassMethods.java file.                    ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Initialize the TestManager object to pass logon credentials, the NV Test Manager IP, the port, and so on            *****/
        printPartDescription(
                "\b------    Part 1 - Initialize the TestManager object to pass logon credentials, the NV Test Manager IP, the port, and so on");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Set/get the NV configuration and active adapter                                                                     *****/
        printPartDescription("------    Part 2 - Set/get the NV configuration and active adapter");
        setActiveAdapter();
        getActiveAdapter();
        setConfiguration();
        getConfiguration();
        printPartSeparator();
        /*****    Part 3 - Start tests and get the NV tests' tokens                                                                             *****/
        printPartDescription("------    Part 3 - Start tests and get the NV tests' tokens");
        startTest1();
        connectTest1ToTransactionManager();
        startTest2();
        connectTest2ToTransactionManager();
        getTestTokens();
        printPartSeparator();
        /*****    Part 4 - Start NV transactions, navigate to the site and start capturing the packet lists                                     *****/
        printPartDescription(
                "------    Part 4 - Start NV transactions, navigate to the site and start capturing the packet lists");
        startTransaction1();
        startTransaction2();
        startPacketListCapture();
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        printPartSeparator();
        /*****    Part 5 - Get the packet list information and print it to the console (if the --debug argument is set to true)                 *****/
        printPartDescription(
                "------    Part 5 - Get the packet list information and print it to the console (if the --debug argument is set to true)");
        getPacketListInfo();
        printPartSeparator();
        /*****    Part 6 - Stop capturing packet lists and stop the NV transactions                                                             *****/
        printPartDescription("------    Part 6 - Stop capturing packet lists and stop the NV transactions");
        stopPacketListCapture();
        stopTransaction1();
        siteTransaction1 = null;
        stopTransaction2();
        siteTransaction2 = null;
        printPartSeparator();
        /*****    Part 7 - Stop the first NV test using the "stopTests" method and then stop the second test using the "stopAllTests" method    *****/
        printPartDescription(
                "------    Part 7 - Stop the first NV test using the \"stopTests\" method and then stop the second test using the \"stopAllTests\" method");
        stopTest1();
        siteTest1 = null;
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        stopAllTests();
        siteTest2 = null;
        printPartSeparator();
        /*****    Part 8 - Analyze the specified .shunra file and print the results to the console                                              *****/
        printPartDescription(
                "------    Part 8 - Analyze the specified .shunra file and print the results to the console");
        analyzeShunra();
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:com.linkedin.cubert.io.rubix.RubixFile.java

public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException,
        ParseException, InstantiationException, IllegalAccessException {
    final int VERBOSE_NUM_ROWS = 4;

    Options options = new Options();

    options.addOption("h", "help", false, "shows this message");
    options.addOption("v", "verbose", false, "print summary and first few rows of each block");
    options.addOption("m", "metadata", false, "show the metadata");
    options.addOption("d", "dump", false,
            "dump the contents of the rubix file. Use -f for specifying format, and -o for specifying "
                    + "output location");
    options.addOption("f", "format", true, "the data format for dumping data (AVRO or TEXT). Default: TEXT");
    options.addOption("e", "extract", true,
            "Extract one or more rubix blocks starting from the given blockId. Use -e blockId,numBlocks "
                    + "for specifying the blocks to be extracted. Use -o for specifying output location");
    options.addOption("o", true, "Store the output at the specified location");

    CommandLineParser parser = new BasicParser();

    // parse the command line arguments
    CommandLine line = parser.parse(options, args);

    // show the help message
    if (line.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(/*w w w. j  a  va 2 s  .c o  m*/
                "RubixFile <rubix file or dir> [options]\nIf no options are provided, print a summary of the blocks.",
                options);
        return;
    }

    // validate provided options
    if (line.hasOption("d") && line.hasOption("e")) {
        System.err.println("Cannot dump (-d) and extract (-e) at the same time!");
        return;
    }

    // obtain the list of rubix files
    String[] files = line.getArgs();
    if (files == null || files.length == 0) {
        System.err.println("Rubix file not specified");
        return;
    }

    Configuration conf = new JobConf();
    FileSystem fs = FileSystem.get(conf);

    Path path = new Path(files[0]);
    FileStatus[] allFiles;

    FileStatus status = fs.getFileStatus(path);
    if (status.isDir()) {
        allFiles = RubixFile.getRubixFiles(path, fs);
    } else {
        allFiles = new FileStatus[] { status };
    }

    // walk over all files and extract the trailer section
    List<RubixFile<Tuple, Object>> rfiles = new ArrayList<RubixFile<Tuple, Object>>();

    for (FileStatus s : allFiles) {
        Path p = s.getPath();

        RubixFile<Tuple, Object> rfile = new RubixFile<Tuple, Object>(conf, p);

        // if printing meta data information.. exit after first file (since all files
        // have the same meta data)
        if (line.hasOption("m")) {
            rfile.getKeyData();

            System.out.println(new ObjectMapper().writer().writeValueAsString(rfile.metadataJson));
            break;
        }

        rfiles.add(rfile);
    }

    // dump the data
    if (line.hasOption("d")) {
        String format = line.getOptionValue("f");
        if (format == null)
            format = "TEXT";

        format = format.trim().toUpperCase();

        if (format.equals("AVRO")) {
            // dumpAvro(rfiles, line.getOptionValue("o"));
            throw new UnsupportedOperationException(
                    "Dumping to avro is not currently supporting. Please write a Cubert (map-only) script to store data in avro format");
        } else if (format.equals("TEXT")) {
            if (line.hasOption("o")) {
                System.err.println("Dumping TEXT format data *into a file* is not currently supported");
                return;
            }
            dumpText(rfiles, line.getOptionValue("o"), Integer.MAX_VALUE);
        } else {
            System.err.println("Invalid format [" + format + "] for dumping. Please use AVRO or TEXT");
            return;
        }
    }
    // extract arguments: -e blockId,numBlocks(contiguous) -o ouputLocation
    else if (line.hasOption("e")) {
        String extractArguments = line.getOptionValue("e");
        String outputLocation;
        if (line.hasOption("o")) {
            outputLocation = line.getOptionValue("o");
        } else {
            System.err.println("Need to specify the location to store the output");
            return;
        }
        long blockId;
        int numBlocks = 1;
        if (extractArguments.contains(",")) {
            String[] splitExtractArgs = extractArguments.split(",");
            blockId = Long.parseLong(splitExtractArgs[0]);
            numBlocks = Integer.parseInt(splitExtractArgs[1]);
        } else {
            blockId = Long.parseLong(extractArguments);
        }

        extract(rfiles, blockId, numBlocks, outputLocation);
    } else
    // print summary
    {
        dumpText(rfiles, null, line.hasOption("v") ? VERBOSE_NUM_ROWS : 0);
    }
}

From source file:mamo.vanillaVotifier.VanillaVotifier.java

public static void main(String[] args) {
    String[] javaVersion = System.getProperty("java.version").split("\\.");
    if (!(javaVersion.length >= 1 && Integer.parseInt(javaVersion[0]) >= 1 && javaVersion.length >= 2
            && Integer.parseInt(javaVersion[1]) >= 6)) {
        System.out.println(("You need at least Java 1.6 to run this program! Current version: "
                + System.getProperty("java.version") + "."));
        return;/*w  w  w  .j  a  v a2 s . co  m*/
    }

    VanillaVotifier votifier = new VanillaVotifier();
    for (String arg : args) {
        if (arg.equalsIgnoreCase("-report-exceptions")) {
            votifier.reportExceptions = true;
        } else if (arg.equalsIgnoreCase("-help")) {
            votifier.getLogger().printlnTranslation("s58");
            return;
        } else {
            votifier.getLogger().printlnTranslation("s55",
                    new AbstractMap.SimpleEntry<String, Object>("option", arg));
            return;
        }
    }
    votifier.getLogger().printlnTranslation("s42");
    if (!(loadConfig(votifier) && startServer(votifier))) {
        return;
    }
    Scanner in = new Scanner(System.in);

    while (true) {
        String command;
        try {
            command = in.nextLine();
        } catch (NoSuchElementException e) {
            // NoSuchElementException: Can only happen at unexpected program interruption (i. e. CTRL+C). Ignoring.
            continue;
        } catch (Exception e) {
            votifier.getLogger().printlnTranslation("s57",
                    new AbstractMap.SimpleEntry<String, Object>("exception", e));
            if (!stopServer(votifier)) {
                System.exit(0); // "return" somehow isn't enough.
            }
            return;
        }
        if (command.equalsIgnoreCase("stop") || command.toLowerCase().startsWith("stop ")) {
            if (command.split(" ").length == 1) {
                stopServer(votifier);
                break;
            } else {
                votifier.getLogger().printlnTranslation("s17");
            }
        } else if (command.equalsIgnoreCase("restart") || command.toLowerCase().startsWith("restart ")) {
            if (command.split(" ").length == 1) {
                Listener listener = new Listener() {
                    @Override
                    public void onEvent(Event event, VanillaVotifier votifier) {
                        if (event instanceof ServerStoppedEvent) {
                            if (loadConfig((VanillaVotifier) votifier)
                                    && startServer((VanillaVotifier) votifier)) {
                                votifier.getServer().getListeners().remove(this);
                            } else {
                                System.exit(0);
                            }
                        }
                    }
                };
                votifier.getServer().getListeners().add(listener);
                if (!stopServer(votifier)) { // Kill the process if the server doesn't stop
                    System.exit(0); // "return" somehow isn't enough.
                    return;
                }
            } else {
                votifier.getLogger().printlnTranslation("s56");
            }
        } else if (command.equalsIgnoreCase("gen-key-pair") || command.startsWith("gen-key-pair ")) {
            String[] commandArgs = command.split(" ");
            int keySize;
            if (commandArgs.length == 1) {
                keySize = 2048;
            } else if (commandArgs.length == 2) {
                try {
                    keySize = Integer.parseInt(commandArgs[1]);
                } catch (NumberFormatException e) {
                    votifier.getLogger().printlnTranslation("s19");
                    continue;
                }
                if (keySize < 512) {
                    votifier.getLogger().printlnTranslation("s51");
                    continue;
                }
                if (keySize > 16384) {
                    votifier.getLogger().printlnTranslation("s52");
                    continue;
                }
            } else {
                votifier.getLogger().printlnTranslation("s20");
                continue;
            }
            votifier.getLogger().printlnTranslation("s16");
            votifier.getConfig().genKeyPair(keySize);
            try {
                votifier.getConfig().save();
            } catch (Exception e) {
                votifier.getLogger().printlnTranslation("s21",
                        new AbstractMap.SimpleEntry<String, Object>("exception", e));
            }
            votifier.getLogger().printlnTranslation("s23");
        } else if (command.equalsIgnoreCase("test-vote") || command.toLowerCase().startsWith("test-vote ")) {
            String[] commandArgs = command.split(" ");
            if (commandArgs.length == 2) {
                try {
                    votifier.getTester().testVote(new Vote("TesterService", commandArgs[1],
                            votifier.getConfig().getInetSocketAddress().getAddress().getHostName()));
                } catch (Exception e) { // GeneralSecurityException, IOException
                    votifier.getLogger().printlnTranslation("s27",
                            new AbstractMap.SimpleEntry<String, Object>("exception", e));
                }
            } else {
                votifier.getLogger().printlnTranslation("s26");
            }
        } else if (command.equalsIgnoreCase("test-query") || command.toLowerCase().startsWith("test-query ")) {
            if (command.split(" ").length >= 2) {
                try {
                    votifier.getTester()
                            .testQuery(command.replaceFirst("test-query ", "").replaceAll("---", "\n"));
                } catch (Exception e) { // GeneralSecurityException, IOException
                    votifier.getLogger().printlnTranslation("s35",
                            new AbstractMap.SimpleEntry<String, Object>("exception", e));
                }
            } else {
                votifier.getLogger().printlnTranslation("s34");
            }
        } else if (command.equalsIgnoreCase("help") || command.toLowerCase().startsWith("help ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s31");
            } else {
                votifier.getLogger().printlnTranslation("s32");
            }
        } else if (command.equalsIgnoreCase("manual") || command.toLowerCase().startsWith("manual ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s36");
            } else {
                votifier.getLogger().printlnTranslation("s37");
            }
        } else if (command.equalsIgnoreCase("info") || command.toLowerCase().startsWith("info ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s40");
            } else {
                votifier.getLogger().printlnTranslation("s41");
            }
        } else if (command.equalsIgnoreCase("license") || command.toLowerCase().startsWith("license ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s43");
            } else {
                votifier.getLogger().printlnTranslation("s44");
            }
        } else {
            votifier.getLogger().printlnTranslation("s33");
        }
    }
}

From source file:com.ailk.oci.ocnosql.tools.load.mutiple.MutipleColumnImportTsv.java

/**
 * Main entry point.//w  w w .j  av a 2s .  co  m
 *
 * @param args  The command line parameters.
 * @throws Exception When running the job fails.
 */
public static void main(String[] args) throws Exception {
    long inputLineNum = 0L;
    long badLineNum = 0L;
    long outputLineNum = 0L;
    Configuration conf = HBaseConfiguration.create();
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
    if (otherArgs.length < 2) {
        usage("Wrong number of arguments: " + otherArgs.length);
        System.exit(-1);
    }
    // Make sure columns are specified
    String columns = conf.get(CommonConstants.COLUMNS);
    if (columns == null) {
        usage("No columns specified. Please specify with -D" + CommonConstants.COLUMNS + "=...");
        System.exit(-1);
    }
    String seperator = conf.get(CommonConstants.SEPARATOR);
    if (StringUtils.isEmpty(seperator)) {
        conf.set(CommonConstants.SEPARATOR, CommonConstants.DEFAULT_SEPARATOR);
        seperator = CommonConstants.DEFAULT_SEPARATOR;
    }
    // Make sure one or more columns are specified
    if (columns.split(",").length < 2) {
        usage("One or more columns in addition to the row key are required");
        System.exit(-1);
    }
    //make sure tableName and columns are upper to used by phoenix.
    columns = columns.toUpperCase();
    String notNeedLoadColumnsStr = conf.get(CommonConstants.NOTNEEDLOADCOLUMNS);
    String notNeedLoadColumns = null;
    if (!StringUtils.isEmpty(notNeedLoadColumnsStr)) {
        notNeedLoadColumns = notNeedLoadColumnsStr.toUpperCase();
        conf.set(CommonConstants.NOTNEEDLOADCOLUMNS, notNeedLoadColumns);
    }

    String writeTableConfigColumns = getWriteConfigColumn(columns, notNeedLoadColumns);
    hbaseAdmin = new HBaseAdmin(conf);
    String tableName = otherArgs[0].toUpperCase();
    String inputPath = otherArgs[1];
    String tmpOutputPath = conf.get(CommonConstants.IMPORT_TMP_OUTPUT);
    conf.set(CommonConstants.TABLE_NAME, tableName);
    conf.set(CommonConstants.COLUMNS, columns);
    String pathStr = conf.get(CommonConstants.HDFS_URL) + inputPath;
    FileSystem fs = FileSystem.get(URI.create(conf.get(CommonConstants.HDFS_URL)), conf);
    FileStatus[] fileStatusArr = fs.listStatus(new Path(pathStr));
    if (fileStatusArr != null && fileStatusArr.length > 0) {
        TableConfiguration.getInstance().writeTableConfiguration(tableName, writeTableConfigColumns, seperator,
                conf);
        if (fileStatusArr[0].isFile()) {
            Object[] resObjs = runJob(conf, tableName, inputPath, tmpOutputPath);
            inputLineNum = (Long) resObjs[1];
            outputLineNum = (Long) resObjs[2];
            badLineNum = (Long) resObjs[3];
            LOG.info("Bulkload Result={inputLine:" + inputLineNum + ",outputLine:" + outputLineNum + ",badLine:"
                    + badLineNum + "}");
            boolean result = (Boolean) resObjs[0];
            if (result) {
                System.exit(0);
            }
            System.exit(-1);
        }
        for (FileStatus everyInputPath : fileStatusArr) {
            Path inputPathStr = everyInputPath.getPath();
            String absoluteInputPathStr = inputPath + "/" + inputPathStr.getName();
            FileStatus[] subFileStatusArr = fs
                    .listStatus(new Path(conf.get(CommonConstants.HDFS_URL) + absoluteInputPathStr));
            if (subFileStatusArr == null || subFileStatusArr.length == 0)//?job
                continue;
            Object[] resObjs = runJob(conf, tableName, absoluteInputPathStr,
                    tmpOutputPath + "/" + inputPathStr.getName());
            boolean ret = (Boolean) resObjs[0];
            if (ret) {
                inputLineNum += (Long) resObjs[1];
                outputLineNum += (Long) resObjs[2];
                badLineNum += (Long) resObjs[3];
                String seperatorStr = conf.get(CommonConstants.SEPARATOR);
                conf.set(CommonConstants.SEPARATOR, new String(Base64.decode(seperatorStr))); //?separator
                continue;
            } else { //
                LOG.error("Bulkload Result={inputLine:" + inputLineNum + ",outputLine:" + outputLineNum
                        + ",badLine:" + badLineNum + "}");
                System.exit(-1);
            }
        }
        LOG.info("Bulkload Result={inputLine:" + inputLineNum + ",outputLine:" + outputLineNum + ",badLine:"
                + badLineNum + "}");
    }
    LOG.info("Bulkload Result={inputLine:" + inputLineNum + ",outputLine:" + outputLineNum + ",badLine:"
            + badLineNum + "}");
    System.exit(0);//
}

From source file:com.gtwm.jasperexecute.RunJasperReports.java

public static void main(String[] args) throws Exception {
    RunJasperReports runJasperReports = new RunJasperReports();
    // Set up command line parser
    Options options = new Options();
    Option reports = OptionBuilder.withArgName("reportlist").hasArg()
            .withDescription("Comma separated list of JasperReport XML input files").create("reports");
    options.addOption(reports);/*from w  ww.  j  a  v  a  2 s . c o  m*/
    Option emailTo = OptionBuilder.withArgName("emailaddress").hasArg()
            .withDescription("Email address to send generated reports to").create("emailto");
    options.addOption(emailTo);
    Option emailFrom = OptionBuilder.withArgName("emailaddress").hasArg()
            .withDescription("Sender email address").create("emailfrom");
    options.addOption(emailFrom);
    Option emailSubjectLine = OptionBuilder.withArgName("emailsubject").hasArg()
            .withDescription("Subject line of email").create("emailsubject");
    options.addOption(emailSubjectLine);
    Option emailHostOption = OptionBuilder.withArgName("emailhost").hasArg()
            .withDescription("Address of email server").create("emailhost");
    options.addOption(emailHostOption);
    Option emailUsernameOption = OptionBuilder.withArgName("emailuser").hasArg()
            .withDescription("Username if email server requires authentication").create("emailuser");
    options.addOption(emailUsernameOption);
    Option emailPasswordOption = OptionBuilder.withArgName("emailpass").hasArg()
            .withDescription("Password if email server requires authentication").create("emailpass");
    options.addOption(emailPasswordOption);
    Option outputFolder = OptionBuilder.withArgName("foldername").hasArg()
            .withDescription(
                    "Folder to write generated reports to, with trailing separator (slash or backslash)")
            .create("folder");
    options.addOption(outputFolder);
    Option dbTypeOption = OptionBuilder.withArgName("databasetype").hasArg()
            .withDescription("Currently supported types are: " + Arrays.asList(DatabaseType.values()))
            .create("dbtype");
    options.addOption(dbTypeOption);
    Option dbNameOption = OptionBuilder.withArgName("databasename").hasArg()
            .withDescription("Name of the database to run reports against").create("dbname");
    options.addOption(dbNameOption);

    Option dbUserOption = OptionBuilder.withArgName("username").hasArg()
            .withDescription("Username to connect to databasewith").create("dbuser");
    options.addOption(dbUserOption);
    Option dbPassOption = OptionBuilder.withArgName("password").hasArg().withDescription("Database password")
            .create("dbpass");
    options.addOption(dbPassOption);
    Option outputTypeOption = OptionBuilder.withArgName("outputtype").hasArg()
            .withDescription("Output type, one of: " + Arrays.asList(OutputType.values())).create("output");
    options.addOption(outputTypeOption);
    Option outputFilenameOption = OptionBuilder.withArgName("outputfilename").hasArg()
            .withDescription("Output filename (excluding filetype suffix)").create("filename");
    options.addOption(outputFilenameOption);
    Option dbHostOption = OptionBuilder.withArgName("host").hasArg().withDescription("Database host address")
            .create("dbhost");
    options.addOption(dbHostOption);
    Option paramsOption = OptionBuilder.withArgName("parameters").hasArg().withDescription(
            "Parameters, e.g. param1=boolean:true,param2=string:ABC,param3=double:134.2,param4=integer:85")
            .create("params");
    options.addOption(paramsOption);
    // Parse command line
    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = parser.parse(options, args);
    String reportsDefinitionFileNamesCvs = commandLine.getOptionValue("reports");
    if (reportsDefinitionFileNamesCvs == null) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar RunJasperReports.jar", options);
        System.out.println();
        System.out.println("See www.agilebase.co.uk/opensource for further documentation");
        System.out.println();
        throw new IllegalArgumentException("No reports specified");
    }
    String outputPath = commandLine.getOptionValue("folder");
    List<String> reportDefinitionFileNames = Arrays.asList(reportsDefinitionFileNamesCvs.split(","));
    List<String> outputFileNames = new ArrayList<String>();
    DatabaseType databaseType = DatabaseType.POSTGRESQL;
    String databaseTypeString = commandLine.getOptionValue("dbtype");
    if (databaseTypeString != null) {
        databaseType = DatabaseType.valueOf(commandLine.getOptionValue("dbtype").toUpperCase());
    }
    String databaseName = commandLine.getOptionValue("dbname");
    String databaseUsername = commandLine.getOptionValue("dbuser");
    String databasePassword = commandLine.getOptionValue("dbpass");
    String databaseHost = commandLine.getOptionValue("dbhost");
    if (databaseHost == null) {
        databaseHost = "localhost";
    }
    OutputType outputType = OutputType.PDF;
    String outputTypeString = commandLine.getOptionValue("output");
    if (outputTypeString != null) {
        outputType = OutputType.valueOf(outputTypeString.toUpperCase());
    }
    String parametersString = commandLine.getOptionValue("params");
    Map parameters = runJasperReports.prepareParameters(parametersString);
    String outputFilenameSpecified = commandLine.getOptionValue("filename");
    if (outputFilenameSpecified == null) {
        outputFilenameSpecified = "";
    }
    // Iterate over reports, generating output for each
    for (String reportsDefinitionFileName : reportDefinitionFileNames) {
        String outputFilename = null;
        if ((reportDefinitionFileNames.size() == 1) && (!outputFilenameSpecified.equals(""))) {
            outputFilename = outputFilenameSpecified;
        } else {
            outputFilename = outputFilenameSpecified + reportsDefinitionFileName.replaceAll("\\..*$", "");
            outputFilename = outputFilename.replaceAll("^.*\\/", "");
            outputFilename = outputFilename.replaceAll("^.*\\\\", "");
        }
        outputFilename = outputFilename.replaceAll("\\W", "").toLowerCase() + "."
                + outputType.toString().toLowerCase();
        if (outputPath != null) {
            if (!outputPath.endsWith("\\") && !outputPath.endsWith("/")) {
                outputPath += java.io.File.separator;
            }
            outputFilename = outputPath + outputFilename;
        }
        System.out.println("Going to generate report " + outputFilename);
        if (outputType.equals(OutputType.PDF)) {
            runJasperReports.generatePdfReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseName, databaseUsername, databasePassword, databaseHost, parameters);
        } else if (outputType.equals(OutputType.TEXT)) {
            runJasperReports.generateTextReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseName, databaseUsername, databasePassword, databaseHost, parameters);
        } else if (outputType.equals(OutputType.CSV)) {
            runJasperReports.generateCSVReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseName, databaseUsername, databasePassword, databaseHost, parameters);
        } else if (outputType.equals(OutputType.XLS)) {
            // NB: parameters are in a different order for XLS for some reasons
            runJasperReports.generateJxlsReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseHost, databaseName, databaseUsername, databasePassword, parameters);
        } else {
            runJasperReports.generateHtmlReport(reportsDefinitionFileName, outputFilename, databaseType,
                    databaseName, databaseUsername, databasePassword, databaseHost, parameters);
        }
        outputFileNames.add(outputFilename);
    }
    String emailRecipientList = commandLine.getOptionValue("emailto");
    if (emailRecipientList != null) {
        Set<String> emailRecipients = new HashSet<String>(Arrays.asList(emailRecipientList.split(",")));
        String emailSender = commandLine.getOptionValue("emailfrom");
        String emailSubject = commandLine.getOptionValue("emailsubject");
        if (emailSubject == null) {
            emailSubject = "Report attached";
        }
        String emailHost = commandLine.getOptionValue("emailhost");
        if (emailHost == null) {
            emailHost = "localhost";
        }
        String emailUser = commandLine.getOptionValue("emailuser");
        String emailPass = commandLine.getOptionValue("emailpass");
        System.out.println("Emailing reports to " + emailRecipients);
        runJasperReports.emailReport(emailHost, emailUser, emailPass, emailRecipients, emailSender,
                emailSubject, outputFileNames);
    } else {
        System.out.println("Email not generated (no recipients specified)");
    }
}

From source file:com.ilopez.jasperemail.JasperEmail.java

public static void main(String[] args) throws Exception {
    JasperEmail runJasperReports = new JasperEmail();
    // Set up command line parser
    Options options = new Options();

    Option reports = OptionBuilder.withArgName("reportlist").hasArg()
            .withDescription("Comma separated list of JasperReport XML input files").create("reports");
    options.addOption(reports);//from ww  w.j  av a  2 s . c  o m

    Option emailTo = OptionBuilder.withArgName("emailaddress").hasArg()
            .withDescription("Email address to send generated reports to").create("emailto");
    options.addOption(emailTo);

    Option emailFrom = OptionBuilder.withArgName("emailaddress").hasArg()
            .withDescription("Sender email address").create("emailfrom");
    options.addOption(emailFrom);

    Option emailSubjectLine = OptionBuilder.withArgName("emailsubject").hasArg()
            .withDescription("Subject line of email").create("emailsubject");
    options.addOption(emailSubjectLine);

    Option smtpHostOption = OptionBuilder.withArgName("smtphost").hasArg()
            .withDescription("Address of email server").create("smtphost");
    options.addOption(smtpHostOption);

    Option smtpUserOption = OptionBuilder.withArgName("smtpuser").hasArg()
            .withDescription("Username if email server requires authentication").create("smtpuser");
    options.addOption(smtpUserOption);

    Option smtpPassOption = OptionBuilder.withArgName("smtppass").hasArg()
            .withDescription("Password if email server requires authentication").create("smtppass");
    options.addOption(smtpPassOption);

    Option smtpAuthOption = OptionBuilder.withArgName("smtpauth").hasArg()
            .withDescription("Set SMTP Authentication").create("smtpauth");
    options.addOption(smtpAuthOption);

    Option smtpPortOption = OptionBuilder.withArgName("smtpport").hasArg()
            .withDescription("Port for the SMTP server 25/468/587/2525/2526").create("smtpport");
    options.addOption(smtpPortOption);

    Option smtpTypeOption = OptionBuilder.withArgName("smtptype").hasArg()
            .withDescription("Define SMTP Type, one of: " + Arrays.asList(OptionValues.SMTPType.values()))
            .create("smtptype");
    options.addOption(smtpTypeOption);

    Option outputFolder = OptionBuilder.withArgName("foldername").hasArg()
            .withDescription(
                    "Folder to write generated reports to, with trailing separator (slash or backslash)")
            .create("folder");
    options.addOption(outputFolder);

    Option dbJDBCClass = OptionBuilder.withArgName("jdbcclass").hasArg()
            .withDescription("Provide the JDBC Database Class ").create("jdbcclass");
    options.addOption(dbJDBCClass);

    Option dbJDBCURL = OptionBuilder.withArgName("jdbcurl").hasArg()
            .withDescription("Provide the JDBC Database URL").create("jdbcurl");
    options.addOption(dbJDBCURL);

    Option dbUserOption = OptionBuilder.withArgName("username").hasArg()
            .withDescription("Username to connect to databasewith").create("dbuser");
    options.addOption(dbUserOption);

    Option dbPassOption = OptionBuilder.withArgName("password").hasArg().withDescription("Database password")
            .create("dbpass");
    options.addOption(dbPassOption);

    Option outputTypeOption = OptionBuilder.withArgName("outputtype").hasArg()
            .withDescription("Output type, one of: " + Arrays.asList(OutputType.values())).create("output");
    options.addOption(outputTypeOption);

    Option outputFilenameOption = OptionBuilder.withArgName("outputfilename").hasArg()
            .withDescription("Output filename (excluding filetype suffix)").create("filename");
    options.addOption(outputFilenameOption);

    Option paramsOption = OptionBuilder.withArgName("parameters").hasArg().withDescription(
            "Parameters, e.g. param1=boolean:true,param2=string:ABC,param3=double:134.2,param4=integer:85")
            .create("params");
    options.addOption(paramsOption);

    // Parse command line
    CommandLineParser parser = new GnuParser();

    CommandLine commandLine = parser.parse(options, args);

    String reportsDefinitionFileNamesCvs = commandLine.getOptionValue("reports");
    if (reportsDefinitionFileNamesCvs == null) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar JasperEmail.jar", options);
        System.out.println();
        System.out.println("See http://github.com/ilopez/JasperEmail for further documentation");
        System.out.println();
        throw new IllegalArgumentException("No reports specified");
    }

    String outputPath = commandLine.getOptionValue("folder");
    List<String> reportDefinitionFileNames = Arrays.asList(reportsDefinitionFileNamesCvs.split(","));
    List<String> outputFileNames = new ArrayList<String>();

    String jdbcClass = commandLine.getOptionValue("jdbcclass");

    String jdbcURL = commandLine.getOptionValue("jdbcurl");
    String databaseUsername = commandLine.getOptionValue("dbuser");
    String databasePassword = commandLine.getOptionValue("dbpass");

    OutputType outputType = OutputType.PDF;
    String outputTypeString = commandLine.getOptionValue("output");
    if (outputTypeString != null) {
        outputType = OutputType.valueOf(outputTypeString.toUpperCase());
    }

    String parametersString = commandLine.getOptionValue("params");
    Map parameters = runJasperReports.prepareParameters(parametersString);
    String outputFilenameSpecified = commandLine.getOptionValue("filename");
    if (outputFilenameSpecified == null) {
        outputFilenameSpecified = "";
    }

    // SMTP PORT

    Integer smtpport = Integer.parseInt(commandLine.getOptionValue("smtpport"));
    Boolean smtpauth = Boolean.parseBoolean(commandLine.getOptionValue("smtpauth"));

    OptionValues.SMTPType smtptype;
    String smtptypestring = commandLine.getOptionValue("smtpenc");
    if (smtptypestring != null) {
        smtptype = OptionValues.SMTPType.valueOf(smtptypestring.toUpperCase());
    } else {
        smtptype = OptionValues.SMTPType.PLAIN;
    }

    // SMTP TLS
    // SMTP 

    // Iterate over reports, generating output for each
    for (String reportsDefinitionFileName : reportDefinitionFileNames) {
        String outputFilename = null;
        if ((reportDefinitionFileNames.size() == 1) && (!outputFilenameSpecified.equals(""))) {
            outputFilename = outputFilenameSpecified;
        } else {
            outputFilename = outputFilenameSpecified + reportsDefinitionFileName.replaceAll("\\..*$", "");
            outputFilename = outputFilename.replaceAll("^.*\\/", "");
            outputFilename = outputFilename.replaceAll("^.*\\\\", "");
        }
        outputFilename = outputFilename.replaceAll("\\W", "").toLowerCase() + "."
                + outputType.toString().toLowerCase();
        if (outputPath != null) {
            if (!outputPath.endsWith("\\") && !outputPath.endsWith("/")) {
                outputPath += java.io.File.separator;
            }
            outputFilename = outputPath + outputFilename;
        }
        System.out.println("Going to generate report " + outputFilename);

        runJasperReports.generateReport(reportsDefinitionFileName, jdbcClass, jdbcURL, databaseUsername,
                databasePassword, jdbcURL, parameters);
        outputFileNames.add(outputFilename);
    }
    String emailRecipientList = commandLine.getOptionValue("emailto");
    if (emailRecipientList != null) {
        Set<String> emailRecipients = new HashSet<String>(Arrays.asList(emailRecipientList.split(",")));
        String emailSender = commandLine.getOptionValue("emailfrom");
        String emailSubject = commandLine.getOptionValue("emailsubject");
        if (emailSubject == null) {
            emailSubject = "Report attached";
        }
        String emailHost = commandLine.getOptionValue("smtphost");
        if (emailHost == null) {
            emailHost = "localhost";
        }
        String emailUser = commandLine.getOptionValue("smtpuser");
        String emailPass = commandLine.getOptionValue("smtppass");
        System.out.println("Emailing reports to " + emailRecipients);
        runJasperReports.emailReport(emailHost, emailUser, emailPass, emailRecipients, emailSender,
                emailSubject, outputFileNames, smtpauth, smtptype, smtpport);
    } else {
        System.out.println("Email not generated (no recipients specified)");
    }
}

From source file:com.act.lcms.db.analysis.StandardIonAnalysis.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());//w ww .j  ava 2 s  . co m
    }

    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        System.err.format("Argument parsing failed: %s\n", e.getMessage());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    if (cl.hasOption("help")) {
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        return;
    }

    File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY));
    if (!lcmsDir.isDirectory()) {
        System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath());
        HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null,
                true);
        System.exit(1);
    }

    try (DB db = DB.openDBFromCLI(cl)) {
        ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir);
        StandardIonAnalysis analysis = new StandardIonAnalysis();
        HashMap<Integer, Plate> plateCache = new HashMap<>();

        String plateBarcode = cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE);
        String inputChemicals = cl.getOptionValue(OPTION_STANDARD_CHEMICAL);
        String medium = cl.getOptionValue(OPTION_MEDIUM);

        // If standard chemical is specified, do standard LCMS ion selection analysis
        if (inputChemicals != null && !inputChemicals.equals("")) {
            String[] chemicals;
            if (!inputChemicals.contains(",")) {
                chemicals = new String[1];
                chemicals[0] = inputChemicals;
            } else {
                chemicals = inputChemicals.split(",");
            }

            String outAnalysis = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + CSV_FORMAT;
            String plottingDirectory = cl.getOptionValue(OPTION_PLOTTING_DIR);
            String[] headerStrings = { "Molecule", "Plate Bar Code", "LCMS Detection Results" };
            CSVPrinter printer = new CSVPrinter(new FileWriter(outAnalysis),
                    CSVFormat.DEFAULT.withHeader(headerStrings));

            for (String inputChemical : chemicals) {
                List<StandardWell> standardWells;

                Plate queryPlate = Plate.getPlateByBarcode(db,
                        cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                if (plateBarcode != null && medium != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlateAndMedium(db,
                            inputChemical, queryPlate.getId(), medium);
                } else if (plateBarcode != null) {
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db, inputChemical,
                            queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, inputChemical);
                }

                if (standardWells.size() == 0) {
                    throw new RuntimeException("Found no LCMS wells for " + inputChemical);
                }

                // Sort in descending order of media where MeOH and Water related media are promoted to the top and
                // anything derived from yeast media are demoted.
                Collections.sort(standardWells, new Comparator<StandardWell>() {
                    @Override
                    public int compare(StandardWell o1, StandardWell o2) {
                        if (StandardWell.doesMediaContainYeastExtract(o1.getMedia())
                                && !StandardWell.doesMediaContainYeastExtract(o2.getMedia())) {
                            return 1;
                        } else {
                            return 0;
                        }
                    }
                });

                Map<StandardWell, StandardIonResult> wellToIonRanking = StandardIonAnalysis
                        .getBestMetlinIonsForChemical(inputChemical, lcmsDir, db, standardWells,
                                plottingDirectory);

                if (wellToIonRanking.size() != standardWells.size()
                        && !cl.hasOption(OPTION_OVERRIDE_NO_SCAN_FILE_FOUND)) {
                    throw new Exception("Could not find a scan file associated with one of the standard wells");
                }

                for (StandardWell well : wellToIonRanking.keySet()) {
                    LinkedHashMap<String, XZ> snrResults = wellToIonRanking.get(well).getAnalysisResults();

                    String snrRankingResults = "";
                    int numResultsToShow = 0;

                    Plate plateForWellToAnalyze = Plate.getPlateById(db, well.getPlateId());

                    for (Map.Entry<String, XZ> ionToSnrAndTime : snrResults.entrySet()) {
                        if (numResultsToShow > 3) {
                            break;
                        }

                        String ion = ionToSnrAndTime.getKey();
                        XZ snrAndTime = ionToSnrAndTime.getValue();

                        snrRankingResults += String.format(ion + " (%.2f SNR at %.2fs); ",
                                snrAndTime.getIntensity(), snrAndTime.getTime());
                        numResultsToShow++;
                    }

                    String[] resultSet = { inputChemical,
                            plateForWellToAnalyze.getBarcode() + " " + well.getCoordinatesString() + " "
                                    + well.getMedia() + " " + well.getConcentration(),
                            snrRankingResults };

                    printer.printRecord(resultSet);
                }
            }

            try {
                printer.flush();
                printer.close();
            } catch (IOException e) {
                System.err.println("Error while flushing/closing csv writer.");
                e.printStackTrace();
            }
        } else {
            // Get the set of chemicals that includes the construct and all it's intermediates
            Pair<ConstructEntry, List<ChemicalAssociatedWithPathway>> constructAndPathwayChems = analysis
                    .getChemicalsForConstruct(db, cl.getOptionValue(OPTION_CONSTRUCT));
            System.out.format("Construct: %s\n", constructAndPathwayChems.getLeft().getCompositionId());

            for (ChemicalAssociatedWithPathway pathwayChem : constructAndPathwayChems.getRight()) {
                System.out.format("  Pathway chem %s\n", pathwayChem.getChemical());

                // Get all the standard wells for the pathway chemicals. These wells contain only the
                // the chemical added with controlled solutions (ie no organism or other chemicals in the
                // solution)

                List<StandardWell> standardWells;

                if (plateBarcode != null) {
                    Plate queryPlate = Plate.getPlateByBarcode(db,
                            cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE));
                    standardWells = analysis.getStandardWellsForChemicalInSpecificPlate(db,
                            pathwayChem.getChemical(), queryPlate.getId());
                } else {
                    standardWells = analysis.getStandardWellsForChemical(db, pathwayChem.getChemical());
                }

                for (StandardWell wellToAnalyze : standardWells) {
                    List<StandardWell> negativeControls = analysis.getViableNegativeControlsForStandardWell(db,
                            wellToAnalyze);
                    Map<StandardWell, List<ScanFile>> allViableScanFiles = analysis
                            .getViableScanFilesForStandardWells(db, wellToAnalyze, negativeControls);

                    List<String> primaryStandardScanFileNames = new ArrayList<>();
                    for (ScanFile scanFile : allViableScanFiles.get(wellToAnalyze)) {
                        primaryStandardScanFileNames.add(scanFile.getFilename());
                    }
                    Plate plate = plateCache.get(wellToAnalyze.getPlateId());
                    if (plate == null) {
                        plate = Plate.getPlateById(db, wellToAnalyze.getPlateId());
                        plateCache.put(plate.getId(), plate);
                    }

                    System.out.format("    Standard well: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                            wellToAnalyze.getCoordinatesString(), wellToAnalyze.getChemical(),
                            wellToAnalyze.getMedia() == null ? ""
                                    : String.format(" in %s", wellToAnalyze.getMedia()),
                            wellToAnalyze.getConcentration() == null ? ""
                                    : String.format(" @ %s", wellToAnalyze.getConcentration()));
                    System.out.format("      Scan files: %s\n",
                            StringUtils.join(primaryStandardScanFileNames, ", "));

                    for (StandardWell negCtrlWell : negativeControls) {
                        plate = plateCache.get(negCtrlWell.getPlateId());
                        if (plate == null) {
                            plate = Plate.getPlateById(db, negCtrlWell.getPlateId());
                            plateCache.put(plate.getId(), plate);
                        }
                        List<String> negativeControlScanFileNames = new ArrayList<>();
                        for (ScanFile scanFile : allViableScanFiles.get(negCtrlWell)) {
                            negativeControlScanFileNames.add(scanFile.getFilename());
                        }

                        System.out.format("      Viable negative: %s @ %s, '%s'%s%s\n", plate.getBarcode(),
                                negCtrlWell.getCoordinatesString(), negCtrlWell.getChemical(),
                                negCtrlWell.getMedia() == null ? ""
                                        : String.format(" in %s", negCtrlWell.getMedia()),
                                negCtrlWell.getConcentration() == null ? ""
                                        : String.format(" @ %s", negCtrlWell.getConcentration()));
                        System.out.format("        Scan files: %s\n",
                                StringUtils.join(negativeControlScanFileNames, ", "));
                        // TODO: do something useful with the standard wells and their scan files, and then stop all the printing.
                    }
                }
            }
        }
    }
}