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

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

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:edu.usc.pgroup.floe.client.commands.KillApp.java

/**
 * Entry point for Scale command.//w w  w  . j  a va2  s.c o m
 * @param args command line arguments sent by the floe.py script.
 */
public static void main(final String[] args) {

    Options options = new Options();

    Option appOption = OptionBuilder.withArgName("name").hasArg().isRequired()
            .withDescription("Application Name").create("app");

    options.addOption(appOption);

    CommandLineParser parser = new BasicParser();
    CommandLine line;

    try {
        line = parser.parse(options, args);

    } catch (ParseException e) {
        LOGGER.error("Invalid command: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scale options", options);
        return;
    }

    String app = line.getOptionValue("app");

    LOGGER.info("Application: {}", app);

    try {
        FloeClient.getInstance().killApp(app);
    } catch (TException e) {
        LOGGER.error("Error while connecting to the coordinator: {}", e);
    }
}

From source file:ca.ualberta.exemplar.core.Exemplar.java

public static void main(String[] rawArgs) throws FileNotFoundException, UnsupportedEncodingException {

    CommandLineParser cli = new BasicParser();

    Options options = new Options();
    options.addOption("h", "help", false, "shows this message");
    options.addOption("b", "benchmark", true, "expects input to be a benchmark file (type = binary | nary)");
    options.addOption("p", "parser", true, "defines which parser to use (parser = stanford | malt)");

    CommandLine line = null;/*  w  w  w. j a  v  a2s  .c  o  m*/

    try {
        line = cli.parse(options, rawArgs);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        System.exit(1);
    }

    String[] args = line.getArgs();
    String parserName = line.getOptionValue("parser", "malt");

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar", options);
        System.exit(0);
    }

    if (args.length != 2) {
        System.out.println("error: exemplar requires an input file and output file.");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sh ./exemplar <input> <output>", options);
        System.exit(0);
    }

    File input = new File(args[0]);
    File output = new File(args[1]);

    String benchmarkType = line.getOptionValue("benchmark", "");
    if (!benchmarkType.isEmpty()) {
        if (benchmarkType.equals("binary")) {
            BenchmarkBinary evaluation = new BenchmarkBinary(input, output, parserName);
            evaluation.runAndTime();
            System.exit(0);
        } else {
            if (benchmarkType.equals("nary")) {
                BenchmarkNary evaluation = new BenchmarkNary(input, output, parserName);
                evaluation.runAndTime();
                System.exit(0);
            } else {
                System.out.println("error: benchmark option has to be either 'binary' or 'nary'.");
                System.exit(0);
            }
        }
    }

    Parser parser = null;
    if (parserName.equals("stanford")) {
        parser = new ParserStanford();
    } else {
        if (parserName.equals("malt")) {
            parser = new ParserMalt();
        } else {
            System.out.println(parserName + " is not a valid parser.");
            System.exit(0);
        }
    }

    System.out.println("Starting EXEMPLAR...");

    RelationExtraction exemplar = null;
    try {
        exemplar = new RelationExtraction(parser);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    BlockingQueue<String> inputQueue = new ArrayBlockingQueue<String>(QUEUE_SIZE);
    PlainTextReader reader = null;
    reader = new PlainTextReader(inputQueue, input);

    Thread readerThread = new Thread(reader);
    readerThread.start();

    PrintStream statementsOut = null;

    try {
        statementsOut = new PrintStream(output, "UTF-8");
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        System.exit(0);
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
        System.exit(0);
    }

    statementsOut.println("Subjects\tRelation\tObjects\tNormalized Relation\tSentence");

    while (true) {
        String doc = null;
        try {
            doc = inputQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (doc.isEmpty()) {
            break;
        }

        List<RelationInstance> instances = exemplar.extractRelations(doc);

        for (RelationInstance instance : instances) {

            // Output SUBJ arguments in a separate field, for clarity
            boolean first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("SUBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }

            // Output the original relation
            statementsOut.print("\t" + instance.getOriginalRelation() + "\t");

            // Output the DOBJ arguments, followed by POBJ
            first = true;
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.equals("DOBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            for (Argument arg : instance.getArguments()) {
                if (arg.argumentType.startsWith("POBJ")) {
                    if (first) {
                        first = false;
                    } else {
                        statementsOut.print(",,");
                    }
                    statementsOut.print(arg.argumentType + ":" + arg.entityId);
                }
            }
            statementsOut.print("\t" + instance.getNormalizedRelation());
            statementsOut.print("\t" + instance.getSentence());
            statementsOut.println();
        }
    }

    System.out.println("Done!");
    statementsOut.close();

}

From source file:edu.toronto.cs.xcurator.cli.CLIRunner.java

public static void main(String[] args) {
    Options options = setupOptions();/* www .  j av  a  2s .  c om*/
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption('t')) {
            fileType = line.getOptionValue('t');
        } else {
            fileType = XML;
        }
        if (line.hasOption('o')) {
            tdbDirectory = line.getOptionValue('o');
            File d = new File(tdbDirectory);
            if (!d.exists() || !d.isDirectory()) {
                throw new Exception("TDB directory does not exist, please create.");
            }
        }
        if (line.hasOption('h')) {
            domain = line.getOptionValue('h');
            try {
                URL url = new URL(domain);
            } catch (MalformedURLException ex) {
                throw new Exception("The domain name is ill-formed");
            }
        } else {
            printHelpAndExit(options);
        }
        if (line.hasOption('m')) {
            serializeMapping = true;
            mappingFilename = line.getOptionValue('m');
        }
        if (line.hasOption('d')) {
            dirLocation = line.getOptionValue('d');
            inputStreams = new ArrayList<>();
            final List<String> files = Util.getFiles(dirLocation);
            for (String inputfile : files) {
                File f = new File(inputfile);
                if (f.isFile() && f.exists()) {
                    System.out.println("Adding document to mapping discoverer: " + inputfile);
                    inputStreams.add(new FileInputStream(f));
                } // If it is a URL download link for the document from SEC
                else if (inputfile.startsWith("http") && inputfile.contains("://")) {
                    // Download
                    System.out.println("Adding remote document to mapping discoverer: " + inputfile);
                    try {
                        URL url = new URL(inputfile);
                        InputStream remoteDocumentStream = url.openStream();
                        inputStreams.add(remoteDocumentStream);
                    } catch (MalformedURLException ex) {
                        throw new Exception("The document URL is ill-formed: " + inputfile);
                    } catch (IOException ex) {
                        throw new Exception("Error in downloading remote document: " + inputfile);
                    }
                } else {
                    throw new Exception("Cannot open XBRL document: " + f.getName());
                }
            }
        }

        if (line.hasOption('f')) {
            fileLocation = line.getOptionValue('f');
            inputStreams = new ArrayList<>();
            File f = new File(fileLocation);
            if (f.isFile() && f.exists()) {
                System.out.println("Adding document to mapping discoverer: " + fileLocation);
                inputStreams.add(new FileInputStream(f));
            } // If it is a URL download link for the document from SEC
            else if (fileLocation.startsWith("http") && fileLocation.contains("://")) {
                // Download
                System.out.println("Adding remote document to mapping discoverer: " + fileLocation);
                try {
                    URL url = new URL(fileLocation);
                    InputStream remoteDocumentStream = url.openStream();
                    inputStreams.add(remoteDocumentStream);
                } catch (MalformedURLException ex) {
                    throw new Exception("The document URL is ill-formed: " + fileLocation);
                } catch (IOException ex) {
                    throw new Exception("Error in downloading remote document: " + fileLocation);
                }
            } else {

                throw new Exception("Cannot open XBRL document: " + f.getName());
            }

        }

        setupDocumentBuilder();
        RdfFactory rdfFactory = new RdfFactory(new RunConfig(domain));
        List<Document> documents = new ArrayList<>();
        for (InputStream inputStream : inputStreams) {
            Document dataDocument = null;
            if (fileType.equals(JSON)) {
                String json = IOUtils.toString(inputStream);
                final String xml = Util.json2xml(json);
                final InputStream xmlInputStream = IOUtils.toInputStream(xml);
                dataDocument = createDocument(xmlInputStream);
            } else {
                dataDocument = createDocument(inputStream);
            }
            documents.add(dataDocument);
        }
        if (serializeMapping) {
            System.out.println("Mapping file will be saved to: " + new File(mappingFilename).getAbsolutePath());
            rdfFactory.createRdfs(documents, tdbDirectory, mappingFilename);
        } else {
            rdfFactory.createRdfs(documents, tdbDirectory);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        System.err.println("Unexpected exception: " + ex.getMessage());
        System.exit(1);
    }
}

From source file:com.google.code.stackexchange.client.examples.AsyncApiExample.java

/**
 * The main method.// w  w w . j av  a  2 s.com
 * 
 * @param args the arguments
 * 
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    Options options = buildOptions();
    try {
        CommandLine line = new BasicParser().parse(options, args);
        processCommandLine(line, options);
    } catch (ParseException exp) {
        System.err.println(exp.getMessage());
        printHelp(options);
    }
}

From source file:com.virtualparadigm.packman.cli.Main.java

public static void main(String[] args) {
    if (args.length > 0) {
        CommandLineParser cliParser = new BasicParser();
        CommandLine cmd = null;//  w  ww .j ava2  s .  c o  m
        try {
            cmd = cliParser.parse(Main.buildCommandLineOptions(), args);
        } catch (ParseException pe) {
            throw new RuntimeException(pe);
        }
        if (cmd != null) {
            boolean status = false;
            if (CMD_CREATE.equalsIgnoreCase(args[0])) {
                status = JPackageManager.createPackage(cmd.getOptionValue(CMD_OPTION_LONG_PACKAGE_NAME),
                        cmd.getOptionValue(CMD_OPTION_LONG_PACKAGE_VERSION),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_PACKAGE_FILE)),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_OLD_STATE_DIR)),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_NEW_STATE_DIR)),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_LICENSE_FILE)),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_AUTORUN_INSTALL_DIR)),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_AUTORUN_UNINSTALL_DIR)),
                        (cmd.getOptionValue(CMD_OPTION_LONG_TEMP_DIR) == null) ? null
                                : new File(cmd.getOptionValue(CMD_OPTION_LONG_TEMP_DIR)),
                        (cmd.getOptionValue(CMD_OPTION_LONG_DEV_MODE) != null)
                                ? Boolean.valueOf(cmd.getOptionValue(CMD_OPTION_LONG_DEV_MODE))
                                : false);

                if (status) {
                    System.out.println("Package creation successful");
                } else {
                    System.out.println("Package creation failed");
                }
            } else if (CMD_INSTALL.equalsIgnoreCase(args[0])) {
                status = JPackageManager.installPackage(
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_PACKAGE_FILE)),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_TARGET_DIR)),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_DATA_DIR)),
                        new File(cmd.getOptionValue(CMD_OPTION_LONG_LOCAL_CONFIG_FILE)),
                        (cmd.getOptionValue(CMD_OPTION_LONG_DEV_MODE) != null)
                                ? Boolean.valueOf(cmd.getOptionValue(CMD_OPTION_LONG_DEV_MODE))
                                : false);

                if (status) {
                    System.out.println("Package installation successful");
                } else {
                    System.out.println("Package installation failed");
                }

            } else if (CMD_LIST.equalsIgnoreCase(args[0])) {
                System.out.println("Installed Packages");
                System.out.println("");
                Collection<Package> installedPackages = JPackageManager.listPackages();
                if (installedPackages != null) {
                    for (Package installedPackage : installedPackages) {
                        System.out.println("package: " + installedPackage.getName());
                        System.out.println("  version: " + installedPackage.getVersion());
                        System.out.println("  timestamp: " + installedPackage.getInstallTimestamp());
                        System.out.println("  root directory: " + installedPackage.getRootDirectory());
                        System.out.println("");
                    }
                }
            } else {
                System.out.println("unsupported JPatchManager operation");
            }
        } else {
            System.out.println("No command specified. Options are:");
            System.out.println("  " + CMD_CREATE);
            System.out.println("  " + CMD_INSTALL);
            System.out.println("  " + CMD_LIST);
        }
    }
}

From source file:fr.tpt.atlanalyser.tests.TestOldAGTExpPost2Pre.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {

    // URL resource = Thread.currentThread().getContextClassLoader()
    // .getResource("OldAGTExp");
    // System.out.println(resource.toString());
    // File f = new File(resource.getPath());
    // System.out.println(f.toString());
    // System.out.println(f.isDirectory());
    // System.exit(0);

    Options options = new Options();
    options.addOption(/*w w  w  .  j a  va 2 s. co m*/
            OptionBuilder.hasArg().withArgName("N").withDescription("Number of parallel jobs").create("j"));
    options.addOption(OptionBuilder.withDescription("Display help").create("h"));

    CommandLineParser parser = new BasicParser();
    int jobs = 1;
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            new HelpFormatter().printHelp(TestOldAGTExpPost2Pre.class.getSimpleName(), options);
            System.exit(0);
        }

        if (cmd.hasOption("j")) {
            jobs = Integer.parseInt(cmd.getOptionValue("j"));
        }
    } catch (Exception e) {
        System.out.println("Incorrect command line arguments");
        new HelpFormatter().printHelp(TestOldAGTExpPost2Pre.class.getSimpleName(), options);
        System.exit(1);
    }

    new TestOldAGTExpPost2Pre(models().iterator().next()[0], jobs).testPost2Pre();
}

From source file:craterdog.security.DigitalNotaryMain.java

public static void main(String[] args) throws ParseException, IOException {
    HelpFormatter help = new HelpFormatter();
    Options options = new Options();
    options.addOption("help", false, "print this message");
    options.addOption("pubfile", true, "public key input file");
    options.addOption("prvfile", true, "private key input file");

    try {/*from   ww w  . j  a va 2 s  . c  om*/
        CommandLine cli = new BasicParser().parse(options, args);
        String pubfile = cli.getOptionValue("pubfile");
        String prvfile = cli.getOptionValue("prvfile");

        NotaryKey notaryKey = notarization.generateNotaryKey();

        if (pubfile != null || prvfile != null) {
            if (pubfile == null)
                throw new MissingArgumentException("Missing option: pubfile");
            if (prvfile == null)
                throw new MissingArgumentException("Missing option: prvfile");

            CertificateManager manager = new RsaCertificateManager();
            PublicKey publicKey = manager.decodePublicKey(FileUtils.readFileToString(new File(pubfile)));
            char[] password = System.console().readPassword("input private key password: ");
            PrivateKey privateKey = manager.decodePrivateKey(FileUtils.readFileToString(new File(prvfile)),
                    password);

            notaryKey.signingKey = privateKey;
            notaryKey.verificationKey = publicKey;

            // make sure it works
            DigitalSeal seal = notarization.notarizeDocument("test document", "test document", notaryKey);
            notarization.documentIsValid("test document", seal, publicKey);
        }
        char[] password = System.console().readPassword("verficationKey password: ");
        System.out.println(notarization.serializeNotaryKey(notaryKey, password));
    } catch (MissingArgumentException | FileNotFoundException ex) {
        System.out.println(ex.getMessage());
        help.printHelp(CMD_LINE_SYNTAX, options);
        System.exit(1);
    }
}

From source file:com.adobe.aem.demomachine.RegExp.java

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

    String fileName = null;//from   w w w.j a  va  2  s .  c  om
    String regExp = null;
    String position = null;
    String value = "n/a";
    List<String> allMatches = new ArrayList<String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Filename");
    options.addOption("r", true, "RegExp");
    options.addOption("p", true, "Position");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            fileName = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("f")) {
            regExp = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("p")) {
            position = cmd.getOptionValue("p");
        }

        if (fileName == null || regExp == null || position == null) {
            System.out.println("Command line parameters: -f fileName -r regExp -p position");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    String content = readFile(fileName, Charset.defaultCharset());

    if (content != null) {
        Matcher m = Pattern.compile(regExp).matcher(content);
        while (m.find()) {
            String group = m.group();
            int pos = group.indexOf(".zip");
            if (pos > 0) {
                group = group.substring(0, pos);
            }
            logger.debug("RegExp: " + m.group() + " found returning " + group);
            allMatches.add(group);
        }

        if (allMatches.size() > 0) {

            if (position.equals("first")) {
                value = allMatches.get(0);
            }

            if (position.equals("last")) {
                value = allMatches.get(allMatches.size() - 1);
            }
        }
    }

    System.out.println(value);

}

From source file:edu.usf.cutr.obascs.OBASCSMain.java

public static void main(String[] args) {

    String logLevel = null;/*from w  w w .ja  v  a2  s.  c o m*/
    String outputFilePath = null;
    String inputFilePath = null;
    String spreadSheetId = null;
    Logger logger = Logger.getInstance();

    Options options = CommandLineUtil.createCommandLineOptions();
    CommandLineParser parser = new BasicParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        logLevel = CommandLineUtil.getLogLevel(cmd);
        logger.setup(logLevel);
        outputFilePath = CommandLineUtil.getOutputPath(cmd);
        spreadSheetId = CommandLineUtil.getSpreadSheetId(cmd);

        inputFilePath = CommandLineUtil.getInputPath(cmd);
    } catch (ParseException e1) {
        logger.logError(e1);
    } catch (FileNotFoundException e) {
        logger.logError(e);
    }

    Map<String, String> agencyMap = null;
    try {
        agencyMap = FileUtil.readAgencyInformantions(inputFilePath);
    } catch (IOException e1) {
        logger.logError(e1);
    }

    logger.log("Consolidation started...");
    logger.log("Trying as public url");

    ListFeed listFeed = null;
    Boolean authRequired = false;
    try {
        listFeed = SpreadSheetReader.readPublicSpreadSheet(spreadSheetId);
    } catch (IOException e) {
        logger.logError(e);
    } catch (ServiceException e) {
        logger.log("Authentication Required");
        authRequired = true;
    }

    if (listFeed == null && authRequired == true) {
        Scanner scanner = new Scanner(System.in);
        String userName, password;
        logger.log("UserName:");
        userName = scanner.nextLine();
        logger.log("Password:");
        password = scanner.nextLine();
        scanner.close();

        try {
            listFeed = SpreadSheetReader.readPrivateSpreadSheet(userName, password, spreadSheetId);
        } catch (IOException e) {
            logger.logError(e);
        } catch (ServiceException e) {
            logger.logError(e);
        }
    }

    if (listFeed != null) {
        //Creating consolidated stops
        String consolidatedString = FileConsolidator.consolidateFile(listFeed, agencyMap);
        try {
            FileUtil.writeToFile(consolidatedString, outputFilePath);
        } catch (FileNotFoundException e) {
            logger.logError(e);
        }

        //Creating sample stop consolidation script config file
        try {
            String path = ClassLoader.getSystemClassLoader()
                    .getResource(GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE).getPath();
            String configXml = FileUtil.readFile(URLUtil.trimSpace(path));
            configXml = ConfigFileGenerator.generateStopConsolidationScriptConfigFile(configXml, agencyMap);
            path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.CONSOLIDATION_SCRIPT_CONFIG_FILE;
            FileUtil.writeToFile(configXml, path);
        } catch (IOException e) {
            logger.logError(e);
        }

        //Creating sample real-time config file
        try {
            String path = ClassLoader.getSystemClassLoader()
                    .getResource(GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE).getPath();
            String configXml = FileUtil.readFile(URLUtil.trimSpace(path));
            configXml = ConfigFileGenerator.generateSampleRealTimeConfigFile(configXml, agencyMap);
            path = URLUtil.trimPath(outputFilePath) + "/" + GeneralConstants.SAMPLE_REALTIME_CONFIG_FILE;
            FileUtil.writeToFile(configXml, path);
        } catch (IOException e) {
            logger.logError(e);
        }
    } else {
        logger.logError("Cannot write files");
    }

    logger.log("Consolidation finished...");

}

From source file:fr.tpt.atlanalyser.tests.TestForPaperPost2Pre.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException {

    // URL resource = Thread.currentThread().getContextClassLoader()
    // .getResource("OldAGTExp");
    // System.out.println(resource.toString());
    // File f = new File(resource.getPath());
    // System.out.println(f.toString());
    // System.out.println(f.isDirectory());
    // System.exit(0);

    Options options = new Options();
    options.addOption(/*from  w  w  w.  j a  va2s. c  om*/
            OptionBuilder.hasArg().withArgName("N").withDescription("Number of parallel jobs").create("j"));
    options.addOption(OptionBuilder.withDescription("Display help").create("h"));

    CommandLineParser parser = new BasicParser();
    int jobs = 1;
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            new HelpFormatter().printHelp(TestForPaperPost2Pre.class.getSimpleName(), options);
            System.exit(0);
        }

        if (cmd.hasOption("j")) {
            jobs = Integer.parseInt(cmd.getOptionValue("j"));
        }
    } catch (Exception e) {
        System.out.println("Incorrect command line arguments");
        new HelpFormatter().printHelp(TestForPaperPost2Pre.class.getSimpleName(), options);
        System.exit(1);
    }

    new TestForPaperPost2Pre(models().get(0)[0], jobs).testPost2Pre();
}