Example usage for org.apache.commons.cli DefaultParser DefaultParser

List of usage examples for org.apache.commons.cli DefaultParser DefaultParser

Introduction

In this page you can find the example usage for org.apache.commons.cli DefaultParser DefaultParser.

Prototype

DefaultParser

Source Link

Usage

From source file:com.cloudera.csd.tools.MetricTools.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    try {/* w ww  .j  a  v a2 s .c  om*/
        CommandLine cmdLine = parser.parse(OPTIONS, args);
        if (!cmdLine.getArgList().isEmpty()) {
            throw new ParseException("Unexpected extra arguments: " + cmdLine.getArgList());
        }
        Main main = new Main(cmdLine);
        main.run();
    } catch (ParseException ex) {
        IOUtils.write("Error: " + ex.getMessage() + "\n", System.err);
        printUsageMessage(System.err);
        System.exit(1);
    }
}

From source file:com.hpe.nv.samples.basic.BasicAnalyzeNVTransactions.java

public static void main(String[] args) {
    try {/*from www  . ja  v  a  2s. 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("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("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("BasicAnalyzeNVTransactions.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("zip-result-file-path")) {
            zipResultFilePath = line.getOptionValue("zip-result-file-path");
        }

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

        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 how to run transactions as part of an NV test.                                               ***"
                + newLine
                + "***                                                                                                                         ***"
                + newLine
                + "***   In this sample, the NV test starts with the \"3G Busy\" network scenario, running three transactions (see below).       ***"
                + newLine
                + "***   After the sample stops and analyzes the NV test, it prints the analysis .zip file path to the console.                ***"
                + newLine
                + "***                                                                                                                         ***"
                + newLine
                + "***   This sample runs three NV transactions:                                                                               ***"
                + newLine
                + "***   1. \"Home Page\" transaction: Navigates to the home page in the HPE Network Virtualization website                      ***"
                + newLine
                + "***   2. \"Get Started\" transaction: Navigates to the Get Started Now page in the HPE Network Virtualization website         ***"
                + newLine
                + "***   3. \"Overview\" transaction: Navigates back to the home page in the HPE Network Virtualization website                  ***"
                + newLine
                + "***                                                                                                                         ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicAnalyzeNVTransactions.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 - Start the NV test with the "3G Busy" network scenario                                                                   *****/
        printPartDescription("\b------    Part 1 - Start the NV test with the \"3G Busy\" network scenario");
        initTestManager();
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 2 - Run three transactions - "Home Page", "Get Started" and "Overview"                                                      *****/
        printPartDescription(
                "------    Part 2 - Run three transactions - \"Home Page\", \"Get Started\" and \"Overview\"");
        connectToTransactionManager();
        startTransaction(1);
        transactionInProgress = true;
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        stopTransaction(1);
        transactionInProgress = false;
        startTransaction(2);
        transactionInProgress = true;
        seleniumGetStartedClick();
        stopTransaction(2);
        transactionInProgress = false;
        startTransaction(3);
        transactionInProgress = true;
        seleniumOverviewClick();
        stopTransaction(3);
        transactionInProgress = false;
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 3 - Stop the NV test, analyze it and print the results to the console                                                       *****/
        printPartDescription(
                "------    Part 3 - Stop the NV test, analyze it and print the results to the console");
        stopTestAndAnalyze();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:at.asitplus.regkassen.demo.RKSVCashboxSimulator.java

public static void main(String[] args) {
    try {//ww w . j a v  a2s  .  c o  m
        //IMPORTANT HINT REGARDING STRING ENCODING
        //in Java all Strings have UTF-8 as default encoding
        //therefore: there are only a few references to UTF-8 encoding in this demo code
        //however, if values are retrieved from a database or another program language is used, then one needs to
        //make sure that the UTF-8 encoding is correctly implemented

        //this demo cashbox does not implement error handling
        //it should only demonstrate the core elements of the RKSV and any boilerplate code is avoided as much as possible
        //if an error occurs, only the stacktraces are logged
        //obviously this needs to be adapted in a productive cashbox

        //----------------------------------------------------------------------------------------------------
        //basic inits
        //add bouncycastle provider
        Security.addProvider(new BouncyCastleProvider());

        //----------------------------------------------------------------------------------------------------
        //check if unlimited strength policy files are installed, they are required for strong crypto algorithms ==> AES 256
        if (!CryptoUtil.isUnlimitedStrengthPolicyAvailable()) {
            System.out.println(
                    "Your JVM does not provide the unlimited strength policy. However, this policy is required to enable strong cryptography (e.g. AES with 256 bits). Please install the required policy files.");
            System.exit(0);
        }

        //----------------------------------------------------------------------------------------------------
        //parse cmd line options
        Options options = new Options();

        // add CMD line options
        options.addOption("o", "output-dir", true,
                "specify base output directory, if none is specified, a new directory will be created in the current working directory");
        //options.addOption("i", "simulation-file-or-directory", true, "cashbox simulation (file) or multiple cashbox simulation files (directory), if none is specified the internal test suites will be executed (can also be considered as demo mode)");
        options.addOption("v", "verbose", false, "dump demo receipts to cmd line");
        options.addOption("c", "closed system", false, "simulate closed system");

        ///parse CMD line options
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(options, args);

        //setup inputs from cmd line
        //verbose
        VERBOSE = cmd.hasOption("v");
        CLOSED_SYSTEM = cmd.hasOption("c");

        //output directory
        String outputParentDirectoryString = cmd.getOptionValue("o");
        if (outputParentDirectoryString == null) {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss");
            outputParentDirectoryString = "./CashBoxDemoOutput" + df.format(new Date());
        }
        File OUTPUT_PARENT_DIRECTORY = new File(outputParentDirectoryString);
        OUTPUT_PARENT_DIRECTORY.mkdirs();

        //----------------------------------------------------------------------------------------------------
        //external simulation runs... not implemented yet, currently only the internal test suites can be executed
        //String simulationFileOrDirectoryPath = cmd.getOptionValue("i");
        //handling of arbitrary input simulation files will be possible in 0.7
        //if (simulationFileOrDirectoryPath == null) {
        //} else {
        //                File simulationFileOrDirectory = new File(simulationFileOrDirectoryPath);
        //                cashBoxSimulationList = readCashBoxSimulationFromFile(simulationFileOrDirectory);
        //}

        List<CashBoxSimulation> cashBoxSimulationList = TestSuiteGenerator.getSimulationRuns();

        //setup simulation and execute
        int index = 1;
        for (CashBoxSimulation cashboxSimulation : cashBoxSimulationList) {
            System.out.println("Executing simulation run " + index + "/" + cashBoxSimulationList.size());
            System.out.println("Simulation run: " + cashboxSimulation.getSimulationRunLabel());
            index++;

            File testSetDirectory = new File(OUTPUT_PARENT_DIRECTORY,
                    cashboxSimulation.getSimulationRunLabel());
            testSetDirectory.mkdirs();

            CashBoxParameters cashBoxParameters = new CashBoxParameters();
            cashBoxParameters.setCashBoxId(cashboxSimulation.getCashBoxId());
            cashBoxParameters.setTurnOverCounterAESKey(
                    CryptoUtil.convertBase64KeyToSecretKey(cashboxSimulation.getBase64AesKey()));
            cashBoxParameters.setDepModul(new SimpleMemoryDEPModule());
            cashBoxParameters.setPrinterModule(new SimplePDFPrinterModule());
            cashBoxParameters.setCompanyID(cashboxSimulation.getCompanyID());

            //create pre-defined number of signature devices
            for (int i = 0; i < cashboxSimulation.getNumberOfSignatureDevices(); i++) {
                JWSModule jwsModule = new ManualJWSModule();
                SignatureModule signatureModule;
                if (!CLOSED_SYSTEM) {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule(
                            RKSuite.R1_AT100, null);
                } else {
                    signatureModule = new NEVER_USE_IN_A_REAL_SYSTEM_SoftwareKeySignatureModule(
                            cashboxSimulation.getCompanyID() + "-" + "K" + i);
                }
                jwsModule.setOpenSystemSignatureModule(signatureModule);
                cashBoxParameters.getJwsSignatureModules().add(jwsModule);
            }

            //init cashbox
            DemoCashBox demoCashBox = new DemoCashBox(cashBoxParameters);

            //exceute simulation run
            demoCashBox.executeSimulation(cashboxSimulation.getCashBoxInstructionList());

            //----------------------------------------------------------------------------------------------------
            //export DEP
            DEPExportFormat depExportFormat = demoCashBox.exportDEP();
            //get JSON rep and dump export format to file/std output
            File depExportFile = new File(testSetDirectory, "dep-export.json");
            dumpJSONRepOfObject(depExportFormat, depExportFile, true,
                    "------------DEP-EXPORT-FORMAT------------");

            //----------------------------------------------------------------------------------------------------
            //store signature certificates and AES key (so that they can be used for verification purposes)
            CryptographicMaterialContainer cryptographicMaterialContainer = new CryptographicMaterialContainer();
            HashMap<String, CertificateOrPublicKeyContainer> certificateContainerMap = new HashMap<>();
            cryptographicMaterialContainer.setCertificateOrPublicKeyMap(certificateContainerMap);

            //store AES key as BASE64 String
            //ATTENTION, this is only for demonstration purposes, the AES key must be stored in a secure location
            cryptographicMaterialContainer.setBase64AESKey(cashboxSimulation.getBase64AesKey());
            List<JWSModule> jwsSignatureModules = demoCashBox.getCashBoxParameters().getJwsSignatureModules();
            for (JWSModule jwsSignatureModule : jwsSignatureModules) {
                CertificateOrPublicKeyContainer certificateOrPublicKeyContainer = new CertificateOrPublicKeyContainer();
                certificateOrPublicKeyContainer.setId(jwsSignatureModule.getSerialNumberOfKeyID());
                certificateContainerMap.put(jwsSignatureModule.getSerialNumberOfKeyID(),
                        certificateOrPublicKeyContainer);
                X509Certificate certificate = (X509Certificate) jwsSignatureModule.getSignatureModule()
                        .getSigningCertificate();
                if (certificate == null) {
                    //must be public key based... (closed system)
                    PublicKey publicKey = jwsSignatureModule.getSignatureModule().getSigningPublicKey();
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(publicKey.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.PUBLIC_KEY);
                } else {
                    certificateOrPublicKeyContainer.setSignatureCertificateOrPublicKey(
                            CashBoxUtils.base64Encode(certificate.getEncoded(), false));
                    certificateOrPublicKeyContainer.setSignatureDeviceType(SignatureDeviceType.CERTIFICATE);
                }
            }

            File cryptographicMaterialContainerFile = new File(testSetDirectory,
                    "cryptographicMaterialContainer.json");
            dumpJSONRepOfObject(cryptographicMaterialContainer, cryptographicMaterialContainerFile, true,
                    "------------CRYPTOGRAPHIC MATERIAL------------");

            //----------------------------------------------------------------------------------------------------
            //export QR codes to file
            //dump machine readable code of receipts (this "code" is used for the QR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            //dump to File
            File qrCoreRepExportFile = new File(testSetDirectory, "qr-code-rep.json");
            List<ReceiptPackage> receiptPackages = demoCashBox.getStoredReceipts();
            List<String> qrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                qrCodeRepList.add(CashBoxUtils.getQRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(qrCodeRepList, qrCoreRepExportFile, true,
                    "------------QR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //export OCR codes to file
            //dump machine readable code of receipts (this "code" is used for the OCR-codes)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            //dump to File
            File ocrCoreRepExportFile = new File(testSetDirectory, "ocr-code-rep.json");
            List<String> ocrCodeRepList = new ArrayList<>();
            for (ReceiptPackage receiptPackage : receiptPackages) {
                ocrCodeRepList.add(CashBoxUtils.getOCRCodeRepresentationFromJWSCompactRepresentation(
                        receiptPackage.getJwsCompactRepresentation()));
            }
            dumpJSONRepOfObject(ocrCodeRepList, ocrCoreRepExportFile, true,
                    "------------OCR-CODE-REP------------");

            //----------------------------------------------------------------------------------------------------
            //create PDF receipts and print to directory
            //REF TO SPECIFICATION: Detailspezifikation/Abs 12
            File qrCodeDumpDirectory = new File(testSetDirectory, "qr-code-dir-pdf");
            qrCodeDumpDirectory.mkdirs();
            List<byte[]> printedQRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.QR_CODE);
            CashBoxUtils.writeReceiptsToFiles(printedQRCodeReceipts, "QR-", qrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //export receipts as PDF (OCR)
            //REF TO SPECIFICATION: Detailspezifikation/Abs 14
            File ocrCodeDumpDirectory = new File(testSetDirectory, "ocr-code-dir-pdf");
            ocrCodeDumpDirectory.mkdirs();
            List<byte[]> printedOCRCodeReceipts = demoCashBox.printReceipt(receiptPackages,
                    ReceiptPrintType.OCR);
            CashBoxUtils.writeReceiptsToFiles(printedOCRCodeReceipts, "OCR-", ocrCodeDumpDirectory);

            //----------------------------------------------------------------------------------------------------
            //dump executed testsuite
            File testSuiteDumpFile = new File(testSetDirectory,
                    cashboxSimulation.getSimulationRunLabel() + ".json");
            dumpJSONRepOfObject(cashboxSimulation, testSuiteDumpFile, true,
                    "------------CASHBOX Simulation------------");
        }
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.act.biointerpretation.sarinference.LibMcsClustering.java

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

    // Build command line parser.
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());// w w w  .ja v a2  s  . c  o m
    }
    CommandLine cl = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cl = parser.parse(opts, args);
    } catch (ParseException e) {
        LOGGER.error("Argument parsing failed: %s", e.getMessage());
        exitWithHelp(opts);
    }

    // Print help.
    if (cl.hasOption(OPTION_HELP)) {
        HELP_FORMATTER.printHelp(L2FilteringDriver.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    File inputCorpusFile = new File(cl.getOptionValue(OPTION_PREDICTION_CORPUS));
    File positiveInchisFile = new File(cl.getOptionValue(OPTION_POSITIVE_INCHIS));
    File sartreeFile = new File(cl.getOptionValue(OPTION_SARTREE_PATH));
    File scoredSarFile = new File(cl.getOptionValue(OPTION_SCORED_SAR_PATH));

    JavaRunnable clusterer = getClusterer(inputCorpusFile, sartreeFile);
    JavaRunnable scorer = getSarScorer(inputCorpusFile, sartreeFile, positiveInchisFile, scoredSarFile,
            SAR_SCORING_FUNCTION, THRESHOLD_TREE_SIZE);

    LOGGER.info("Running clustering.");
    clusterer.run();

    LOGGER.info("Running sar scoring.");
    scorer.run();

    LOGGER.info("Complete!.");
}

From source file:com.dsf.dbxtract.cdc.App.java

/**
 * <p>/*ww  w  .j  av  a2s  . c  o  m*/
 * Starts the dbxtract app.
 * </p>
 * <p>
 * usage: java -jar dbxtract.jar --config &lt;file&gt; [--list | --start]
 * </p>
 * 
 * <pre>
 * --config &lt;file&gt; configuration file pathname
 * --list          list configuration parameters and values
 * --start         start dbxtract agent
 * </pre>
 * 
 * @param args
 *            execution call arguments
 */
public static void main(String[] args) {

    Options options = prepareCmdLineOptions();
    try {
        CommandLineParser parser = new DefaultParser();

        CommandLine cmd = parser.parse(options, args);
        parseCommand(cmd);

    } catch (ParseException e1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar dbxtract.jar", options, true);

        error("Unable to parse parameters", e1);

    } catch (Exception e) {
        error("Unable to start dbxtract", e);
    }
}

From source file:com.vmware.photon.controller.common.auth.AuthOIDCRegistrar.java

public static int main(String[] args) {
    Options options = new Options();
    options.addOption(USERNAME_ARG, true, "Lightwave user name");
    options.addOption(PASSWORD_ARG, true, "Password");
    options.addOption(TARGET_ARG, true, "Registration Hostname or IPAddress"); // Possible
                                                                               // load-balancer
                                                                               // address
    options.addOption(MANAGEMENT_UI_REG_FILE_ARG, true, "Management UI Registration Path");
    options.addOption(SWAGGER_UI_REG_FILE_ARG, true, "Swagger UI Registration Path");
    options.addOption(HELP_ARG, false, "Help");

    try {/*w ww.  j a v  a 2 s . c om*/
        String username = null;
        String password = null;
        String registrationAddress = null;
        String mgmtUiRegPath = null;
        String swaggerUiRegPath = null;

        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = null;
        cmd = parser.parse(options, args);

        if (cmd.hasOption(HELP_ARG)) {
            showUsage(options);
            return 0;
        }

        if (cmd.hasOption(USERNAME_ARG)) {
            username = cmd.getOptionValue(USERNAME_ARG);
        }

        if (cmd.hasOption(PASSWORD_ARG)) {
            password = cmd.getOptionValue(PASSWORD_ARG);
        }

        if (cmd.hasOption(TARGET_ARG)) {
            registrationAddress = cmd.getOptionValue(TARGET_ARG);
        }

        if (cmd.hasOption(MANAGEMENT_UI_REG_FILE_ARG)) {
            mgmtUiRegPath = cmd.getOptionValue(MANAGEMENT_UI_REG_FILE_ARG);
        }

        if (cmd.hasOption(SWAGGER_UI_REG_FILE_ARG)) {
            swaggerUiRegPath = cmd.getOptionValue(SWAGGER_UI_REG_FILE_ARG);
        }

        if (username == null || username.trim().isEmpty()) {
            throw new UsageException("Error: username is not specified");
        }

        if (password == null) {
            char[] passwd = System.console().readPassword("Password:");
            password = new String(passwd);
        }

        DomainInfo domainInfo = DomainInfo.build();

        AuthOIDCRegistrar registrar = new AuthOIDCRegistrar(domainInfo);

        registrar.register(registrationAddress, username, password, mgmtUiRegPath, swaggerUiRegPath);

        return 0;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        return ERROR_PARSE_EXCEPTION;
    } catch (UsageException e) {
        System.err.println(e.getMessage());
        showUsage(options);
        return ERROR_USAGE_EXCEPTION;
    } catch (AuthException e) {
        System.err.println(e.getMessage());
        return ERROR_AUTH_EXCEPTION;
    }
}

From source file:com.examples.cloud.speech.AsyncRecognizeClient.java

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

    String audioFile = "";
    String host = "speech.googleapis.com";
    Integer port = 443;/*from  w  w  w  .  ja v  a 2  s  .  co  m*/
    Integer sampling = 16000;

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("uri").withDescription("path to audio uri").hasArg()
            .withArgName("FILE_PATH").create());
    options.addOption(
            OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com")
                    .hasArg().withArgName("ENDPOINT").create());
    options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg()
            .withArgName("PORT").create());
    options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000")
            .hasArg().withArgName("RATE").create());

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("uri")) {
            audioFile = line.getOptionValue("uri");
        } else {
            System.err.println("An Audio uri must be specified (e.g. file:///foo/baz.raw).");
            System.exit(1);
        }

        if (line.hasOption("host")) {
            host = line.getOptionValue("host");
        } else {
            System.err.println("An API enpoint must be specified (typically speech.googleapis.com).");
            System.exit(1);
        }

        if (line.hasOption("port")) {
            port = Integer.parseInt(line.getOptionValue("port"));
        } else {
            System.err.println("An SSL port must be specified (typically 443).");
            System.exit(1);
        }

        if (line.hasOption("sampling")) {
            sampling = Integer.parseInt(line.getOptionValue("sampling"));
        } else {
            System.err.println("An Audio sampling rate must be specified.");
            System.exit(1);
        }
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    ManagedChannel channel = AsyncRecognizeClient.createChannel(host, port);

    AsyncRecognizeClient client = new AsyncRecognizeClient(channel, URI.create(audioFile), sampling);
    try {
        client.recognize();
    } finally {
        client.shutdown();
    }
}

From source file:erigo.filepump.FilePump.java

public static void main(String[] argsI) {

    boolean local_bShowGUI = true;

    String initial_outputFolder = ".";
    double initial_filesPerSec = 1.0;
    int initial_totNumFiles = 1000;
    String initial_mode_str = "local";
    String initial_ftpHost;//w w  w . j  a  va 2  s  . co  m
    String initial_ftpUser;
    String initial_ftpPassword;

    //
    // Parse command line arguments
    //
    // We use the Apche Commons CLI library to handle command line
    // arguments. See https://commons.apache.org/proper/commons-cli/usage.html
    // for examples, although note that we use the more up-to-date form
    // (Option.builder) to create Option objects.
    //
    // 1. Setup command line options
    //
    Options options = new Options();
    // Example of a Boolean option (i.e., only the flag, no argument goes with it)
    options.addOption("h", "help", false, "Print this message.");
    // The following example is for: -outputfolder <folder>    Location of output files
    Option outputFolderOption = Option.builder("outputfolder").argName("folder").hasArg()
            .desc("Location of output files; this folder must exist (it will not be created); default = \""
                    + initial_outputFolder + "\".")
            .build();
    options.addOption(outputFolderOption);
    Option filesPerSecOption = Option.builder("fps").argName("filespersec").hasArg()
            .desc("Desired file rate, files/sec; default = " + initial_filesPerSec + ".").build();
    options.addOption(filesPerSecOption);
    Option totNumFilesOption = Option.builder("totnum").argName("num").hasArg().desc(
            "Total number of output files; use -1 for unlimited number; default = " + initial_totNumFiles + ".")
            .build();
    options.addOption(totNumFilesOption);
    Option outputModeOption = Option.builder("mode").argName("mode").hasArg()
            .desc("Specifies output interface, one of <local|ftp|sftp>; default = " + initial_mode_str + ".")
            .build();
    options.addOption(outputModeOption);
    Option ftpHostOption = Option.builder("ftphost").argName("host").hasArg()
            .desc("Host name, for FTP or SFTP.").build();
    options.addOption(ftpHostOption);
    Option ftpUsernameOption = Option.builder("ftpuser").argName("user").hasArg()
            .desc("Username, for FTP or SFTP.").build();
    options.addOption(ftpUsernameOption);
    Option ftpPasswordOption = Option.builder("ftppass").argName("password").hasArg()
            .desc("Password, for FTP or SFTP.").build();
    options.addOption(ftpPasswordOption);
    Option autoRunOption = new Option("x", "Automatically run at startup.");
    options.addOption(autoRunOption);
    //
    // 2. Parse command line options
    //
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, argsI);
    } catch (ParseException exp) {
        // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }
    //
    // 3. Retrieve the command line values
    //
    if (line.hasOption("help")) {
        // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("FilePump", options);
        return;
    }
    if (line.hasOption("x")) {
        local_bShowGUI = false;
    }
    // Where to write the files to
    initial_outputFolder = line.getOptionValue("outputfolder", initial_outputFolder);
    // How many files per second the pump should output
    try {
        initial_filesPerSec = Double.parseDouble(line.getOptionValue("fps", "" + initial_filesPerSec));
    } catch (NumberFormatException nfe) {
        System.err.println("\nError parsing \"fps\" (it should be a floating point value):\n" + nfe);
        return;
    }
    // Total number of files to write out; -1 indicates unlimited
    try {
        initial_totNumFiles = Integer.parseInt(line.getOptionValue("totnum", "" + initial_totNumFiles));
    } catch (NumberFormatException nfe) {
        System.err.println("\nError parsing \"totnum\" (it should be an integer):\n" + nfe);
        return;
    }
    // Specifies how files will be written out
    initial_mode_str = line.getOptionValue("mode", initial_mode_str);
    if (!initial_mode_str.equals("local") && !initial_mode_str.equals("ftp")
            && !initial_mode_str.equals("sftp")) {
        System.err.println(new String("\nUnrecognized mode, \"" + initial_mode_str + "\""));
        return;
    }
    // FTP hostname
    initial_ftpHost = line.getOptionValue("ftphost", "");
    // FTP username
    initial_ftpUser = line.getOptionValue("ftpuser", "");
    // FTP password
    initial_ftpPassword = line.getOptionValue("ftppass", "");

    // Create the FilePump object
    new FilePump(local_bShowGUI, initial_outputFolder, initial_filesPerSec, initial_totNumFiles,
            initial_mode_str, initial_ftpHost, initial_ftpUser, initial_ftpPassword);

}

From source file:com.twitter.heron.healthmgr.HealthManager.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    Options slaManagerCliOptions = constructCliOptions();

    // parse the help options first.
    Options helpOptions = constructHelpOptions();
    CommandLine cmd = parser.parse(helpOptions, args, true);
    if (cmd.hasOption("h")) {
        usage(slaManagerCliOptions);/*from  w  ww.jav a2s .  c  om*/
        return;
    }

    try {
        cmd = parser.parse(slaManagerCliOptions, args);
    } catch (ParseException e) {
        usage(slaManagerCliOptions);
        throw new RuntimeException("Error parsing command line options: ", e);
    }

    HealthManagerMode mode = HealthManagerMode.cluster;
    if (hasOption(cmd, CliArgs.MODE)) {
        mode = HealthManagerMode.valueOf(getOptionValue(cmd, CliArgs.MODE));
    }

    Config config;
    switch (mode) {
    case cluster:
        config = Config.toClusterMode(Config.newBuilder().putAll(ConfigLoader.loadClusterConfig())
                .putAll(commandLineConfigs(cmd)).build());
        break;

    case local:
        if (!hasOption(cmd, CliArgs.HERON_HOME) || !hasOption(cmd, CliArgs.CONFIG_PATH)) {
            throw new IllegalArgumentException("Missing heron_home or config_path argument");
        }
        String heronHome = getOptionValue(cmd, CliArgs.HERON_HOME);
        String configPath = getOptionValue(cmd, CliArgs.CONFIG_PATH);
        config = Config.toLocalMode(
                Config.newBuilder().putAll(ConfigLoader.loadConfig(heronHome, configPath, null, null))
                        .putAll(commandLineConfigs(cmd)).build());
        break;

    default:
        throw new IllegalArgumentException("Invalid mode: " + getOptionValue(cmd, CliArgs.MODE));
    }

    setupLogging(cmd, config);

    LOG.info("Static Heron config loaded successfully ");
    LOG.fine(config.toString());

    // load the default config value and override with any command line values
    String metricSourceClassName = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_TYPE.key());
    metricSourceClassName = getOptionValue(cmd, CliArgs.METRIC_SOURCE_TYPE, metricSourceClassName);

    String metricsUrl = config.getStringValue(PolicyConfigKey.METRIC_SOURCE_URL.key());
    metricsUrl = getOptionValue(cmd, CliArgs.METRIC_SOURCE_URL, metricsUrl);

    AbstractModule module = buildMetricsProviderModule(metricsUrl, metricSourceClassName);
    HealthManager healthManager = new HealthManager(config, module);

    LOG.info("Initializing health manager");
    healthManager.initialize();

    LOG.info("Starting Health Manager metirc posting thread");
    HealthManagerMetrics publishingMetricsRunnable = null;
    if (hasOption(cmd, CliArgs.METRICSMGR_PORT)) {
        publishingMetricsRunnable = new HealthManagerMetrics(
                Integer.valueOf(getOptionValue(cmd, CliArgs.METRICSMGR_PORT)));
    }

    LOG.info("Starting Health Manager");
    PoliciesExecutor policyExecutor = new PoliciesExecutor(healthManager.healthPolicies);
    ScheduledFuture<?> future = policyExecutor.start();
    if (publishingMetricsRunnable != null) {
        new Thread(publishingMetricsRunnable).start();
    }
    try {
        future.get();
    } finally {
        policyExecutor.destroy();
        if (publishingMetricsRunnable != null) {
            publishingMetricsRunnable.close();
        }
    }
}

From source file:gobblin.yarn.GobblinYarnTaskRunner.java

public static void main(String[] args) throws Exception {
    Options options = buildOptions();//  w w  w  . ja  v  a  2 s  .com
    try {
        CommandLine cmd = new DefaultParser().parse(options, args);
        if (!cmd.hasOption(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME)
                || !cmd.hasOption(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME)) {
            printUsage(options);
            System.exit(1);
        }

        Log4jConfigurationHelper.updateLog4jConfiguration(GobblinTaskRunner.class,
                GobblinYarnConfigurationKeys.GOBBLIN_YARN_LOG4J_CONFIGURATION_FILE,
                GobblinYarnConfigurationKeys.GOBBLIN_YARN_LOG4J_CONFIGURATION_FILE);

        LOGGER.info(JvmUtils.getJvmInputArguments());

        ContainerId containerId = ConverterUtils
                .toContainerId(System.getenv().get(ApplicationConstants.Environment.CONTAINER_ID.key()));
        String applicationName = cmd
                .getOptionValue(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME);
        String helixInstanceName = cmd
                .getOptionValue(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME);

        GobblinTaskRunner gobblinTaskRunner = new GobblinYarnTaskRunner(applicationName, helixInstanceName,
                containerId, ConfigFactory.load(), Optional.<Path>absent());
        gobblinTaskRunner.start();
    } catch (ParseException pe) {
        printUsage(options);
        System.exit(1);
    }
}