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:net.lldp.checksims.ChecksimsRunner.java

/**
 * CLI entrypoint of Checksims./*  w w  w .ja  va  2 s. co m*/
 *
 * @param args CLI arguments
 */
public static void main(String[] args) {
    try {
        ChecksimsCommandLine.runCLI(args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    } catch (ChecksimsException e) {
        System.err.println(e.toString());
        if (e.getCause() != null) {
            System.err.println("Caused by: " + e.getCause().toString());
        }
        // Print the stack trace for internal exceptions, they may be serious
        e.printStackTrace();
        System.exit(-1);
    } catch (IOException e) {
        System.err.println("I/O Error!");
        System.err.println(e.getMessage());
        System.exit(-1);
    }

    System.exit(0);
}

From source file:com.cohesionforce.AvroToParquet.java

public static void main(String[] args) {

    String inputFile = null;/* w w  w  . j a va  2 s  .c  om*/
    String outputFile = null;

    HelpFormatter formatter = new HelpFormatter();
    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("i", true, "input avro file");
    options.addOption("o", true, "ouptut Parquet file");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
        inputFile = cmd.getOptionValue("i");
        if (inputFile == null) {
            formatter.printHelp("AvroToParquet", options);
            return;
        }
        outputFile = cmd.getOptionValue("o");
    } catch (ParseException exc) {
        System.err.println("Problem with command line parameters: " + exc.getMessage());
        return;
    }

    File avroFile = new File(inputFile);

    if (!avroFile.exists()) {
        System.err.println("Could not open file: " + inputFile);
        return;
    }
    try {

        DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>();
        DataFileReader<GenericRecord> dataFileReader;
        dataFileReader = new DataFileReader<GenericRecord>(avroFile, datumReader);
        Schema avroSchema = dataFileReader.getSchema();

        // choose compression scheme
        CompressionCodecName compressionCodecName = CompressionCodecName.SNAPPY;

        // set Parquet file block size and page size values
        int blockSize = 256 * 1024 * 1024;
        int pageSize = 64 * 1024;

        String base = FilenameUtils.removeExtension(avroFile.getAbsolutePath()) + ".parquet";
        if (outputFile != null) {
            File file = new File(outputFile);
            base = file.getAbsolutePath();
        }

        Path outputPath = new Path("file:///" + base);

        // the ParquetWriter object that will consume Avro GenericRecords
        ParquetWriter<GenericRecord> parquetWriter;
        parquetWriter = new AvroParquetWriter<GenericRecord>(outputPath, avroSchema, compressionCodecName,
                blockSize, pageSize);
        for (GenericRecord record : dataFileReader) {
            parquetWriter.write(record);
        }
        dataFileReader.close();
        parquetWriter.close();
    } catch (IOException e) {
        System.err.println("Caught exception: " + e.getMessage());
    }
}

From source file:jparser.JParser.java

/**
 * @param args the command line arguments
 *//*  w  w w  . j  a  v a  2  s  .c o  m*/
public static void main(String[] args) {

    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(
            Option.builder().longOpt("to").desc("Indica el tipo de archivo al que debera convertir: JSON / XML")
                    .hasArg().argName("tipo").build());

    options.addOption(Option.builder().longOpt("path")
            .desc("Indica la ruta donde se encuentra el archivo origen").hasArg().argName("origen").build());

    options.addOption(
            Option.builder().longOpt("target").desc("Indica la ruta donde se guardara el archivo resultante")
                    .hasArg().argName("destino").build());

    options.addOption("h", "help", false, "Muestra la guia de como usar la aplicacion");

    try {
        CommandLine command = parser.parse(options, args);
        Path source = null;
        Path target = null;
        FactoryFileParse.TypeParce type = FactoryFileParse.TypeParce.NULL;
        Optional<Customer> customer = Optional.empty();

        if (command.hasOption("h")) {
            HelpFormatter helper = new HelpFormatter();
            helper.printHelp("JParser", options);

            System.exit(0);
        }

        if (command.hasOption("to"))
            type = FactoryFileParse.TypeParce.fromValue(command.getOptionValue("to", ""));

        if (command.hasOption("path"))
            source = Paths.get(command.getOptionValue("path", ""));

        if (command.hasOption("target"))
            target = Paths.get(command.getOptionValue("target", ""));

        switch (type) {
        case JSON:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.XML).read(source);

            break;

        case XML:
            customer = FactoryFileParse.createNewInstance(FactoryFileParse.TypeParce.JSON).read(source);

            break;
        }

        if (customer.isPresent()) {
            Customer c = customer.get();

            boolean success = FactoryFileParse.createNewInstance(type).write(c, target);

            System.out.println(String.format("Operatation was: %s", success ? "success" : "fails"));
        }

    } catch (ParseException ex) {
        Logger.getLogger(JParser.class.getSimpleName()).log(Level.SEVERE, ex.getMessage(), ex);

        System.exit(-1);
    }
}

From source file:com.github.besherman.fingerprint.Main.java

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

    options.addOption(OptionBuilder.withDescription("creates a fingerprint file for the directory").hasArg()
            .withArgName("dir").create('c'));

    options.addOption(OptionBuilder.withDescription("shows a diff between two fingerprint files")
            .withArgName("left-file> <right-file").hasArgs(2).create('d'));

    options.addOption(OptionBuilder.withDescription("shows a diff between a fingerprint and a directory")
            .withArgName("fingerprint> <dir").hasArgs(2).create('t'));

    options.addOption(OptionBuilder.withDescription("shows duplicates in a directory").withArgName("dir")
            .hasArgs(1).create('u'));

    options.addOption(// ww  w.  j  a va 2  s  .  c o  m
            OptionBuilder.withDescription("output to file").withArgName("output-file").hasArg().create('o'));

    PosixParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
        System.out.println("");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingerprint-dir", options, true);
        System.exit(7);
    }

    if (cmd.hasOption('c')) {
        Path root = Paths.get(cmd.getOptionValue('c'));

        if (!Files.isDirectory(root)) {
            System.err.println("root is not a directory");
            System.exit(7);
        }

        OutputStream out = System.out;

        if (cmd.hasOption('o')) {
            Path p = Paths.get(cmd.getOptionValue('o'));
            out = Files.newOutputStream(p);
        }

        Fingerprint fp = new Fingerprint(root, "");
        fp.write(out);

    } else if (cmd.hasOption('d')) {
        String[] ar = cmd.getOptionValues('d');
        Path leftFingerprintFile = Paths.get(ar[0]), rightFingerprintFile = Paths.get(ar[1]);
        if (!Files.isRegularFile(leftFingerprintFile)) {
            System.out.printf("%s is not a file%n", leftFingerprintFile);
            System.exit(7);
        }
        if (!Files.isRegularFile(rightFingerprintFile)) {
            System.out.printf("%s is not a file%n", rightFingerprintFile);
            System.exit(7);
        }

        Fingerprint left, right;
        try (InputStream input = Files.newInputStream(leftFingerprintFile)) {
            left = new Fingerprint(input);
        }

        try (InputStream input = Files.newInputStream(rightFingerprintFile)) {
            right = new Fingerprint(input);
        }

        Diff diff = new Diff(left, right);

        // TODO: if we have redirected output
        diff.print(System.out);
    } else if (cmd.hasOption('t')) {
        throw new RuntimeException("Not yet implemented");
    } else if (cmd.hasOption('u')) {
        Path root = Paths.get(cmd.getOptionValue('u'));
        Fingerprint fp = new Fingerprint(root, "");
        Map<String, FilePrint> map = new HashMap<>();
        fp.stream().forEach(f -> {
            if (map.containsKey(f.getHash())) {
                System.out.println("  " + map.get(f.getHash()).getPath());
                System.out.println("= " + f.getPath());
                System.out.println("");
            } else {
                map.put(f.getHash(), f);
            }
        });
    } else {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fingd", options, true);
    }
}

From source file:cc.wikitools.lucene.SearchWikipedia.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(// w w  w .  j  a  v  a 2 s  .c  o  m
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("query text").create(QUERY_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));

    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));
    options.addOption(new Option(TITLE_OPTION, "search title"));
    options.addOption(new Option(ARTICLE_OPTION, "search article"));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(QUERY_OPTION) || !cmdline.hasOption(INDEX_OPTION)
            || !cmdline.hasOption(QUERY_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchWikipedia.class.getName(), options);
        System.exit(-1);
    }

    File indexLocation = new File(cmdline.getOptionValue(INDEX_OPTION));
    if (!indexLocation.exists()) {
        System.err.println("Error: " + indexLocation + " does not exist!");
        System.exit(-1);
    }

    String queryText = cmdline.getOptionValue(QUERY_OPTION);
    int numResults = cmdline.hasOption(NUM_RESULTS_OPTION)
            ? Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION))
            : DEFAULT_NUM_RESULTS;
    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);
    boolean searchArticle = !cmdline.hasOption(TITLE_OPTION);

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

    WikipediaSearcher searcher = new WikipediaSearcher(indexLocation);
    TopDocs rs = null;
    if (searchArticle) {
        rs = searcher.searchArticle(queryText, numResults);
    } else {
        rs = searcher.searchTitle(queryText, numResults);
    }

    int i = 1;
    for (ScoreDoc scoreDoc : rs.scoreDocs) {
        Document hit = searcher.doc(scoreDoc.doc);

        out.println(String.format("%d. %s (wiki id = %s, lucene id = %d) %f", i,
                hit.getField(IndexField.TITLE.name).stringValue(),
                hit.getField(IndexField.ID.name).stringValue(), scoreDoc.doc, scoreDoc.score));
        if (verbose) {
            out.println("# " + hit.toString().replaceAll("[\\n\\r]+", " "));
        }
        i++;
    }

    searcher.close();
    out.close();
}

From source file:com.twitter.bazel.checkstyle.CppCheckstyle.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new DefaultParser();

    // create the Options
    Options options = new Options();
    options.addOption(Option.builder("f").required(true).hasArg().longOpt("extra_action_file")
            .desc("bazel extra action protobuf file").build());
    options.addOption(Option.builder("c").required(true).hasArg().longOpt("cpplint_file")
            .desc("Executable cpplint file to invoke").build());

    try {//from  w  ww. j  a  v a  2s.c  o  m
        // parse the command line arguments
        CommandLine line = parser.parse(options, args);

        String extraActionFile = line.getOptionValue("f");
        String cpplintFile = line.getOptionValue("c");

        Collection<String> sourceFiles = getSourceFiles(extraActionFile);
        if (sourceFiles.size() == 0) {
            LOG.fine("No cpp files found by checkstyle");
            return;
        }

        LOG.fine(sourceFiles.size() + " cpp files found by checkstyle");

        // Create and run the command
        List<String> commandBuilder = new ArrayList<>();
        commandBuilder.add(cpplintFile);
        commandBuilder.add("--linelength=100");
        // TODO: https://github.com/twitter/heron/issues/466,
        // Remove "runtime/references" when we fix all non-const references in our codebase.
        // TODO: https://github.com/twitter/heron/issues/467,
        // Remove "runtime/threadsafe_fn" when we fix all non-threadsafe libc functions
        commandBuilder.add("--filter=-build/header_guard,-runtime/references,-runtime/threadsafe_fn");
        commandBuilder.addAll(sourceFiles);
        runLinter(commandBuilder);

    } catch (ParseException exp) {
        LOG.severe(String.format("Invalid input to %s: %s", CLASSNAME, exp.getMessage()));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java " + CLASSNAME, options);
    }
}

From source file:eu.optimis.monitoring.amazoncollector.Collector.java

public static void main(String[] args) {

    Collector collector = new Collector();
    Options options = new Options();
    Option id = OptionBuilder.withArgName("id").hasArg().withDescription("use given collector ID")
            .create(ID_OPT);//from w w w.j av a2s.c  om
    Option conf = OptionBuilder.withArgName("configuration path").hasArg().withDescription("Configuration path")
            .create(PATH_OPT);
    options.addOption(id);
    options.addOption(conf);

    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Incorrect parameters: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("collector", options);
        System.exit(2); //Incorrect usage
    }

    if (line.hasOption(ID_OPT)) {
        String cid = line.getOptionValue(ID_OPT);
        Measurement.setDefCollectorId(cid);
        System.out.println("Using Collector ID: " + cid);
    } else {
        System.out.println("Using default Collector ID: " + DEFAULT_ID + " (To use custom ID use -i argument)");
        Measurement.setDefCollectorId(DEFAULT_ID);
    }

    if (line.hasOption(PATH_OPT)) {
        collector.propertiesPath = line.getOptionValue(PATH_OPT);
        System.out.println("Using Properties file: " + collector.propertiesPath);
    } else {
        System.out.println("Using default Configuration file: " + DEFAULT_PROPERTIES_PATH
                + " (To use custom path use -c argument)");
        collector.propertiesPath = DEFAULT_PROPERTIES_PATH;
    }

    collector.getProperties();

    MeasurementsHelper helper = new MeasurementsHelper(collector.accessKey, collector.secretKey);
    List<Measurement> measurements = helper.getMeasurements();

    String xmlData = XMLHelper.createDocument(measurements);
    RESTHelper rest = new RESTHelper(collector.aggregatorURL);
    rest.sendDocument(xmlData);
}

From source file:it.crs4.features.MergeImgSets.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    CommandLine cmd = null;//from   w w  w . ja  v a2s.  c om
    try {
        cmd = parseCmdLine(opts, args);
    } catch (ParseException e) {
        System.err.println("ERROR: " + e.getMessage());
        System.exit(1);
    }
    String[] posArgs = cmd.getArgs();
    if (posArgs.length < 2) {
        HelpFormatter fmt = new HelpFormatter();
        fmt.printHelp("java MergeImgSets IMG_SET_LIST OUT_FN", opts);
        System.exit(2);
    }
    String setsFn = posArgs[0];
    String outFn = posArgs[1];
    int replication = 1;
    if (cmd.hasOption("replication")) {
        replication = Integer.parseInt(cmd.getOptionValue("replication"));
    }

    List<List<String>> filesets = getFilesets(setsFn);
    int sizeZ = filesets.size();
    if (0 == sizeZ) {
        System.out.println("File set list is empty, nothing to do.");
        System.exit(0);
    }
    int sizeC = filesets.get(0).size();
    for (List<String> fs : filesets) {
        if (fs.size() != sizeC) {
            System.err.println("File sets must have equal size");
            System.exit(1);
        }
    }
    write(filesets, outFn, replication);
}

From source file:com.ingby.socbox.bischeck.migration.Properties2ServerProperties.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;//  w  ww .  j ava  2  s .  c  o  m
    // create the Options
    Options options = new Options();
    options.addOption("u", "usage", false, "show usage.");
    options.addOption("v", "verbose", false, "verbose - do not write to files");
    options.addOption("s", "source", true, "directory old properties.xml is located");
    options.addOption("d", "destination", true, "directory where the new xml files while be stored");

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

    } catch (org.apache.commons.cli.ParseException e) {
        System.out.println("Command parse error:" + e.getMessage());
        Util.ShellExit(1);
    }

    if (line.hasOption("usage")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("DB2XMLConvert", options);
        Util.ShellExit(0);
    }

    Properties2ServerProperties converter = new Properties2ServerProperties();

    if (line.hasOption("source")) {
        String sourcedir = line.getOptionValue("source");
        String destdir = ".";
        if (line.hasOption("destination")) {
            destdir = line.getOptionValue("destination");
        }

        converter.createXMLServerProperties(sourcedir, destdir);

    }
}

From source file:com.zimbra.common.util.RandomPassword.java

public static void main(String args[]) {
    CommandLineParser parser = new GnuParser();
    Options options = new Options();
    options.addOption("l", "localpart", false, "generated string does not contain dot(.)");

    CommandLine cl = null;/*from w w  w. j ava  2  s .  c  om*/
    boolean err = false;

    try {
        cl = parser.parse(options, args, true);
    } catch (ParseException pe) {
        System.err.println("error: " + pe.getMessage());
        err = true;
    }

    if (err || cl.hasOption('h')) {
        usage();
    }

    boolean localpart = false;
    int minLength = DEFAULT_MIN_LENGTH;
    int maxLength = DEFAULT_MAX_LENGTH;

    if (cl.hasOption('l'))
        localpart = true;

    args = cl.getArgs();

    if (args.length != 0) {
        if (args.length != 2) {
            usage();
        }
        try {
            minLength = Integer.valueOf(args[0]).intValue();
            maxLength = Integer.valueOf(args[1]).intValue();
        } catch (Exception e) {
            System.err.println(e);
            e.printStackTrace();
        }
    }

    System.out.println(generate(minLength, maxLength, localpart));
}