Example usage for org.apache.commons.cli ParseException getMessage

List of usage examples for org.apache.commons.cli ParseException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.google.flightmap.parsing.faa.afd.AfdCommParser.java

public static void main(String args[]) {
    CommandLine line = null;//from  w w w . j  ava 2 s  . c o m
    try {
        final CommandLineParser parser = new PosixParser();
        line = parser.parse(OPTIONS, args);
    } catch (ParseException pEx) {
        System.err.println(pEx.getMessage());
        printHelp(line);
        System.exit(1);
    }

    if (line.hasOption(HELP_OPTION)) {
        printHelp(line);
        System.exit(0);
    }

    final String afdFile = line.getOptionValue(AFD_OPTION);
    final String iataToIcaoFile = line.getOptionValue(IATA_TO_ICAO_OPTION);
    final String dbFile = line.getOptionValue(AVIATION_DB_OPTION);

    (new AfdCommParser(afdFile, iataToIcaoFile, dbFile)).execute();
}

From source file:com.act.biointerpretation.analytics.ReactionDeletion.java

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

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

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

    if (!cl.hasOption(OPTION_OUTPUT_PATH)) {
        LOGGER.error("Input -o prefix");
        return;
    }

    NoSQLAPI srcApi = new NoSQLAPI(cl.getOptionValue(OPTION_SOURCE_DB), cl.getOptionValue(OPTION_SOURCE_DB));
    NoSQLAPI sinkApi = new NoSQLAPI(cl.getOptionValue(OPTION_SINK_DB), cl.getOptionValue(OPTION_SINK_DB));

    searchForDroppedReactions(srcApi, sinkApi, new File(cl.getOptionValue(OPTION_OUTPUT_PATH)));
}

From source file:com.ctriposs.rest4j.tools.data.FilterSchemaGenerator.java

public static void main(String[] args) {
    final CommandLineParser parser = new GnuParser();
    CommandLine cl = null;//from w  w w  .j a  v a 2  s  .c  o m
    try {
        cl = parser.parse(_options, args);
    } catch (ParseException e) {
        _log.error("Invalid arguments: " + e.getMessage());
        reportInvalidArguments();
    }

    final String[] directoryArgs = cl.getArgs();
    if (directoryArgs.length != 2) {
        reportInvalidArguments();
    }

    final File sourceDirectory = new File(directoryArgs[0]);
    if (!sourceDirectory.exists()) {
        _log.error(sourceDirectory.getPath() + " does not exist");
        System.exit(1);
    }
    if (!sourceDirectory.isDirectory()) {
        _log.error(sourceDirectory.getPath() + " is not a directory");
        System.exit(1);
    }
    final URI sourceDirectoryURI = sourceDirectory.toURI();

    final File outputDirectory = new File(directoryArgs[1]);
    if (outputDirectory.exists() && !sourceDirectory.isDirectory()) {
        _log.error(outputDirectory.getPath() + " is not a directory");
        System.exit(1);
    }

    final boolean isAvroMode = cl.hasOption('a');
    final String predicateExpression = cl.getOptionValue('e');
    final Predicate predicate = PredicateExpressionParser.parse(predicateExpression);

    final Collection<File> sourceFiles = FileUtil.listFiles(sourceDirectory, null);
    int exitCode = 0;
    for (File sourceFile : sourceFiles) {
        try {
            final ValidationOptions val = new ValidationOptions();
            val.setAvroUnionMode(isAvroMode);

            final SchemaParser schemaParser = new SchemaParser();
            schemaParser.setValidationOptions(val);

            schemaParser.parse(new FileInputStream(sourceFile));
            if (schemaParser.hasError()) {
                _log.error("Error parsing " + sourceFile.getPath() + ": "
                        + schemaParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final DataSchema originalSchema = schemaParser.topLevelDataSchemas().get(0);
            if (!(originalSchema instanceof NamedDataSchema)) {
                _log.error(sourceFile.getPath() + " does not contain valid NamedDataSchema");
                exitCode = 1;
                continue;
            }

            final SchemaParser filterParser = new SchemaParser();
            filterParser.setValidationOptions(val);

            final NamedDataSchema filteredSchema = Filters.removeByPredicate((NamedDataSchema) originalSchema,
                    predicate, filterParser);
            if (filterParser.hasError()) {
                _log.error("Error applying predicate: " + filterParser.errorMessageBuilder().toString());
                exitCode = 1;
                continue;
            }

            final String relativePath = sourceDirectoryURI.relativize(sourceFile.toURI()).getPath();
            final String outputFilePath = outputDirectory.getPath() + File.separator + relativePath;
            final File outputFile = new File(outputFilePath);
            final File outputFileParent = outputFile.getParentFile();
            outputFileParent.mkdirs();
            if (!outputFileParent.exists()) {
                _log.error("Unable to write filtered schema to " + outputFileParent.getPath());
                exitCode = 1;
                continue;
            }

            FileOutputStream fout = new FileOutputStream(outputFile);
            fout.write(filteredSchema.toString().getBytes(RestConstants.DEFAULT_CHARSET));
            fout.close();
        } catch (IOException e) {
            _log.error(e.getMessage());
            exitCode = 1;
        }
    }

    System.exit(exitCode);
}

From source file:com.twentyn.patentScorer.PatentScorer.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();//  w  w  w.j  a  v  a  2s.  c  o m
    Options opts = new Options();
    opts.addOption(Option.builder("i").longOpt("input").hasArg().required()
            .desc("Input file or directory to score").build());
    opts.addOption(Option.builder("o").longOpt("output").hasArg().required()
            .desc("Output file to which to write score JSON").build());
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
    opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }

    if (cmdLine.hasOption("verbose")) {
        // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2
        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration ctxConfig = ctx.getConfiguration();
        LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
        logConfig.setLevel(Level.DEBUG);

        ctx.updateLoggers();
        LOGGER.debug("Verbose logging enabled");
    }

    String inputFileOrDir = cmdLine.getOptionValue("input");
    File splitFileOrDir = new File(inputFileOrDir);
    if (!(splitFileOrDir.exists())) {
        LOGGER.error("Unable to find directory at " + inputFileOrDir);
        System.exit(1);
    }

    try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"))) {
        PatentScorer scorer = new PatentScorer(PatentModel.getModel(), writer);
        PatentCorpusReader corpusReader = new PatentCorpusReader(scorer, splitFileOrDir);
        corpusReader.readPatentCorpus();
    }
}

From source file:UploadUrlGenerator.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();

    opts.addOption(Option.builder().longOpt(ENDPOINT_OPTION).required().hasArg().argName("url")
            .desc("Sets the ECS S3 endpoint to use, e.g. https://ecs.company.com:9021").build());
    opts.addOption(Option.builder().longOpt(ACCESS_KEY_OPTION).required().hasArg().argName("access-key")
            .desc("Sets the Access Key (user) to sign the request").build());
    opts.addOption(Option.builder().longOpt(SECRET_KEY_OPTION).required().hasArg().argName("secret")
            .desc("Sets the secret key to sign the request").build());
    opts.addOption(Option.builder().longOpt(BUCKET_OPTION).required().hasArg().argName("bucket-name")
            .desc("The bucket containing the object").build());
    opts.addOption(Option.builder().longOpt(KEY_OPTION).required().hasArg().argName("object-key")
            .desc("The object name (key) to access with the URL").build());
    opts.addOption(Option.builder().longOpt(EXPIRES_OPTION).hasArg().argName("minutes")
            .desc("Minutes from local time to expire the request.  1 day = 1440, 1 week=10080, "
                    + "1 month (30 days)=43200, 1 year=525600.  Defaults to 1 hour (60).")
            .build());//from  www .  j a v  a 2 s . com
    opts.addOption(Option.builder().longOpt(VERB_OPTION).hasArg().argName("http-verb").type(HttpMethod.class)
            .desc("The HTTP verb that will be used with the URL (PUT, GET, etc).  Defaults to GET.").build());
    opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPTION).hasArg().argName("mimetype")
            .desc("Sets the Content-Type header (e.g. image/jpeg) that will be used with the request.  "
                    + "Must match exactly.  Defaults to application/octet-stream for PUT/POST and "
                    + "null for all others")
            .build());

    DefaultParser dp = new DefaultParser();

    CommandLine cmd = null;
    try {
        cmd = dp.parse(opts, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar UploadUrlGenerator-xxx.jar", opts, true);
        System.exit(255);
    }

    URI endpoint = URI.create(cmd.getOptionValue(ENDPOINT_OPTION));
    String accessKey = cmd.getOptionValue(ACCESS_KEY_OPTION);
    String secretKey = cmd.getOptionValue(SECRET_KEY_OPTION);
    String bucket = cmd.getOptionValue(BUCKET_OPTION);
    String key = cmd.getOptionValue(KEY_OPTION);
    HttpMethod method = HttpMethod.GET;
    if (cmd.hasOption(VERB_OPTION)) {
        method = HttpMethod.valueOf(cmd.getOptionValue(VERB_OPTION).toUpperCase());
    }
    int expiresMinutes = 60;
    if (cmd.hasOption(EXPIRES_OPTION)) {
        expiresMinutes = Integer.parseInt(cmd.getOptionValue(EXPIRES_OPTION));
    }
    String contentType = null;
    if (method == HttpMethod.PUT || method == HttpMethod.POST) {
        contentType = "application/octet-stream";
    }

    if (cmd.hasOption(CONTENT_TYPE_OPTION)) {
        contentType = cmd.getOptionValue(CONTENT_TYPE_OPTION);
    }

    BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    ClientConfiguration cc = new ClientConfiguration();
    // Force use of v2 Signer.  ECS does not support v4 signatures yet.
    cc.setSignerOverride("S3SignerType");
    AmazonS3Client s3 = new AmazonS3Client(credentials, cc);
    s3.setEndpoint(endpoint.toString());
    S3ClientOptions s3c = new S3ClientOptions();
    s3c.setPathStyleAccess(true);
    s3.setS3ClientOptions(s3c);

    // Sign the URL
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, expiresMinutes);
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key).withExpiration(c.getTime())
            .withMethod(method);
    if (contentType != null) {
        req = req.withContentType(contentType);
    }
    URL u = s3.generatePresignedUrl(req);
    System.out.printf("URL: %s\n", u.toURI().toASCIIString());
    System.out.printf("HTTP Verb: %s\n", method);
    System.out.printf("Expires: %s\n", c.getTime());
    System.out.println("To Upload with curl:");

    StringBuilder sb = new StringBuilder();
    sb.append("curl ");

    if (method != HttpMethod.GET) {
        sb.append("-X ");
        sb.append(method.toString());
        sb.append(" ");
    }

    if (contentType != null) {
        sb.append("-H \"Content-Type: ");
        sb.append(contentType);
        sb.append("\" ");
    }

    if (method == HttpMethod.POST || method == HttpMethod.PUT) {
        sb.append("-T <filename> ");
    }

    sb.append("\"");
    sb.append(u.toURI().toASCIIString());
    sb.append("\"");

    System.out.println(sb.toString());

    System.exit(0);
}

From source file:com.evolveum.midpoint.tools.ninja.Main.java

public static void main(String[] args) {
    Options options = new Options();
    options.addOption(help);//from ww w. j  a va2s. c  o  m
    options.addOption(validate);
    options.addOption(create);
    options.addOption(importOp);
    options.addOption(schemaOp);
    options.addOption(exportOp);
    options.addOption(driver);
    options.addOption(url);
    options.addOption(username);
    options.addOption(password);
    options.addOption(Password);
    options.addOption(keyStore);
    options.addOption(trans);
    options.addOption(outputFormat);
    options.addOption(outputDirectory);
    options.addOption(input);

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);
        if (line.getOptions().length == 0 || line.hasOption(help.getOpt())) {
            printHelp(options);
            return;
        }

        //repository validation, if proper option is present
        boolean valid = validate(line, options);
        //import DDL, if proper option is present
        if (line.hasOption(create.getOpt())) {
            ImportDDL ddl = new ImportDDL(createDDLConfig(line));
            if (!ddl.execute()) {
                System.out.println("DLL import was unsuccessful, skipping other steps.");
                return;
            }

            //repository validation after DDL import, if proper option is present
            valid = validate(line, options);
        }

        //import objects, only if repository validation didn't fail (in case it was tested)
        if (valid && line.hasOption(importOp.getOpt())) {
            String path = line.getOptionValue(importOp.getOpt());
            boolean validateSchema = line.hasOption(schemaOp.getOpt());
            ImportObjects objects = new ImportObjects(path, validateSchema);
            objects.execute();
        }

        if (valid && line.hasOption(exportOp.getOpt())) {
            String path = line.getOptionValue(exportOp.getOpt());
            ExportObjects objects = new ExportObjects(path);
            objects.execute();
        }

        if (line.hasOption(keyStore.getOpt())) {
            KeyStoreDumper keyStoreDumper = new KeyStoreDumper();
            keyStoreDumper.execute();
        }

        if (line.hasOption(trans.getOpt())) {
            if (!checkCommand(line)) {
                return;
            }
            FileTransformer transformer = new FileTransformer();
            configureTransformer(transformer, line);
            transformer.execute();
        }
    } catch (ParseException ex) {
        System.out.println("Error: " + ex.getMessage());
        printHelp(options);
    } catch (Exception ex) {
        System.out.println("Exception occurred, reason: " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:com.dattack.dbping.cli.PingCli.java

/**
 * The <code>main</code> method.
 *
 * @param args/*  ww w  .  j  a v a2s  .c  o  m*/
 *            the program arguments
 */
public static void main(final String[] args) {

    final Options options = createOptions();

    try {
        final CommandLineParser parser = new DefaultParser();
        final CommandLine cmd = parser.parse(options, args);
        final String[] filenames = cmd.getOptionValues(FILE_OPTION);
        final String[] taskNames = cmd.getOptionValues(TASK_NAME_OPTION);

        HashSet<String> hs = null;
        if (taskNames != null) {
            hs = new HashSet<>(Arrays.asList(taskNames));
        }

        final PingEngine ping = new PingEngine();
        ping.execute(filenames, hs);

    } catch (@SuppressWarnings("unused") final ParseException e) {
        showUsage(options);
    } catch (final ConfigurationException | DattackParserException e) {
        System.err.println(e.getMessage());
    }
}

From source file:com.github.trohovsky.just.Main.java

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

    // parsing of command line
    final CommandLineParser parser = new GnuParser();

    final Options options = new Options();
    options.addOption("ai", true, "prefixes of classes from artifacts that will be included");
    options.addOption("ae", true, "prefixes of classes from artifacts that will be excluded");
    options.addOption("di", true, "prefixes of classes from dependencies that will be included");
    options.addOption("de", true, "prefixes of classes from dependencies that will be excluded");
    options.addOption("f", "flatten", false, "flatten report, display only used classes");
    options.addOption("p", "packages", false, "display package names instead of class names");
    options.addOption("u", "unused", false, "display unused classes from dependencies");
    options.addOption("h", "help", false, "print this help");

    CommandLine cmdLine = null;//from   w w w  .j a v  a2s  . c o  m
    try {
        cmdLine = parser.parse(options, args);
        if (cmdLine.hasOption('h')) {
            final HelpFormatter formatter = new HelpFormatter();
            formatter.setOptionComparator(null);
            formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER);
            return;
        }
        if (cmdLine.getArgs().length == 0) {
            throw new ParseException("Missing ARTIFACT and/or DEPENDENCY.");
        } else if (cmdLine.getArgs().length > 2) {
            throw new ParseException(
                    "More that two arquments found, multiple ARTIFACTs DEPENDENCies should be separated by ','"
                            + " without whitespaces.");
        }

    } catch (ParseException e) {
        System.err.println("Error parsing command line: " + e.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(HELP_CMDLINE, HELP_HEADER, options, HELP_FOOTER);
        return;
    }

    // obtaining of values
    final String[] artifactPaths = cmdLine.getArgs()[0].split(",");
    final String[] dependencyPaths = cmdLine.getArgs().length == 2 ? cmdLine.getArgs()[1].split(",") : null;
    final String[] artifactIncludes = splitValues(cmdLine.getOptionValue("ai"));
    final String[] artifactExcludes = splitValues(cmdLine.getOptionValue("ae"));
    final String[] dependencyIncludes = splitValues(cmdLine.getOptionValue("di"));
    final String[] dependencyExcludes = splitValues(cmdLine.getOptionValue("de"));

    // validation of values
    if (dependencyPaths == null) {
        if (dependencyIncludes != null) {
            System.err.println("At least one dependency has to be specified to use option -di");
            return;
        }
        if (dependencyExcludes != null) {
            System.err.println("At least one dependency has to be specified to use option -de");
            return;
        }
        if (cmdLine.hasOption('u')) {
            System.err.println("At least one dependency has to be specified to use option -u");
            return;
        }
    }

    // execution
    Set<String> externalClasses = null;
    if (dependencyPaths != null) {
        externalClasses = Reader.from(dependencyPaths).includes(dependencyIncludes).excludes(dependencyExcludes)
                .listClasses();
    }

    if (cmdLine.hasOption('f') || cmdLine.hasOption('u')) {
        Set<String> dependencies = Reader.from(artifactPaths).includes(artifactIncludes)
                .excludes(artifactExcludes).readDependencies();
        if (externalClasses != null) {
            dependencies = DependencyUtils.intersection(dependencies, externalClasses);
            if (cmdLine.hasOption('u')) {
                dependencies = DependencyUtils.subtract(externalClasses, dependencies);
            }
        }
        if (cmdLine.hasOption('p')) {
            dependencies = DependencyUtils.toPackageNames(dependencies);
        }
        Reporter.report(dependencies);
    } else {
        Map<String, Set<String>> classesWithDependencies = Reader.from(artifactPaths).includes(artifactIncludes)
                .excludes(artifactExcludes).readClassesWithDependencies();
        if (externalClasses != null) {
            classesWithDependencies = DependencyUtils.intersection(classesWithDependencies, externalClasses);
        }
        if (cmdLine.hasOption('p')) {
            classesWithDependencies = DependencyUtils.toPackageNames(classesWithDependencies);
        }
        Reporter.report(classesWithDependencies);
    }
}

From source file:com.twentyn.patentTextProcessor.WordCountProcessor.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();//from  w w w  . j a  v a2  s .com
    Options opts = new Options();
    opts.addOption(Option.builder("i").longOpt("input").hasArg().required()
            .desc("Input file or directory to score").build());
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
    opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("WordCountProcessor", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }

    String inputFileOrDir = cmdLine.getOptionValue("input");
    File splitFileOrDir = new File(inputFileOrDir);
    if (!(splitFileOrDir.exists())) {
        LOGGER.error("Unable to find directory at " + inputFileOrDir);
        System.exit(1);
    }

    WordCountProcessor wcp = new WordCountProcessor();
    PatentCorpusReader corpusReader = new PatentCorpusReader(wcp, splitFileOrDir);
    corpusReader.readPatentCorpus();
}

From source file:is.merkor.cli.Main.java

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

    List<String> results = new ArrayList<String>();

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    CommandLineParser parser = new GnuParser();
    try {// www.  j  ava2s  .  c o  m

        MerkorCommandLineOptions.createOptions();
        results = processCommandLine(parser.parse(MerkorCommandLineOptions.options, args));
        //          out.print("\n");
        //          for (String str : results) {
        //             if(!str.equals("no message"))
        //                out.println(str);
        //         }
        //          out.print("\n");
        //         if (results.isEmpty()) {   
        //            out.println("nothing found for parameters: ");
        //            for (int i = 0; i < args.length; i++)
        //               out.println("\t" + args[i]);
        //            out.println("for help type: -help or see README.markdown");
        //            out.print("\n");
        //         }
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
    }
}