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

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

Introduction

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

Prototype

HelpFormatter

Source Link

Usage

From source file:com.benasmussen.tools.testeditor.ExtractorCLI.java

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

    // cli options
    Options options = new Options();
    options.addOption(CMD_OPT_INPUT, true, "Input file");
    // options.addOption(CMD_OPT_OUTPUT, true, "Output file");

    try {/*from  www .j a  v  a 2  s.co m*/

        // evaluate command line options
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(CMD_OPT_INPUT)) {
            // option value
            String optionValue = cmd.getOptionValue(CMD_OPT_INPUT);

            // input file
            File inputFile = new File(optionValue);

            // id extractor
            IdExtractor idExtractor = new IdExtractor(inputFile);
            Vector<Vector> data = idExtractor.parse();

            // // TODO implement output folder
            // if (cmd.hasOption(CMD_OPT_OUTPUT))
            // {
            // // file output
            // throw new Exception("Not implemented");
            // }
            // else
            // {
            // console output
            System.out.println("Id;Value");
            for (Vector vector : data) {
                StringBuilder sb = new StringBuilder();
                if (vector.size() >= 1) {
                    sb.append(vector.get(0));
                }
                sb.append(";");
                if (vector.size() >= 2) {
                    sb.append(vector.get(1));
                }
                System.out.println(sb.toString());
            }
            // }
        } else {
            throw new IllegalArgumentException();
        }

    } catch (ParseException e) {
        formatter.printHelp("ExtractorCLI", options);
    } catch (IllegalArgumentException e) {
        formatter.printHelp("ExtractorCLI", options);
    }
}

From source file:com.tomdoel.mpg2dcm.Xml2Dicom.java

public static void main(String[] args) {
    try {/* ww  w  . j  a  v  a  2s.co  m*/
        final Options helpOptions = new Options();
        helpOptions.addOption("h", false, "Print help for this application");

        final DefaultParser parser = new DefaultParser();
        final CommandLine commandLine = parser.parse(helpOptions, args);

        if (commandLine.hasOption('h')) {
            final String helpHeader = "Converts an endoscopic xml and video files to Dicom\n\n";
            String helpFooter = "\nPlease report issues at github.com/tomdoel/mpg2dcm";

            final HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Xml2Dcm xml-file dicom-output-path", helpHeader, helpOptions, helpFooter,
                    true);

        } else {
            final List<String> remainingArgs = commandLine.getArgList();
            if (remainingArgs.size() < 2) {
                throw new org.apache.commons.cli.ParseException("ERROR : Not enough arguments specified.");
            }

            final String xmlInputFileName = remainingArgs.get(0);
            final String dicomOutputPath = remainingArgs.get(1);
            EndoscopicXmlToDicomConverter.convert(new File(xmlInputFileName), dicomOutputPath);
        }
    } catch (org.apache.commons.cli.ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:jlite.cli.ProxyDestroy.java

public static void main(String[] args) {
    System.out.println(); // extra line
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();// w  w  w  .  ja  v  a  2 s  . co  m
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false);
            System.out.println(); // extra line
            System.exit(0);
        }

        if (line.hasOption("xml")) {
            System.out.println("<output>");
        }

        run(line);
    } catch (ParseException e) {
        System.err.println(e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if (line.hasOption("xml")) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        System.out.println("</output>");
    }
    System.out.println(); // extra line
}

From source file:io.github.the28awg.okato.App.java

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

    options.addOption(Option.builder().longOpt("token").hasArg().required().argName("token")
            .desc(" ? ?  ??").build());
    options.addOption(Option.builder("t").longOpt("type").hasArg().required().argName("type")
            .desc("  [city, street, building]").build());
    options.addOption(Option.builder("q").longOpt("query").hasArg().argName("query")
            .desc(" ? ?  ").build());
    options.addOption(Option.builder("c").longOpt("city_id").hasArg().argName("city_id")
            .desc("  (? )").build());
    options.addOption(Option.builder("s").longOpt("street_id").hasArg().argName("street_id")
            .desc(" ").build());

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;//from w  w w. j a  v  a2s .c  om

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("okato", options);
        System.exit(1);
        return;
    }

    AddressFactory.token(cmd.getOptionValue("token"));

    String arg_type = cmd.getOptionValue("type");
    String arg_city_id = cmd.getOptionValue("city_id", "");
    String arg_street_id = cmd.getOptionValue("street_id", "");
    String arg_query = cmd.getOptionValue("query", "");
    if (arg_type.equalsIgnoreCase("city")) {
        try {
            log(SimpleOkato.toSimpleResponse(
                    AddressFactory.service().city(AddressFactory.token(), arg_query).execute().body()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (arg_type.equalsIgnoreCase("street")) {
        try {
            log(SimpleOkato.toSimpleResponse(AddressFactory.service()
                    .street(AddressFactory.token(), arg_city_id, arg_query).execute().body()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else if (arg_type.equalsIgnoreCase("building")) {
        try {
            log(SimpleOkato.toSimpleResponse(AddressFactory.service()
                    .building(AddressFactory.token(), arg_city_id, arg_street_id, arg_query).execute().body()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:jlite.cli.ProxyDelegate.java

public static void main(String[] args) {
    System.out.println(); // extra line
    CommandLineParser parser = new GnuParser();
    Options options = setupOptions();/*ww  w . j  a  v a2  s.c o  m*/
    HelpFormatter helpFormatter = new HelpFormatter();
    helpFormatter.setSyntaxPrefix("Usage: ");
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
        if (line.hasOption("help")) {
            helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false);
            System.out.println(); // extra line
            System.exit(0);
        }
        if (line.hasOption("xml")) {
            System.out.println("<output>");
        }
        run(line);
    } catch (ParseException e) {
        System.err.println(e.getMessage() + "\n");
        helpFormatter.printHelp(100, COMMAND, "\noptions:", options, "\n" + CLI.FOOTER, false);
        System.out.println(); // extra line
        System.exit(-1);
    } catch (Exception e) {
        if ((line != null) && (line.hasOption("xml"))) {
            System.out.println("<error>" + e.getMessage() + "</error>");
        } else {
            System.err.println(e.getMessage());
        }
    } finally {
        if (line.hasOption("xml")) {
            System.out.println("</output>");
        }
    }
    System.out.println(); // extra line
}

From source file:com.github.braully.graph.UtilResultCompare.java

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

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(false);/*from w  w w. ja  va  2 s.c  o  m*/
    options.addOption(input);

    Option output = new Option("o", "output", true, "output file");
    output.setRequired(false);
    options.addOption(output);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("UtilResult", options);

        System.exit(1);
        return;
    }

    String inputFilePath = cmd.getOptionValue("input");
    if (inputFilePath == null) {
        inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-quartic-ht.txt";

        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-mft-parcial-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-highlyirregular-ht.txt";
        //            inputFilePath = "/home/strike/Documentos/grafos-processados/mtf/resultado-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-hypo-parcial-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-eul-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-almhypo-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-Almost_hypohamiltonian_graphs_cubic-parcial-ht.txt";
    }
    if (inputFilePath != null) {
        if (inputFilePath.toLowerCase().endsWith(".txt")) {
            processFileTxt(inputFilePath);
        } else if (inputFilePath.toLowerCase().endsWith(".json")) {
            processFileJson(inputFilePath);
        }
    }
}

From source file:cloudlens.cli.Main.java

public static void main(String[] args) throws Exception {
    final CommandLineParser optionParser = new DefaultParser();
    final HelpFormatter formatter = new HelpFormatter();

    final Option lens = Option.builder("r").longOpt("run").hasArg().argName("lens file").desc("Lens file.")
            .required(true).build();//from  ww  w.j ava2  s .c o  m
    final Option log = Option.builder("l").longOpt("log").hasArg().argName("log file").desc("Log file.")
            .build();
    final Option jsonpath = Option.builder().longOpt("jsonpath").hasArg().argName("path")
            .desc("Path to logs in a json object.").build();
    final Option js = Option.builder().longOpt("js").hasArg().argName("js file").desc("Load JS file.").build();
    final Option format = Option.builder("f").longOpt("format").hasArg()
            .desc("Choose log format (text or json).").build();
    final Option streaming = Option.builder().longOpt("stream").desc("Streaming mode.").build();
    final Option history = Option.builder().longOpt("history").desc("Store history.").build();

    final Options options = new Options();
    options.addOption(log);
    options.addOption(lens);
    options.addOption(format);
    options.addOption(jsonpath);
    options.addOption(js);
    options.addOption(streaming);
    options.addOption(history);

    try {
        final CommandLine cmd = optionParser.parse(options, args);

        final String jsonPath = cmd.getOptionValue("jsonpath");
        final String[] jsFiles = cmd.getOptionValues("js");
        final String[] lensFiles = cmd.getOptionValues("run");
        final String[] logFiles = cmd.getOptionValues("log");
        final String source = cmd.getOptionValue("format");

        final boolean stream = cmd.hasOption("stream") || !cmd.hasOption("log");
        final boolean withHistory = cmd.hasOption("history") || !stream;

        final CL cl = new CL(System.out, System.err, stream, withHistory);

        try {
            final InputStream input = (cmd.hasOption("log")) ? FileReader.readFiles(logFiles) : System.in;

            if (source == null) {
                cl.source(input);
            } else {
                switch (source) {
                case "text":
                    cl.source(input);
                    break;
                case "json":
                    cl.json(input, jsonPath);
                    break;
                default:
                    input.close();
                    throw new CLException("Unsupported format: " + source);
                }
            }

            for (final String jsFile : FileReader.fullPaths(jsFiles)) {
                cl.engine.eval("CL.loadjs('file://" + jsFile + "')");
            }

            final List<ASTElement> top = ASTBuilder.parseFiles(lensFiles);
            cl.launch(top);

        } catch (final CLException | ASTException e) {
            cl.errWriter.println(e.getMessage());
        } finally {
            cl.outWriter.flush();
            cl.errWriter.flush();
        }
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        formatter.printHelp("cloudlens", options);
    }
}

From source file:com.github.braully.graph.UtilResult.java

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

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(false);/*  w w  w  .  j  ava 2 s  . c o m*/
    options.addOption(input);

    Option verb = new Option("v", "verbose", false, "verbose process");
    input.setRequired(false);
    options.addOption(verb);

    Option output = new Option("o", "output", true, "output file");
    output.setRequired(false);
    options.addOption(output);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp("UtilResult", options);

        System.exit(1);
        return;
    }

    String inputFilePath = cmd.getOptionValue("input");
    if (inputFilePath == null) {
        inputFilePath = "/home/strike/grafos-para-processar/mft2/resultado.txt";
    }
    if (inputFilePath != null) {
        if (inputFilePath.toLowerCase().endsWith(".txt")) {
            processFileTxt(inputFilePath);
        } else if (inputFilePath.toLowerCase().endsWith(".json")) {
            processFileJson(inputFilePath);
        }
    }
}

From source file:com.cohesionforce.AvroToParquet.java

public static void main(String[] args) {

    String inputFile = null;/* ww  w  .j a v a 2s. c o  m*/
    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:be.i8c.sag.wm.is.SwaggerImporter.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    Options options = getOptions();/*w  w  w. j av a2 s  .com*/
    CommandLine cmd = parser.parse(options, args);
    HelpFormatter formatter = new HelpFormatter();
    if (cmd.hasOption("h")) {
        formatter.printHelp("", options);
    } else if (cmd.hasOption("is") && cmd.hasOption("u") && cmd.hasOption("p") && cmd.hasOption("swf")
            && cmd.hasOption("pkg")) {
        SwaggerParser swaggerParser = new SwaggerParser();
        Swagger swaggerModel = swaggerParser.read(cmd.getOptionValue("swf"));
        String[] conn = cmd.getOptionValue("is").split(":");
        String host = conn[0];
        String port = "80";
        if (conn.length > 1) {
            port = conn[1];
        }
        ServerConnection sc = new ServerConnection(host, port, cmd.getOptionValue("u"), cmd.getOptionValue("p"),
                false);
        try {
            logger.info("Connecting to server " + host + "(" + port + ")");
            sc.connect();
            logger.info("Connected to server");

            RestImplementation ri = new RestImplementation(sc, swaggerModel, cmd.getOptionValue("pkg"),
                    cmd.getOptionValue("acl"));

            ri.generateImplementation();

        } catch (Throwable e) {
            logger.error("Error: " + e.getMessage());
            //logger.error(e.getStackTrace());
            e.printStackTrace();
        } finally {
            logger.info("Disconnecting from server");
            sc.disconnect();
            ServerConnectionManager.getInstance().closeServerConnectionManager();
            logger.info("Disconnected from server");
            logger.info("BYE");
            System.exit(0);
        }
    }

}