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:graphgen.GraphGen.java

/**
 * @param args the command line arguments
 *///from  w w w . j a v a 2s.  c  o m
public static void main(String[] args) {
    Options options = new Options();
    HelpFormatter formatter = new HelpFormatter();

    options.addOption(OPTION_EDGES, true, OPTION_EDGES_MSG);
    options.addOption(OPTION_NODES, true, OPTION_NODES_MSG);
    options.addOption(OPTION_OUTPUT, true, OPTION_OUTPUT_MSG);

    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        int edgeCount = Integer.valueOf(cmd.getOptionValue(OPTION_EDGES));
        int nodeCount = Integer.valueOf(cmd.getOptionValue(OPTION_NODES));
        String outputFile = cmd.getOptionValue(OPTION_OUTPUT);

        if ((nodeCount < edgeCount) || (outputFile != null)) {
            String graph = generateGraph(nodeCount, edgeCount);
            saveGraph(graph, outputFile);
        } else {
            formatter.printHelp(HELP_NAME, options);
        }

    } catch (NumberFormatException | ParseException e) {
        formatter.printHelp(HELP_NAME, options);
    } catch (IllegalArgumentException | FileNotFoundException e) {
        System.err.println(e.getMessage());
    }
}

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

public static void main(String[] args) {
    try {//from   w w  w  .ja  v  a 2 s.  c o  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 mpeg2 video file to Dicom\n\n";
            String helpFooter = "\nPlease report issues at github.com/tomdoel/mpg2dcm";

            final HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Mpg2Dcm mpegfile dicomfile", 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 mpegFileName = remainingArgs.get(0);
            final String dicomFileName = remainingArgs.get(1);
            final File mpegFile = new File(mpegFileName);
            final File dicomOutputFile = new File(dicomFileName);
            MpegFileConverter.convert(mpegFile, dicomOutputFile);
        }
    } catch (org.apache.commons.cli.ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.alexoree.jenkins.Main.java

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

    options.addOption("t", false, "throttle the downloads, waits 5 seconds in between each d/l");

    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("jenkins-sync", options);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    boolean throttle = cmd.hasOption("t");

    String plugins = "https://updates.jenkins-ci.org/latest/";
    List<String> ps = new ArrayList<String>();
    Document doc = Jsoup.connect(plugins).get();
    for (Element file : doc.select("td a")) {
        //System.out.println(file.attr("href"));
        if (file.attr("href").endsWith(".hpi") || file.attr("href").endsWith(".war")) {
            ps.add(file.attr("href"));
        }/*from w w  w  .j a v a 2s  .  c  o m*/
    }

    File root = new File(".");
    //https://updates.jenkins-ci.org/latest/AdaptivePlugin.hpi
    new File("./latest").mkdirs();

    //output zip file
    String zipFile = "jenkinsSync.zip";
    // create byte buffer
    byte[] buffer = new byte[1024];
    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    //download the plugins
    for (int i = 0; i < ps.size(); i++) {
        System.out.println("[" + i + "/" + ps.size() + "] downloading " + plugins + ps.get(i));
        String outputFile = download(root.getAbsolutePath() + "/latest/" + ps.get(i), plugins + ps.get(i));

        FileInputStream fis = new FileInputStream(outputFile);
        // begin writing a new ZIP entry, positions the stream to the start of the entry data
        zos.putNextEntry(new ZipEntry(outputFile.replace(root.getAbsolutePath(), "")
                .replace("updates.jenkins-ci.org/", "").replace("https:/", "")));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
        if (throttle)
            Thread.sleep(WAIT);
        new File(root.getAbsolutePath() + "/latest/" + ps.get(i)).deleteOnExit();
    }

    //download the json metadata
    plugins = "https://updates.jenkins-ci.org/";
    ps = new ArrayList<String>();
    doc = Jsoup.connect(plugins).get();
    for (Element file : doc.select("td a")) {
        //System.out.println(file.attr("href"));
        if (file.attr("href").endsWith(".json")) {
            ps.add(file.attr("href"));
        }
    }
    for (int i = 0; i < ps.size(); i++) {
        download(root.getAbsolutePath() + "/" + ps.get(i), plugins + ps.get(i));

        FileInputStream fis = new FileInputStream(root.getAbsolutePath() + "/" + ps.get(i));
        // begin writing a new ZIP entry, positions the stream to the start of the entry data
        zos.putNextEntry(new ZipEntry(plugins + ps.get(i)));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
        new File(root.getAbsolutePath() + "/" + ps.get(i)).deleteOnExit();
        if (throttle)
            Thread.sleep(WAIT);
    }

    // close the ZipOutputStream
    zos.close();
}

From source file:com.sourcethought.simpledaemon.EchoTask.java

public static void main(String[] args) throws Exception {
    // setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "print this help screen");

    // read command line options
    CommandLineParser parser = new PosixParser();
    try {//  ww w . j  a v  a 2  s . co m
        CommandLine cmdline = parser.parse(options, args);

        if (cmdline.hasOption("help") || cmdline.hasOption("h")) {
            System.out.println("SimpleDaemon Version " + Main.version);

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(
                    "java -cp lib/*:target/SimpleDaemon-1.0-SNAPSHOT.jar com.sourcethought.simpledaemon.Main",
                    options);
            return;
        }

        final SimpleDaemon daemon = new SimpleDaemon();
        daemon.start();

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                if (daemon.isRunning()) {
                    try {
                        System.out.println("Shutting down daemon...");
                        daemon.stop();
                    } catch (Exception ex) {
                        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }));

    } catch (ParseException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.floragunn.searchguard.tools.Hasher.java

public static void main(final String[] args) {

    final Options options = new Options();
    final HelpFormatter formatter = new HelpFormatter();
    options.addOption(//from w  ww .  j av a 2 s  .  c o m
            Option.builder("p").argName("password").hasArg().desc("Cleartext password to hash").build());
    options.addOption(Option.builder("env").argName("name environment variable").hasArg()
            .desc("name environment variable to read password from").build());

    final CommandLineParser parser = new DefaultParser();
    try {
        final CommandLine line = parser.parse(options, args);

        if (line.hasOption("p")) {
            System.out.println(hash(line.getOptionValue("p").getBytes("UTF-8")));
        } else if (line.hasOption("env")) {
            final String pwd = System.getenv(line.getOptionValue("env"));
            if (pwd == null || pwd.isEmpty()) {
                throw new Exception("No environment variable '" + line.getOptionValue("env") + "' set");
            }
            System.out.println(hash(pwd.getBytes("UTF-8")));
        } else {
            final Console console = System.console();
            if (console == null) {
                throw new Exception("Cannot allocate a console");
            }
            final char[] passwd = console.readPassword("[%s]", "Password:");
            System.out.println(hash(new String(passwd).getBytes("UTF-8")));
        }
    } catch (final Exception exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        formatter.printHelp("hasher.sh", options, true);
        System.exit(-1);
    }
}

From source file:be.redlab.maven.yamlprops.create.YamlConvertCli.java

public static void main(String... args) throws IOException {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    HelpFormatter formatter = new HelpFormatter();
    options.addOption(Option.builder("s").argName("source").desc("the source folder or file to convert")
            .longOpt("source").hasArg(true).build());
    options.addOption(Option.builder("t").argName("target").desc("the target file to store in")
            .longOpt("target").hasArg(true).build());
    options.addOption(Option.builder("h").desc("print help").build());

    try {/*from   w w w  . ja va 2 s . c om*/
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption('h')) {
            formatter.printHelp("converter", options);
        }
        File source = new File(cmd.getOptionValue("s", System.getProperty("user.dir")));
        String name = source.getName();
        if (source.isDirectory()) {
            PropertiesToYamlConverter yamlConverter = new PropertiesToYamlConverter();
            String[] ext = { "properties" };
            Iterator<File> fileIterator = FileUtils.iterateFiles(source, ext, true);
            while (fileIterator.hasNext()) {
                File next = fileIterator.next();
                System.out.println(next);
                String s = StringUtils.removeStart(next.getParentFile().getPath(), source.getPath());
                System.out.println(s);
                String f = StringUtils.split(s, IOUtils.DIR_SEPARATOR)[0];
                System.out.println("key = " + f);
                Properties p = new Properties();
                try {
                    p.load(new FileReader(next));
                    yamlConverter.addProperties(f, p);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            yamlConverter.writeYaml(fileWriter);
            fileWriter.close();
        } else {
            Properties p = new Properties();
            p.load(new FileReader(source));
            FileWriter fileWriter = new FileWriter(
                    new File(source.getParentFile(), StringUtils.substringBeforeLast(name, ".") + ".yaml"));
            new PropertiesToYamlConverter().addProperties(name, p).writeYaml(fileWriter);
            fileWriter.close();
        }
    } catch (ParseException e) {
        e.printStackTrace();
        formatter.printHelp("converter", options);
    }
}

From source file:com.basingwerk.utilisation.Utilisation.java

public static void main(final String[] args) {
    String dataFile = null;/*from  www. j av a2 s  .c o m*/

    Options options = new Options();

    Option helpOption = new Option("h", "help", false, "print this help");
    Option serverURLOption = new Option("l", "logfile", true, "log file");

    options.addOption(helpOption);
    options.addOption(serverURLOption);

    CommandLineParser argsParser = new PosixParser();

    try {
        CommandLine commandLine = argsParser.parse(options, args);

        if (commandLine.hasOption(helpOption.getOpt())) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Usage grapher", options);
            System.exit(0);
        }

        dataFile = commandLine.getOptionValue(serverURLOption.getOpt());
        String[] otherArgs = commandLine.getArgs();

        if (dataFile == null || otherArgs.length > 1) {
            System.out.println("Please specify a logfile");
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("Usage grapher", options);
            System.exit(0);
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
    }

    final UsagePlotter demo = new UsagePlotter("Usage", new File(dataFile));
    demo.pack();
    RefineryUtilities.centerFrameOnScreen(demo);
    demo.setVisible(true);
}

From source file:edu.freiburg.dbis.rdd.RddExtractor.java

/**
 * @param args// w  ww .  j a  va 2  s. c  o m
 */
public static void main(String[] args) {
    String Classname = RddExtractor.class.getName();
    // Creating and parsing commandline options
    Options options = createOptions();
    CommandLineParser parser = new BasicParser();
    HelpFormatter help = new HelpFormatter();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help.printHelp(Classname, options);
            return;
        }
        // XOR (either input-file or sparql-endpoint) --> Throw error if it is the same
        if (cmd.hasOption("i") == cmd.hasOption("e")) {
            help.printHelp(Classname, options);
            System.err.println(
                    "Use either the the option to read from an input file or (XOR) the option to send queries against an SPARQL Endpoint");
            return;
        }
        // the graph variable can only be used with the sparql-enpoint
        if ((cmd.hasOption("g") == true) && (cmd.hasOption("e") == false)) {
            help.printHelp(Classname, options);
            System.err.println(
                    "The graph variable can only be used when sending queries against a SPARQL Endpoint");
            return;
        }

    } catch (ParseException e) {
        help.printHelp(Classname, options);
        System.err.println("Command line parsing failed. Reason: " + e.getMessage());
        return;
    }

    String INPUT_FILE = cmd.getOptionValue("i");
    String OUTPUT_FILE = cmd.getOptionValue("o");
    String ENDPOINTURL = cmd.getOptionValue("e");
    String VIRTUOSO_GRAPH_NAME = cmd.getOptionValue("g");
    String WA = cmd.getOptionValue("w");
    String propertyFile = "src/main/resources/log4j.properties2";
    if (cmd.hasOption("v")) {
        propertyFile = "src/main/resources/log4j.properties";
    } else if (cmd.hasOption("l")) {
        propertyFile = cmd.getOptionValue("l");
    }
    //      String propertyFile = (cmd.hasOption("l")) ? cmd.getOptionValue("l") : "src/main/resources/log4j.properties2";

    PropertyConfigurator.configure(propertyFile);

    logger.debug("INPUT FILE  : " + INPUT_FILE);
    logger.debug("OUTPUT FILE : " + OUTPUT_FILE);
    logger.debug("ENDPOINT URL: " + ENDPOINTURL);
    logger.debug("GRAPH NAME  : " + VIRTUOSO_GRAPH_NAME);
    logger.debug("WORLD ASSUMP: " + WA);

    long start = System.currentTimeMillis();
    long end = 0;
    logger.info("Starting The Generator");
    Backend back = new Backend(INPUT_FILE, OUTPUT_FILE, ENDPOINTURL, VIRTUOSO_GRAPH_NAME, WA);
    end = System.currentTimeMillis();
    logger.info("Runtime of Generator in ms: " + (end - start));
}

From source file:com.amertkara.multiplerunners.Application.java

public static void main(String[] args) {
    if (args.length == 0) {
        Options options = new Options();
        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();

        Option parserOpt = Option.builder("parse").desc("Parser").build();
        Option analyzerOpt = Option.builder("analyze").desc("Analyzer").build();

        options.addOption(analyzerOpt);//from  ww  w.j a  v a 2 s  .  c  o m
        options.addOption(parserOpt);

        formatter.printHelp("sample", options);
    } else {
        SpringApplication.run(Application.class, args);
    }
}

From source file:io.minimum.minecraft.rbclean.RedisBungeeClean.java

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

    Option hostOption = new Option("h", "host", true, "Sets the Redis host to use.");
    hostOption.setRequired(true);// w  ww .jav a2 s .  com
    options.addOption(hostOption);

    Option portOption = new Option("p", "port", true, "Sets the Redis port to use.");
    options.addOption(portOption);

    Option passwordOption = new Option("w", "password", true, "Sets the Redis password to use.");
    options.addOption(passwordOption);

    Option dryRunOption = new Option("d", "dry-run", false, "Performs a dry run (no data is modified).");
    options.addOption(dryRunOption);

    CommandLine commandLine;

    try {
        commandLine = new DefaultParser().parse(options, args);
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("RedisBungeeClean", options);
        return;
    }

    int port = commandLine.hasOption('p') ? Integer.parseInt(commandLine.getOptionValue('p')) : 6379;

    try (Jedis jedis = new Jedis(commandLine.getOptionValue('h'), port, 0)) {
        if (commandLine.hasOption('w')) {
            jedis.auth(commandLine.getOptionValue('w'));
        }

        System.out.println("Fetching UUID cache...");
        Map<String, String> uuidCache = jedis.hgetAll("uuid-cache");
        Gson gson = new Gson();

        // Just in case we need it, compress everything in JSON format.
        if (!commandLine.hasOption('d')) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
            File file = new File("uuid-cache-previous-" + dateFormat.format(new Date()) + ".json.gz");
            try {
                file.createNewFile();
            } catch (IOException e) {
                System.out.println("Can't write backup of the UUID cache, will NOT proceed.");
                e.printStackTrace();
                return;
            }

            System.out.println("Creating backup (as " + file.getName() + ")...");

            try (OutputStreamWriter bw = new OutputStreamWriter(
                    new GZIPOutputStream(new FileOutputStream(file)))) {
                gson.toJson(uuidCache, bw);
            } catch (IOException e) {
                System.out.println("Can't write backup of the UUID cache, will NOT proceed.");
                e.printStackTrace();
                return;
            }
        }

        System.out.println("Cleaning out the bird cage (this may take a while...)");
        int originalSize = uuidCache.size();
        for (Iterator<Map.Entry<String, String>> it = uuidCache.entrySet().iterator(); it.hasNext();) {
            CachedUUIDEntry entry = gson.fromJson(it.next().getValue(), CachedUUIDEntry.class);

            if (entry.expired()) {
                it.remove();
            }
        }
        int newSize = uuidCache.size();

        if (commandLine.hasOption('d')) {
            System.out.println(
                    (originalSize - newSize) + " records would be expunged if a dry run was not conducted.");
        } else {
            System.out.println("Expunging " + (originalSize - newSize) + " records...");
            Transaction transaction = jedis.multi();
            transaction.del("uuid-cache");
            transaction.hmset("uuid-cache", uuidCache);
            transaction.exec();
            System.out.println("Expunging complete.");
        }
    }
}