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.examples.cloud.speech.SyncRecognizeClient.java

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

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

    CommandLineParser parser = new DefaultParser();

    Options options = new Options();
    options.addOption(OptionBuilder.withLongOpt("uri").withDescription("path to audio uri").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("uri")) {
            audioFile = line.getOptionValue("uri");
        } else {
            System.err.println("An Audio uri must be specified (e.g. file:///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);
    }

    ManagedChannel channel = AsyncRecognizeClient.createChannel(host, port);
    SyncRecognizeClient client = new SyncRecognizeClient(channel, URI.create(audioFile), sampling);
    try {
        client.recognize();
    } finally {
        client.shutdown();
    }
}

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

/**
 * @param args/* w ww . j  a v  a  2s. 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:de.dominicscheurer.passwords.Main.java

/**
 * @param args//  w  w  w  .  j  av a  2  s .  c  o m
 *            Command line arguments (see code or output of program when
 *            started with no arguments).
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();

    Option seedPwdOpt = OptionBuilder.withArgName("Seed Password").isRequired().hasArg()
            .withDescription("Password used as a seed").withLongOpt("seed-password").create("s");

    Option serviceIdOpt = OptionBuilder.withArgName("Service Identifier").isRequired().hasArg()
            .withDescription("The service that the password is created for, e.g. facebook.com")
            .withLongOpt("service-identifier").create("i");

    Option pwdLengthOpt = OptionBuilder.withArgName("Password Length").withType(Integer.class).hasArg()
            .withDescription("Length of the password in characters").withLongOpt("pwd-length").create("l");

    Option specialChars = OptionBuilder.withArgName("With special chars (TRUE|false)").withType(Boolean.class)
            .hasArg().withDescription("Set to true if special chars !-_?=@/+* are desired, else false")
            .withLongOpt("special-chars").create("c");

    Option suppressPwdOutpOpt = OptionBuilder
            .withDescription("Suppress password output (copy to clipboard only)").withLongOpt("hide-password")
            .hasArg(false).create("x");

    Option helpOpt = OptionBuilder.withDescription("Prints this help message").withLongOpt("help").create("h");

    options.addOption(seedPwdOpt);
    options.addOption(serviceIdOpt);
    options.addOption(pwdLengthOpt);
    options.addOption(specialChars);
    options.addOption(suppressPwdOutpOpt);
    options.addOption(helpOpt);

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

        if (cmd.hasOption("h")) {
            SafePwdGen.printHelp(options);
            System.exit(0);
        }

        int pwdLength = STD_PWD_LENGTH;
        if (cmd.hasOption("l")) {
            pwdLength = new Integer(cmd.getOptionValue("l"));
        }

        boolean useSpecialChars = true;
        if (cmd.hasOption("c")) {
            useSpecialChars = new Boolean(cmd.getOptionValue("c"));
        }

        if (pwdLength > MAX_PWD_LENGTH_64 && !useSpecialChars) {
            System.out.println(PASSWORD_SIZE_TOO_BIG + MAX_PWD_LENGTH_64);
        }

        if (pwdLength > MAX_PWD_LENGTH_71 && useSpecialChars) {
            System.out.println(PASSWORD_SIZE_TOO_BIG + MAX_PWD_LENGTH_71);
        }

        boolean suppressPwdOutput = cmd.hasOption('x');

        String pwd = SafePwdGen.createPwd(cmd.getOptionValue("s"), cmd.getOptionValue("i"), pwdLength,
                useSpecialChars);

        if (!suppressPwdOutput) {
            System.out.print(GENERATED_PASSWORD);
            System.out.println(pwd);
        }
        System.out.println(CLIPBOARD_COPIED_MSG);
        SystemClipboardInterface.copy(pwd);

        System.in.read();
    } catch (ParseException e) {
        System.out.println(e.getLocalizedMessage());
        SafePwdGen.printHelp(options);
    } catch (UnsupportedEncodingException e) {
        System.out.println(e.getLocalizedMessage());
    } catch (NoSuchAlgorithmException e) {
        System.out.println(e.getLocalizedMessage());
    } catch (IOException e) {
        System.out.println(e.getLocalizedMessage());
    }
}

From source file:mecard.MetroService.java

public static void main(String[] args) {
    // First get the valid options
    Options options = new Options();
    // add t option c to config directory true=arg required.
    options.addOption("c", true,
            "configuration file directory path, include all sys dependant dir seperators like '/'.");
    // add t option c to config directory true=arg required.
    options.addOption("v", false, "Metro server version information.");
    try {/*from   w  w  w .  jav  a2s . c o m*/
        // parse the command line.
        CommandLineParser parser = new BasicParser();
        CommandLine cmd;
        cmd = parser.parse(options, args);
        if (cmd.hasOption("v")) {
            System.out.println("Metro (MeCard) server version " + PropertyReader.VERSION);
        }
        // get c option value
        String configDirectory = cmd.getOptionValue("c");
        PropertyReader.setConfigDirectory(configDirectory);
    } catch (ParseException ex) {
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println(
                new Date() + "Unable to parse command line option. Please check your service configuration.");
        System.exit(799);
    }

    Properties properties = PropertyReader.getProperties(ConfigFileTypes.ENVIRONMENT);
    String portString = properties.getProperty(LibraryPropertyTypes.METRO_PORT.toString(), defaultPort);

    try {
        int port = Integer.parseInt(portString);
        serverSocket = new ServerSocket(port);
    } catch (IOException ex) {
        String msg = " Could not listen on port: " + portString;
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    } catch (NumberFormatException ex) {
        String msg = "Could not parse port number defined in configuration file.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    }

    while (listening) {
        try {
            new SocketThread(serverSocket.accept()).start();
        } catch (IOException ex) {
            String msg = "unable to start server socket; either accept or start failed.";
            //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
            System.out.println(new Date() + msg);
        }
    }
    try {
        serverSocket.close();
    } catch (IOException ex) {
        String msg = "failed to close the server socket.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg);
    }
}

From source file:com.zimbra.cs.mailbox.calendar.FixCalendarTZUtil.java

public static void main(String[] args) {
    CliUtil.toolSetup();//  w  ww .  j  a v  a2 s  . c o  m
    FixCalendarTZUtil util = null;
    try {
        util = new FixCalendarTZUtil();
    } catch (ServiceException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    try {
        CommandLine cl = util.getCommandLine(args);
        if (cl == null)
            return;
        if (!cl.hasOption(O_RULEFILE))
            throw new ParseException("Missing required option --" + O_RULEFILE);
        String after = null;
        if (cl.hasOption(O_AFTER))
            after = cl.getOptionValue(O_AFTER);

        util.doit(getZAuthToken(cl), cl.getOptionValue(O_RULEFILE), cl.getOptionValues(O_ACCOUNT), after,
                cl.hasOption(O_SYNC));
        System.exit(0);
    } catch (ParseException e) {
        util.usage(e);
    } catch (Exception e) {
        System.err.println("Error occurred: " + e.getMessage());
        util.usage(null);
    }
    System.exit(1);
}

From source file:com.chschmid.pilight.server.PILight.java

public static void main(String args[]) throws Exception {
    // Application Title
    System.out.println(TITLE);//from  w ww .j a v  a2  s.  c  om

    // Apache CLI Parser
    Options options = getCLIOptions();
    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("c"))
            cli = true;
        if (line.hasOption("d"))
            DEBUG = true;
        if (line.hasOption("h")) {
            printHelp();
            return;
        }
    } catch (ParseException exp) {
        System.out.println(PILIGHT + ": " + exp.getMessage());
        System.out.println(ERROR_CLI);
        return;
    }

    // Init BoosterPack and check if SPI and RF work properly
    RFBoosterPack rf = new RFBoosterPack();

    if (rf.getSPIStatus() != RFBoosterPack.STATUS_SPI_INITIALIZED) {
        System.out.println(ERROR_SPI);
        return;
    }
    if (rf.getRFStatus() != RFBoosterPack.STATUS_RF_INITIALIZED) {
        System.out.println(ERROR_RF);
        return;
    }

    // Initialize nicer interface
    PiLightInterface light = new PiLightInterface(rf);
    try {
        Thread.sleep(10);
    } catch (InterruptedException e) {
    }

    if (cli)
        simpleCommandLineInterface(light);
    else
        startServers(light);
}

From source file:edu.msu.cme.rdp.probematch.cli.PrimerMatch.java

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

    PrintStream out = new PrintStream(System.out);
    int maxDist = Integer.MAX_VALUE;

    try {//from w  w  w  .j a v a2s  .  com
        CommandLine line = new PosixParser().parse(options, args);
        if (line.hasOption("outFile")) {
            out = new PrintStream(new File(line.getOptionValue("outFile")));
        }
        if (line.hasOption("maxDist")) {
            maxDist = Integer.valueOf(line.getOptionValue("maxDist"));
        }
        args = line.getArgs();

        if (args.length != 2) {
            throw new Exception("Unexpected number of command line arguments");
        }
    } catch (Exception e) {
        System.err.println("Error: " + e.getMessage());
        new HelpFormatter().printHelp("PrimerMatch <primer_list | primer_file> <seq_file>", options);
        return;
    }

    List<PatternBitMask64> primers = new ArrayList();
    if (new File(args[0]).exists()) {
        File primerFile = new File(args[0]);
        SequenceFormat seqformat = SeqUtils.guessFileFormat(primerFile);

        if (seqformat.equals(SequenceFormat.FASTA)) {
            SequenceReader reader = new SequenceReader(primerFile);
            Sequence seq;

            while ((seq = reader.readNextSequence()) != null) {
                primers.add(new PatternBitMask64(seq.getSeqString(), true, seq.getSeqName()));
            }
            reader.close();
        } else {
            BufferedReader reader = new BufferedReader(new FileReader(args[0]));
            String line;

            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.equals("")) {
                    primers.add(new PatternBitMask64(line, true));
                }
            }
            reader.close();
        }
    } else {
        for (String primer : args[0].split(",")) {
            primers.add(new PatternBitMask64(primer, true));
        }
    }

    SeqReader seqReader = new SequenceReader(new File(args[1]));
    Sequence seq;
    String primerRegion;

    out.println("#seqname\tdesc\tprimer_index\tprimer_name\tposition\tmismatches\tseq_primer_region");
    while ((seq = seqReader.readNextSequence()) != null) {
        for (int index = 0; index < primers.size(); index++) {
            PatternBitMask64 primer = primers.get(index);
            BitVector64Result results = BitVector64.process(seq.getSeqString().toCharArray(), primer, maxDist);

            for (BitVector64Match result : results.getResults()) {
                primerRegion = seq.getSeqString().substring(
                        Math.max(0, result.getPosition() - primer.getPatternLength()), result.getPosition());

                if (result.getPosition() < primer.getPatternLength()) {
                    for (int pad = result.getPosition(); pad < primer.getPatternLength(); pad++) {
                        primerRegion = "x" + primerRegion;
                    }
                }

                out.println(seq.getSeqName() + "\t" + seq.getDesc() + "\t" + (index + 1) + "\t"
                        + primer.getPrimerName() + "\t" + result.getPosition() + "\t" + result.getScore() + "\t"
                        + primerRegion);
            }
        }
    }
    out.close();
    seqReader.close();
}

From source file:gobblin.yarn.GobblinYarnTaskRunner.java

public static void main(String[] args) throws Exception {
    Options options = buildOptions();/*from   w ww .j  a v  a2 s .  c o m*/
    try {
        CommandLine cmd = new DefaultParser().parse(options, args);
        if (!cmd.hasOption(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME)
                || !cmd.hasOption(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME)) {
            printUsage(options);
            System.exit(1);
        }

        Log4jConfigurationHelper.updateLog4jConfiguration(GobblinTaskRunner.class,
                GobblinYarnConfigurationKeys.GOBBLIN_YARN_LOG4J_CONFIGURATION_FILE,
                GobblinYarnConfigurationKeys.GOBBLIN_YARN_LOG4J_CONFIGURATION_FILE);

        LOGGER.info(JvmUtils.getJvmInputArguments());

        ContainerId containerId = ConverterUtils
                .toContainerId(System.getenv().get(ApplicationConstants.Environment.CONTAINER_ID.key()));
        String applicationName = cmd
                .getOptionValue(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME);
        String helixInstanceName = cmd
                .getOptionValue(GobblinClusterConfigurationKeys.HELIX_INSTANCE_NAME_OPTION_NAME);

        GobblinTaskRunner gobblinTaskRunner = new GobblinYarnTaskRunner(applicationName, helixInstanceName,
                containerId, ConfigFactory.load(), Optional.<Path>absent());
        gobblinTaskRunner.start();
    } catch (ParseException pe) {
        printUsage(options);
        System.exit(1);
    }
}

From source file:at.ac.tuwien.dsg.comot.m.adapter.Main.java

public static void main(String[] args) {

    Options options = createOptions();//  w  w w  . j  a  va  2s  . c  o m

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

        if (cmd.hasOption("mh") && cmd.hasOption("ih") && cmd.hasOption("ip")) {

            Integer infoPort = null;

            try {
                infoPort = new Integer(cmd.getOptionValue("ip"));
            } catch (NumberFormatException e) {
                LOG.warn("infoPort must be a number");
                showHelp(options);
            }

            AppContextAdapter.setBrokerHost(cmd.getOptionValue("mh"));
            AppContextAdapter.setInfoHost(cmd.getOptionValue("ih"));
            AppContextAdapter.setInfoPort(infoPort);

            context = new AnnotationConfigApplicationContext(AppContextAdapter.class);

            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    if (context != null) {
                        context.close();
                    }
                }
            });

            if (cmd.hasOption("m") || cmd.hasOption("r") || cmd.hasOption("s")) {

                Manager manager = context.getBean(EpsAdapterManager.class);
                String serviceId = getServiceInstanceId();
                String participantId = context.getBean(InfoClient.class).getOsuInstanceByServiceId(serviceId)
                        .getId();

                if (cmd.hasOption("m")) {

                    Monitoring processor = context.getBean(Monitoring.class);
                    manager.start(participantId, processor);

                } else if (cmd.hasOption("r")) {

                    Control processor = context.getBean(Control.class);
                    manager.start(participantId, processor);

                } else if (cmd.hasOption("s")) {

                    Deployment processor = context.getBean(Deployment.class);
                    manager.start(participantId, processor);
                }

            } else {
                LOG.warn("No adapter type specified");
                showHelp(options);
            }
        } else {
            LOG.warn("Required parameters were not specified.");
            showHelp(options);
        }
    } catch (Exception e) {
        LOG.error("{}", e);
        showHelp(options);
    }
}

From source file:gobblin.aws.GobblinAWSClusterManager.java

public static void main(String[] args) throws Exception {
    final Options options = buildOptions();
    try {/*from  www  .j a  va 2 s  .c om*/
        final CommandLine cmd = new DefaultParser().parse(options, args);
        if (!cmd.hasOption(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME)
                || !cmd.hasOption(GobblinAWSConfigurationKeys.APP_WORK_DIR)) {
            printUsage(options);
            System.exit(1);
        }

        Log4jConfigHelper.updateLog4jConfiguration(GobblinAWSClusterManager.class,
                GobblinAWSConfigurationKeys.GOBBLIN_AWS_LOG4J_CONFIGURATION_FILE);

        LOGGER.info(JvmUtils.getJvmInputArguments());

        // Note: Application id is required param for {@link GobblinClusterManager} super class
        // .. but has not meaning in AWS cluster context, so defaulting to a fixed value
        final String applicationId = "1";
        final String appWorkDir = cmd.getOptionValue(GobblinAWSConfigurationKeys.APP_WORK_DIR);

        try (GobblinAWSClusterManager clusterMaster = new GobblinAWSClusterManager(
                cmd.getOptionValue(GobblinClusterConfigurationKeys.APPLICATION_NAME_OPTION_NAME), applicationId,
                ConfigFactory.load(), Optional.of(new Path(appWorkDir)))) {

            clusterMaster.start();
        }
    } catch (ParseException pe) {
        printUsage(options);
        System.exit(1);
    }
}