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

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

Introduction

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

Prototype

public void printHelp(String cmdLineSyntax, Options options, boolean autoUsage) 

Source Link

Document

Print the help for options with the specified command line syntax.

Usage

From source file:au.id.hazelwood.xmltvguidebuilder.runner.Main.java

public static void main(String[] args) throws Exception {
    SLF4JBridgeHandler.install();//from  w  ww.j a  v  a  2  s .com

    Options options = new Options();
    options.addOption(createOptionWithArg("config", true, "file", File.class, "Config file location"));
    options.addOption(createOptionWithArg("out", true, "file", File.class, "Output file name"));

    try {
        CommandLineParser parser = new GnuParser();
        CommandLine line = parser.parse(options, args);
        App app = new App();
        app.run((File) line.getParsedOptionValue("config"), (File) line.getParsedOptionValue("out"));
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Main", options, true);
    }
}

From source file:io.github.dustalov.maxmax.Application.java

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

    final Options options = new Options();
    options.addOption(Option.builder("in").argName("in").desc("input graph in the ABC format").hasArg()
            .required().build());/*from   w ww.  ja  v a 2  s.c  o m*/
    options.addOption(Option.builder("out").argName("out").desc("name of cluster output file").hasArg()
            .required().build());

    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (final ParseException ex) {
        System.err.println(ex.getMessage());
        final HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar this.jar", options, true);
        System.exit(1);
    }

    final UndirectedGraph<String, DefaultWeightedEdge> graph = parse(cmd.getOptionValue("in"),
            ABCParser::parse);
    final MaxMax<String> maxmax = new MaxMax<>(graph);
    maxmax.run();
    write(cmd.getOptionValue("out"), maxmax);
}

From source file:demo.learn.shiro.tool.PasswordEncryptionTool.java

/**
 * Main method./*w w w .j  a v a  2s  .com*/
 * @param args Requires a plain text password.
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    String plainTextPassword = "root";

    Option p = OptionBuilder.withArgName("password").hasArg().withDescription("plain text password")
            .isRequired(false).create('p');

    Options options = new Options();
    options.addOption(p);

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("p")) {
            plainTextPassword = cmd.getOptionValue("p");
        }
    } catch (ParseException pe) {
        String cmdLineSyntax = "java -cp %CLASSPATH% demo.learn.shiro.tool.PasswordEncryptionTool";
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options, false);
        return;
    }

    final RandomNumberGenerator rng = new SecureRandomNumberGenerator();

    final ByteSource salt = rng.nextBytes();
    final String saltBase64 = Base64.encodeToString(salt.getBytes());
    final String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt, S.HASH_ITER).toBase64();

    System.out.print("-p " + plainTextPassword);
    System.out.print(" -h " + hashedPasswordBase64);
    System.out.println(" -s " + saltBase64);
}

From source file:di.uniba.it.tee2.search.Search.java

/**
 * language maindir query temp_query/*  w w w  .j a  v a  2s  .  co m*/
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {
        CommandLine cmd = cmdParser.parse(options, args);
        if (cmd.hasOption("l") && cmd.hasOption("d") && cmd.hasOption("q")) {
            try {
                TemporalExtractor te = new TemporalExtractor(cmd.getOptionValue("l"));
                te.init();
                TemporalEventSearch search = new TemporalEventSearch(cmd.getOptionValue("d"), te);
                search.init();
                List<SearchResult> res = search.search(cmd.getOptionValue("q"), cmd.getOptionValue("t", ""),
                        100);
                for (SearchResult r : res) {
                    System.out.println(r);
                }
                search.close();
                te.close();
            } catch (Exception ex) {
                Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Run searching", options, true);
        }
    } catch (ParseException ex) {
        Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.cloudera.flume.handlers.debug.TextToCollector.java

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

    Options opts = new Options();
    opts.addOption("m", false, "Load events into memory");
    opts.addOption("t", false, "Simple text file format loader");
    opts.addOption("l", false, "Log4j text file format loader");

    try {//from w  w w.j a  v  a 2  s  .c o m
        if (argv.length < 1) {
            HelpFormatter fmt = new HelpFormatter();
            fmt.printHelp("TextToCollector", opts, true);
            System.exit(-1);
        }

        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(opts, argv);

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

}

From source file:com.commonsware.android.gcm.cmd.GCM.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Option helpOpt = new Option("h", "help", false, "print this message");
    Option apiKeyOpt = OptionBuilder.withArgName("key").hasArg().isRequired().withDescription("GCM API key")
            .withLongOpt("apiKey").create('a');
    Option deviceOpt = OptionBuilder.withArgName("regId").hasArg().isRequired()
            .withDescription("device to send to").withLongOpt("device").create('d');
    Option dataOpt = OptionBuilder.withArgName("key=value").hasArgs(2).withDescription("datum to send")
            .withValueSeparator().withLongOpt("data").create('D');

    Options options = new Options();

    options.addOption(apiKeyOpt);/*from  www  .jav a2 s . co m*/
    options.addOption(deviceOpt);
    options.addOption(dataOpt);
    options.addOption(helpOpt);

    CommandLineParser parser = new PosixParser();

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

        if (line.hasOption('h') || !line.hasOption('a') || !line.hasOption('d')) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("gcm", options, true);
        } else {
            sendMessage(line.getOptionValue('a'), Arrays.asList(line.getOptionValues('d')),
                    line.getOptionProperties("data"));
        }
    } catch (org.apache.commons.cli.MissingOptionException moe) {
        System.err.println("Invalid command syntax");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("gcm", options, true);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:demo.learn.shiro.tool.PasswordMatcherTool.java

/**
 * Main method.// ww w . j  a  v  a  2 s  .co  m
 * @param args Pass in plain text password, hashed password,
 * and salt. These arguments are generated from
 * {@link PasswordEncryptionTool}.
 * @throws ParseException
 */
@SuppressWarnings("static-access")
public static void main(String[] args) throws ParseException {
    String username = "";
    String plainTextPassword = "root";
    String hashedPasswordBase64 = "ZzIkhapTVzGkhWRQqdUn2zod5npt9RJMSni8My6X+r8=";
    String saltBase64 = "BobnkcsIXcZGksA30eOySA==";
    String realmName = "";

    Option p = OptionBuilder.withArgName("password").hasArg().withDescription("plain text password")
            .isRequired(false).create('p');
    Option h = OptionBuilder.withArgName("password").hasArg().withDescription("hashed password")
            .isRequired(false).create('h');
    Option s = OptionBuilder.withArgName("salt").hasArg().withDescription("salt (Base64 encoded)")
            .isRequired(false).create('s');

    Options options = new Options();
    options.addOption(p);
    options.addOption(h);
    options.addOption(s);

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("p")) {
            plainTextPassword = cmd.getOptionValue("p");
        }
        if (cmd.hasOption("h")) {
            hashedPasswordBase64 = cmd.getOptionValue("h");
        }
        if (cmd.hasOption("s")) {
            saltBase64 = cmd.getOptionValue("s");
        }
    } catch (ParseException pe) {
        String cmdLineSyntax = "java -cp %CLASSPATH% demo.learn.shiro.tool.PasswordMatcherTool";
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options, false);
        return;
    }

    SimpleByteSource salt = new SimpleByteSource(Base64.decode(saltBase64));
    SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username, hashedPasswordBase64, salt,
            realmName);
    UsernamePasswordToken token = new UsernamePasswordToken(username, plainTextPassword);

    HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
    matcher.setHashIterations(S.HASH_ITER);
    matcher.setStoredCredentialsHexEncoded(false);
    matcher.setHashAlgorithmName(S.ALGORITHM_NAME);

    boolean result = matcher.doCredentialsMatch(token, info);
    System.out.println("match? " + result);

}

From source file:fr.inria.atlanmod.kyanos.benchmarks.XmiTraverser.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input model");
    inputOpt.setArgs(1);/*  w ww.  j a  v a 2  s .c o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

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

        URI uri = URI.createFileURI(commandLine.getOptionValue(IN));

        Class<?> inClazz = XmiTraverser.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("xmi",
                new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("zxmi",
                new XMIResourceFactoryImpl());

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);

        LOG.log(Level.INFO, "Start counting");
        int count = 0;
        long begin = System.currentTimeMillis();
        for (Iterator<EObject> iterator = resource.getAllContents(); iterator.hasNext(); iterator
                .next(), count++)
            ;
        long end = System.currentTimeMillis();
        LOG.log(Level.INFO, "End counting");
        LOG.log(Level.INFO, MessageFormat.format("Resource {0} contains {1} elements", uri, count));
        LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));

        resource.unload();

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}

From source file:di.uniba.it.tee2.wiki.Wikidump2Text.java

/**
 * @param args the command line arguments
 *//*from  ww  w . java  2 s.co  m*/
public static void main(String[] args) {
    try {
        CommandLine cmd = cmdParser.parse(options, args);
        if (cmd.hasOption("l") && cmd.hasOption("d") && cmd.hasOption("o")) {
            encoding = cmd.getOptionValue("e", "UTF-8");
            int counter = 0;
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                        new GZIPOutputStream(new FileOutputStream(cmd.getOptionValue("o"))), "UTF-8"));
                WikipediaDumpIterator it = new WikipediaDumpIterator(new File(cmd.getOptionValue("d")),
                        encoding);
                PageCleaner cleaner = PageCleanerWrapper.getInstance(cmd.getOptionValue("l"));
                while (it.hasNext()) {
                    WikiPage wikiPage = it.next();
                    ParsedPage parsedPage = wikiPage.getParsedPage();
                    if (parsedPage != null) {
                        String title = wikiPage.getTitle();
                        if (!title.matches(notValidTitle)) {
                            if (parsedPage.getText() != null) {
                                writer.append(cleaner.clean(parsedPage.getText()));
                                writer.newLine();
                                writer.newLine();
                                counter++;
                                if (counter % 10000 == 0) {
                                    System.out.println(counter);
                                    writer.flush();
                                }
                            }
                        }
                    }
                }
                writer.flush();
                writer.close();
            } catch (Exception ex) {
                Logger.getLogger(Wikidump2Text.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Indexed pages: " + counter);
        } else {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Wikipedia dump to text", options, true);
        }
    } catch (ParseException ex) {
        Logger.getLogger(Wikidump2Text.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:fr.inria.atlanmod.kyanos.benchmarks.KyanosMapQueryGrabats.java

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

    Option inputOpt = OptionBuilder.create(IN);
    inputOpt.setArgName("INPUT");
    inputOpt.setDescription("Input Kyanos resource directory");
    inputOpt.setArgs(1);/*from   ww  w .  j  a va  2 s .c o  m*/
    inputOpt.setRequired(true);

    Option inClassOpt = OptionBuilder.create(EPACKAGE_CLASS);
    inClassOpt.setArgName("CLASS");
    inClassOpt.setDescription("FQN of EPackage implementation class");
    inClassOpt.setArgs(1);
    inClassOpt.setRequired(true);

    options.addOption(inputOpt);
    options.addOption(inClassOpt);

    CommandLineParser parser = new PosixParser();

    try {
        PersistenceBackendFactoryRegistry.getFactories().put(NeoMapURI.NEO_MAP_SCHEME,
                new MapPersistenceBackendFactory());

        CommandLine commandLine = parser.parse(options, args);

        URI uri = NeoMapURI.createNeoMapURI(new File(commandLine.getOptionValue(IN)));

        Class<?> inClazz = KyanosMapQueryGrabats.class.getClassLoader()
                .loadClass(commandLine.getOptionValue(EPACKAGE_CLASS));
        inClazz.getMethod("init").invoke(null);

        ResourceSet resourceSet = new ResourceSetImpl();
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoMapURI.NEO_MAP_SCHEME,
                PersistentResourceFactory.eINSTANCE);

        Resource resource = resourceSet.createResource(uri);

        Map<String, Object> loadOpts = new HashMap<String, Object>();
        resource.load(loadOpts);
        {
            LOG.log(Level.INFO, "Start query");
            long begin = System.currentTimeMillis();
            EList<ClassDeclaration> list = JavaQueries.grabats09(resource);
            long end = System.currentTimeMillis();
            LOG.log(Level.INFO, "End query");
            LOG.log(Level.INFO, MessageFormat.format("Query result contains {0} elements", list.size()));
            LOG.log(Level.INFO, MessageFormat.format("Time spent: {0}", MessageUtil.formatMillis(end - begin)));
        }

        if (resource instanceof PersistentResourceImpl) {
            PersistentResourceImpl.shutdownWithoutUnload((PersistentResourceImpl) resource);
        } else {
            resource.unload();
        }

    } catch (ParseException e) {
        MessageUtil.showError(e.toString());
        MessageUtil.showError("Current arguments: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar <this-file.jar>", options, true);
    } catch (Throwable e) {
        MessageUtil.showError(e.toString());
    }
}