Example usage for org.apache.commons.cli CommandLine hasOption

List of usage examples for org.apache.commons.cli CommandLine hasOption

Introduction

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

Prototype

public boolean hasOption(char opt) 

Source Link

Document

Query to see if an option has been set.

Usage

From source file:com.yahoo.gondola.cli.GondolaAgent.java

public static void main(String[] args) throws ParseException, IOException {
    PropertyConfigurator.configure("conf/log4j.properties");
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();
    options.addOption("port", true, "Listening port");
    options.addOption("config", true, "config file");
    options.addOption("h", false, "help");
    CommandLine commandLine = parser.parse(options, args);

    if (commandLine.hasOption("help")) {
        new HelpFormatter().printHelp("GondolaAgent", options);
        return;//w  ww .  j  a v a  2s  .  c  o m
    }

    if (commandLine.hasOption("port")) {
        port = Integer.parseInt(commandLine.getOptionValue("port"));
    } else {
        port = 1200;
    }
    if (commandLine.hasOption("config")) {
        configFile = commandLine.getOptionValue("config");
    }

    config = new Config(new File(configFile));

    logger.info("Initialize system, kill all gondola processes");
    new DefaultExecutor().execute(org.apache.commons.exec.CommandLine.parse("bin/gondola-local-test.sh stop"));

    new GondolaAgent(port);
}

From source file:glacierpipe.GlacierPipeMain.java

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

    CommandLine cmd = parser.parse(OPTIONS, args);

    if (cmd.hasOption("help")) {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            printHelp(writer);//from  ww  w  .  j  a v a 2s. com
        }

        System.exit(0);
    } else if (cmd.hasOption("upload")) {

        // Turn the CommandLine into Properties
        Properties cliProperties = new Properties();
        for (Iterator<?> i = cmd.iterator(); i.hasNext();) {
            Option o = (Option) i.next();

            String opt = o.getLongOpt();
            opt = opt != null ? opt : o.getOpt();

            String value = o.getValue();
            value = value != null ? value : "";

            cliProperties.setProperty(opt, value);
        }

        // Build up a configuration
        ConfigBuilder configBuilder = new ConfigBuilder();

        // Archive name
        List<?> archiveList = cmd.getArgList();
        if (archiveList.size() > 1) {
            throw new ParseException("Too many arguments");
        } else if (archiveList.isEmpty()) {
            throw new ParseException("No archive name provided");
        }

        configBuilder.setArchive(archiveList.get(0).toString());

        // All other arguments on the command line
        configBuilder.setFromProperties(cliProperties);

        // Load any config from the properties file
        Properties fileProperties = new Properties();
        try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) {
            fileProperties.load(in);
        } catch (IOException e) {
            System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile,
                    e);
        }

        configBuilder.setFromProperties(fileProperties);

        // ...
        Config config = new Config(configBuilder);

        IOBuffer buffer = new MemoryIOBuffer(config.partSize);

        AmazonGlacierClient client = new AmazonGlacierClient(
                new BasicAWSCredentials(config.accessKey, config.secretKey));
        client.setEndpoint(config.endpoint);

        // Actual upload
        try (InputStream in = new BufferedInputStream(System.in, 4096);
                PrintWriter writer = new PrintWriter(System.err);
                ObservableProperties configMonitor = config.reloadProperties
                        ? new ObservableProperties(config.propertiesFile)
                        : null;
                ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) {
            TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer);

            if (configMonitor != null) {
                configMonitor.registerObserver(throttlingStrategy);
            }

            GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy);
            pipe.pipe(client, config.vault, config.archive, in);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        System.exit(0);
    } else {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            writer.println("No action specified.");
            printHelp(writer);
        }

        System.exit(-1);
    }
}

From source file:com.astexample.Recognize.java

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

    String audioFile = "";
    String host = "speech.googleapis.com";
    Integer port = 443;/*from   w  w w .  j a v  a  2  s  .c om*/
    Integer sampling = 16000;

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("file").withDescription("path to audio file").hasArg()
            .withArgName("FILE_PATH").create());
    options.addOption(
            OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com")
                    .hasArg().withArgName("ENDPOINT").create());
    options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg()
            .withArgName("PORT").create());
    options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000")
            .hasArg().withArgName("RATE").create());

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("file")) {
            audioFile = line.getOptionValue("file");
        } else {
            System.err.println("An Audio file must be specified (e.g. /foo/baz.raw).");
            System.exit(1);
        }

        if (line.hasOption("host")) {
            host = line.getOptionValue("host");
        } else {
            System.err.println("An API enpoint must be specified (typically speech.googleapis.com).");
            System.exit(1);
        }

        if (line.hasOption("port")) {
            port = Integer.parseInt(line.getOptionValue("port"));
        } else {
            System.err.println("An SSL port must be specified (typically 443).");
            System.exit(1);
        }

        if (line.hasOption("sampling")) {
            sampling = Integer.parseInt(line.getOptionValue("sampling"));
        } else {
            System.err.println("An Audio sampling rate must be specified.");
            System.exit(1);
        }
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    Recognize client = new Recognize(host, port, audioFile, sampling);
    try {
        client.recognize();
    } finally {
        client.shutdown();
    }
}

From source file:com.astexample.RecognizeGoogleTest.java

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

    String audioFile = "";
    String host = "speech.googleapis.com";
    Integer port = 443;//from   w ww  . j av a 2 s. c  om
    Integer sampling = 16000;

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("file").withDescription("path to audio file").hasArg()
            .withArgName("FILE_PATH").create());
    options.addOption(
            OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com")
                    .hasArg().withArgName("ENDPOINT").create());
    options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg()
            .withArgName("PORT").create());
    options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000")
            .hasArg().withArgName("RATE").create());

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("file")) {
            audioFile = line.getOptionValue("file");
        } else {
            System.err.println("An Audio file must be specified (e.g. /foo/baz.raw).");
            System.exit(1);
        }

        if (line.hasOption("host")) {
            host = line.getOptionValue("host");
        } else {
            System.err.println("An API enpoint must be specified (typically speech.googleapis.com).");
            System.exit(1);
        }

        if (line.hasOption("port")) {
            port = Integer.parseInt(line.getOptionValue("port"));
        } else {
            System.err.println("An SSL port must be specified (typically 443).");
            System.exit(1);
        }

        if (line.hasOption("sampling")) {
            sampling = Integer.parseInt(line.getOptionValue("sampling"));
        } else {
            System.err.println("An Audio sampling rate must be specified.");
            System.exit(1);
        }
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    RecognizeGoogleTest client = new RecognizeGoogleTest(host, port, audioFile, sampling);
    try {
        client.recognize();
    } finally {
        client.shutdown();
    }
}

From source file:com.google.cloud.speech.grpc.demos.RecognizeClient.java

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

    String audioFile = "";
    String host = "speech.googleapis.com";
    Integer port = 443;/*  w  w w . j a  v a 2 s .  c  o  m*/
    Integer sampling = 16000;

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("file").withDescription("path to audio file").hasArg()
            .withArgName("FILE_PATH").create());
    options.addOption(
            OptionBuilder.withLongOpt("host").withDescription("endpoint for api, e.g. speech.googleapis.com")
                    .hasArg().withArgName("ENDPOINT").create());
    options.addOption(OptionBuilder.withLongOpt("port").withDescription("SSL port, usually 443").hasArg()
            .withArgName("PORT").create());
    options.addOption(OptionBuilder.withLongOpt("sampling").withDescription("Sampling Rate, i.e. 16000")
            .hasArg().withArgName("RATE").create());

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("file")) {
            audioFile = line.getOptionValue("file");
        } else {
            System.err.println("An Audio file must be specified (e.g. /foo/baz.raw).");
            System.exit(1);
        }

        if (line.hasOption("host")) {
            host = line.getOptionValue("host");
        } else {
            System.err.println("An API enpoint must be specified (typically speech.googleapis.com).");
            System.exit(1);
        }

        if (line.hasOption("port")) {
            port = Integer.parseInt(line.getOptionValue("port"));
        } else {
            System.err.println("An SSL port must be specified (typically 443).");
            System.exit(1);
        }

        if (line.hasOption("sampling")) {
            sampling = Integer.parseInt(line.getOptionValue("sampling"));
        } else {
            System.err.println("An Audio sampling rate must be specified.");
            System.exit(1);
        }
    } catch (ParseException exp) {
        System.err.println("Unexpected exception:" + exp.getMessage());
        System.exit(1);
    }

    RecognizeClient client = new RecognizeClient(host, port, audioFile, sampling);
    try {
        client.recognize();
    } finally {
        client.shutdown();
    }
}

From source file:it.jnrpe.server.CJNRPEServer.java

public static void main(String[] args) {
    CommandLine cl = parseCommandLine(args);

    if (cl.hasOption("help") && cl.getOptionValue("help") == null)
        printUsage();/*from w w w. j  a v a  2 s  .co  m*/

    if (cl.hasOption("version"))
        printVersion();

    CJNRPEConfiguration.init(cl.getOptionValue("conf"));

    if (cl.hasOption("help") && cl.getOptionValue("help") != null)
        printHelp(cl.getOptionValue("help"));

    if (cl.hasOption("list"))
        printPluginList();

    if (cl.hasOption("generateConfig"))
        generateScheletonConfig(cl.getOptionValue("generateConfig"));

    //        // Configure the timeout watcher
    //        m_ThreadTimeoutWatcher = new ThreadTimeoutWatcher();
    //        m_ThreadTimeoutWatcher.setThreadTimeout(CJNRPEConfiguration.getInstance().getThreadTimeout());
    //        m_ThreadTimeoutWatcher.start();

    List vBindings = CJNRPEConfiguration.getInstance().getServerBindings();

    for (Iterator iterator = vBindings.iterator(); iterator.hasNext();) {
        CBinding binding = (CBinding) iterator.next();
        try {
            CBindingThread bt = new CBindingThread(binding);
            bt.setAcceptedHosts(CJNRPEConfiguration.getInstance().getAcceptedHosts());
            bt.start();
            m_vBindingThreads.add(bt);
        } catch (Exception e) {
            System.out.println("ERROR BINDING TO ADDRESS " + binding.getIP() + ":" + binding.getPort() + " - "
                    + e.getMessage());
            System.exit(-1);
        }
    }
}

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;
    try {//from w  w  w . java 2s  .c  o  m
        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.dhenton9000.screenshots.ScreenShotLauncher.java

/**
 * main launching method that takes command line arguments
 *
 * @param args/*from   w  ww. j  a  v  a 2s  . c  om*/
 */
public static void main(String[] args) {

    final String[] actions = { ACTIONS.source.toString(), ACTIONS.target.toString(),
            ACTIONS.compare.toString() };
    final List actionArray = Arrays.asList(actions);

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("action").hasArg().isRequired().withArgName("action").create());
    HelpFormatter formatter = new HelpFormatter();

    String header = "Process screenshots\n" + "--action=source   create source screenshots\n"
            + "--action=target     create the screenshots for comparison\n"
            + "--action=compare  compare the images\n" + "%s\n\n";

    String action = null;
    try {
        // parse the command line arguments
        CommandLineParser parser = new PosixParser();
        CommandLine line = parser.parse(options, args);

        // validate that action option has been set
        if (line.hasOption("action")) {
            action = line.getOptionValue("action");
            LOG.debug("action '" + action + "'");
            if (!actionArray.contains(action)) {

                formatter.printHelp(ScreenShotLauncher.class.getName(),
                        String.format(header, String.format("action option '%s' is invalid", action)), options,
                        "\n\n", true);
                System.exit(1);

            }

        } else {
            formatter.printHelp(ScreenShotLauncher.class.getName(), String.format(header, "not found"), options,
                    "\n\n", false);
            System.exit(1);
        }
    } catch (ParseException exp) {
        formatter.printHelp(ScreenShotLauncher.class.getName(),
                String.format(header, "problem " + exp.getMessage()), options, "\n\n", false);
        System.exit(1);

    }
    ACTIONS actionEnum = ACTIONS.valueOf(action);
    ScreenShotLauncher launcher = new ScreenShotLauncher();
    try {
        launcher.handleRequest(actionEnum);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);

    }
}

From source file:de.bamamoto.mactools.png2icns.Scaler.java

public static void main(String[] args) {

    Options options = new Options();
    options.addOption("i", "input-filename", true,
            "Filename ofthe image containing the icon. The image should be a square with at least 1024x124 pixel in PNG format.");
    options.addOption("o", "iconset-foldername", true,
            "Name of the folder where the iconset will be stored. The extension .iconset will be added automatically.");
    String folderName;// w ww  .jav  a  2  s .  c o  m
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("i")) {
            if (new File(cmd.getOptionValue("i")).isFile()) {

                if (cmd.hasOption("o")) {
                    folderName = cmd.getOptionValue("o");
                } else {
                    folderName = "/tmp/noname.iconset";
                }

                if (!folderName.endsWith(".iconset")) {
                    folderName = folderName + ".iconset";
                }
                new File(folderName).mkdirs();

                BufferedImage source = ImageIO.read(new File(cmd.getOptionValue("i")));
                BufferedImage resized = resize(source, 1024, 1024);
                save(resized, folderName + "/icon_512x512@2x.png");
                resized = resize(source, 512, 512);
                save(resized, folderName + "/icon_512x512.png");
                save(resized, folderName + "/icon_256x256@2x.png");

                resized = resize(source, 256, 256);
                save(resized, folderName + "/icon_256x256.png");
                save(resized, folderName + "/icon_128x128@2x.png");

                resized = resize(source, 128, 128);
                save(resized, folderName + "/icon_128x128.png");

                resized = resize(source, 64, 64);
                save(resized, folderName + "/icon_32x32@2x.png");

                resized = resize(source, 32, 32);
                save(resized, folderName + "/icon_32x32.png");
                save(resized, folderName + "/icon_16x16@2x.png");

                resized = resize(source, 16, 16);
                save(resized, folderName + "/icon_16x16.png");

                Scaler.runProcess(new String[] { "/usr/bin/iconutil", "-c", "icns", folderName });
            }
        }

    } catch (IOException e) {
        System.out.println("Error reading image: " + cmd.getOptionValue("i"));
        e.printStackTrace();

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

From source file:com.jones_systems.Tieout.java

public static void main(String[] args) {

    String testFilename = null;//from  www.j  a  v a2  s.  c om

    Options options = new Options();

    //options.addOption("f", "filename", true, "the file to use for the Tieout check");
    Option filename = OptionBuilder.withArgName("filename").hasArg()
            .withDescription("the file name of the XML test file").create("filename");
    options.addOption(filename);

    CommandLineParser parser = new GnuParser();

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

        if (line.hasOption("filename")) {
            testFilename = line.getOptionValue("filename");
        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("tieout", options);
            System.exit(2);
        }

    } catch (ParseException exp) {

    }

    File testfile = new File(testFilename);

    if (!testfile.exists()) {
        System.err.println("Cannot find file!");
        System.exit(1);
    }

    System.out.println("Starting test with file: " + testFilename);

    Tieout ts = new Tieout(testfile);
    boolean connected = ts.connectDatasources();

    if (!connected) {
        System.err.print("Could not connect to all datasources");
        System.exit(1);
    }

    ts.runTests();

}