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

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

Introduction

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

Prototype

GnuParser

Source Link

Usage

From source file:cc.twittertools.corpus.demo.ReadStatuses.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input directory or file")
            .create(INPUT_OPTION));/* w  ww.j a v a2s.co  m*/
    options.addOption(VERBOSE_OPTION, false, "print logging output every 10000 tweets");
    options.addOption(DUMP_OPTION, false, "dump statuses");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ReadStatuses.class.getName(), options);
        System.exit(-1);
    }

    PrintStream out = new PrintStream(System.out, true, "UTF-8");

    StatusStream stream;
    // Figure out if we're reading from HTML SequenceFiles or JSON.
    File file = new File(cmdline.getOptionValue(INPUT_OPTION));
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    if (file.isDirectory()) {
        stream = new JsonStatusCorpusReader(file);
    } else {
        stream = new JsonStatusBlockReader(file);
    }

    int cnt = 0;
    Status status;
    while ((status = stream.next()) != null) {
        if (cmdline.hasOption(DUMP_OPTION)) {
            String text = status.getText();
            if (text != null) {
                text = text.replaceAll("\\s+", " ");
                text = text.replaceAll("\0", "");
            }
            out.println(String.format("%d\t%s\t%s\t%s", status.getId(), status.getScreenname(),
                    status.getCreatedAt(), text));
        }
        cnt++;
        if (cnt % 10000 == 0 && cmdline.hasOption(VERBOSE_OPTION)) {
            LOG.info(cnt + " statuses read");
        }
    }
    stream.close();
    LOG.info(String.format("Total of %s statuses read.", cnt));
}

From source file:com.medsavant.mailer.Mail.java

public static void main(String[] args) throws IOException {
    CommandLineParser parser = new GnuParser();
    Options ops = getOptions();/* w  w  w .  j a v  a 2 s.  c  o m*/
    try {
        // parse the command line arguments
        CommandLine line = parser.parse(ops, args);

        // print help
        if (line.hasOption('h') || line.getOptions().length == 0) {
            printHelp();
            return;
        }

        // parse args

        String email = null;
        String emailPass = null;
        String mailingList = null;
        String subject = null;
        String htmlFile = null;

        for (Option o : line.getOptions()) {
            switch (o.getOpt().charAt(0)) {
            case 's':
                subject = o.getValue();
                break;
            case 'e':
                htmlFile = o.getValue();
                break;
            case 'u':
                email = o.getValue();
                break;
            case 'p':
                emailPass = o.getValue();
                break;
            case 'l':
                mailingList = o.getValue();
                break;
            }
        }

        setMailCredentials(email, emailPass, host, port);

        String text = readFileIntoString(new File(htmlFile));

        sendEmail(mailingList, subject, text);

    } catch (org.apache.commons.cli.ParseException exp) {

        printHelp();
        // oops, something went wrong
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }
}

From source file:be.dnsbelgium.rdap.client.RDAPCLI.java

public static void main(String[] args) {

    LOGGER.debug("Create the command line parser");
    CommandLineParser parser = new GnuParser();

    LOGGER.debug("Create the options");
    Options options = new RDAPOptions(Locale.ENGLISH);

    try {//from  w w w  . j  av a 2 s  .c  o m
        LOGGER.debug("Parse the command line arguments");
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            printHelp(options);
            return;
        }

        if (line.getArgs().length == 0) {
            throw new IllegalArgumentException("You must provide a query");
        }
        String query = line.getArgs()[0];

        Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase())
                : guessQueryType(query);

        LOGGER.debug("Query: {}, Type: {}", query, type);

        try {
            SSLContextBuilder sslContextBuilder = SSLContexts.custom();
            if (line.hasOption(RDAPOptions.TRUSTSTORE)) {
                sslContextBuilder.loadTrustMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS)));
            }
            if (line.hasOption(RDAPOptions.KEYSTORE)) {
                sslContextBuilder.loadKeyMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)),
                                line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)),
                        line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray());
            }
            SSLContext sslContext = sslContextBuilder.build();

            final String url = line.getOptionValue(RDAPOptions.URL);
            final HttpHost host = Utils.httpHost(url);

            HashSet<Header> headers = new HashSet<Header>();
            headers.add(new BasicHeader("Accept-Language",
                    line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString())));
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext,
                            (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier()
                                    : new BrowserCompatHostnameVerifier())));

            if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) {
                BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                        new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME),
                                line.getOptionValue(RDAPOptions.PASSWORD)));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url);
            ObjectMapper mapper = new ObjectMapper();

            JsonNode json = null;
            switch (type) {
            case DOMAIN:
                json = rdapClient.getDomainAsJson(query);
                break;
            case ENTITY:
                json = rdapClient.getEntityAsJson(query);
                break;
            case AUTNUM:
                json = rdapClient.getAutNum(query);
                break;
            case IP:
                json = rdapClient.getIp(query);
                break;
            case NAMESERVER:
                json = rdapClient.getNameserver(query);
                break;
            }
            PrintWriter out = new PrintWriter(System.out, true);
            if (line.hasOption(RDAPOptions.RAW)) {
                mapper.writer().writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.PRETTY)) {
                mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.YAML)) {
                DumperOptions dumperOptions = new DumperOptions();
                dumperOptions.setPrettyFlow(true);
                dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                dumperOptions.setSplitLines(true);
                Yaml yaml = new Yaml(dumperOptions);
                Map data = mapper.convertValue(json, Map.class);
                yaml.dump(data, out);
            } else {
                mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json);
            }
            out.flush();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }
    } catch (org.apache.commons.cli.ParseException e) {
        printHelp(options);
        System.exit(-1);
    }
}

From source file:com.temenos.interaction.rimdsl.generator.launcher.Main.java

public static void main(String[] args) {
    // handle command line options
    final Options options = new Options();
    OptionBuilder.withArgName("src");
    OptionBuilder.withDescription("Model source");
    OptionBuilder.hasArg();/*w  ww. j ava 2s .  co m*/
    OptionBuilder.isRequired();
    OptionBuilder.withValueSeparator(' ');
    Option optSrc = OptionBuilder.create("src");

    OptionBuilder.withArgName("targetdir");
    OptionBuilder.withDescription("Generator target directory");
    OptionBuilder.hasArg();
    OptionBuilder.isRequired();
    OptionBuilder.withValueSeparator(' ');
    Option optTargetDir = OptionBuilder.create("targetdir");

    options.addOption(optSrc);
    options.addOption(optTargetDir);

    // create the command line parser
    final CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (final ParseException exp) {
        System.err.println("Parsing arguments failed.  Reason: " + exp);
        wrongCall(options);
        return;
    }

    // execute the generator
    Injector injector = new RIMDslStandaloneSetup().createInjectorAndDoEMFRegistration();
    Generator generator = injector.getInstance(Generator.class);
    File srcFile = new File(line.getOptionValue(optSrc.getArgName()));
    if (srcFile.exists()) {
        boolean result = false;
        if (srcFile.isDirectory()) {
            result = generator.runGeneratorDir(srcFile.getPath(),
                    line.getOptionValue(optTargetDir.getArgName()));
        } else {
            result = generator.runGenerator(srcFile.getPath(), line.getOptionValue(optTargetDir.getArgName()));
        }
        System.out.println("Code generation finished [" + result + "]");
    } else {
        System.out.println("Src dir not found.");
    }

}

From source file:com.opensearchserver.affinities.Main.java

public static void main(String[] args) throws IOException, ParseException {
    Logger.getLogger("").setLevel(Level.WARNING);
    Options options = new Options();
    options.addOption("h", "help", false, "print this message");
    options.addOption("d", "datadir", true, "Data directory");
    options.addOption("p", "port", true, "TCP port");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar target/oss-affinities.jar", options);
        return;//from   ww w . java2s  . c  o  m
    }
    int port = cmd.hasOption("p") ? Integer.parseInt(cmd.getOptionValue("p")) : 9092;

    File dataDir = new File(System.getProperty("user.home"), "opensearchserver_affinities");
    if (cmd.hasOption("d"))
        dataDir = new File(cmd.getOptionValue("d"));
    if (!dataDir.exists())
        throw new IOException("The data directory does not exists: " + dataDir);
    if (!dataDir.isDirectory())
        throw new IOException("The data directory path is not a directory: " + dataDir);
    AffinityList.load(dataDir);

    UndertowJaxrsServer server = new UndertowJaxrsServer()
            .start(Undertow.builder().addHttpListener(port, "0.0.0.0"));
    server.deploy(Main.class);
}

From source file:edu.gslis.ts.RunQuery.java

public static void main(String[] args) {
    try {// ww w .  ja v  a2 s. c  om
        // Get the commandline options
        Options options = createOptions();
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        String inputPath = cmd.getOptionValue("input");
        String eventsPath = cmd.getOptionValue("events");
        String stopPath = cmd.getOptionValue("stop");
        int queryId = Integer.valueOf(cmd.getOptionValue("query"));

        List<String> ids = FileUtils.readLines(new File(inputPath + File.separator + "ids.txt"));

        Stopper stopper = new Stopper(stopPath);
        Map<Integer, FeatureVector> queries = readEvents(eventsPath, stopper);

        FeatureVector query = queries.get(queryId);

        Pairtree ptree = new Pairtree();
        Bag<String> words = new HashBag<String>();

        for (String streamId : ids) {

            String ppath = ptree.mapToPPath(streamId.replace("-", ""));

            String inpath = inputPath + File.separator + ppath + File.separator + streamId + ".xz";
            //                System.out.println(inpath);
            File infile = new File(inpath);
            InputStream in = new XZInputStream(new FileInputStream(infile));

            TTransport inTransport = new TIOStreamTransport(new BufferedInputStream(in));
            TBinaryProtocol inProtocol = new TBinaryProtocol(inTransport);
            inTransport.open();
            final StreamItem item = new StreamItem();

            while (true) {
                try {
                    item.read(inProtocol);
                    //                        System.out.println("Read " + item.stream_id);

                } catch (TTransportException tte) {
                    // END_OF_FILE is used to indicate EOF and is not an exception.
                    if (tte.getType() != TTransportException.END_OF_FILE)
                        tte.printStackTrace();
                    break;
                }
            }

            // Do something with this document...
            String docText = item.getBody().getClean_visible();

            StringTokenizer itr = new StringTokenizer(docText);
            while (itr.hasMoreTokens()) {
                words.add(itr.nextToken());
            }

            inTransport.close();

        }

        for (String term : words.uniqueSet()) {
            System.out.println(term + ":" + words.getCount(term));
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cc.twittertools.util.VerifySubcollection.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(// w  w  w  .j  av a2 s .c  o m
            OptionBuilder.withArgName("file").hasArg().withDescription("list of tweetids").create(ID_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(COLLECTION_OPTION) || !cmdline.hasOption(ID_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ExtractSubcollection.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    LongOpenHashSet tweetids = new LongOpenHashSet();
    File tweetidsFile = new File(cmdline.getOptionValue(ID_OPTION));
    if (!tweetidsFile.exists()) {
        System.err.println("Error: " + tweetidsFile + " does not exist!");
        System.exit(-1);
    }
    LOG.info("Reading tweetids from " + tweetidsFile);

    FileInputStream fin = new FileInputStream(tweetidsFile);
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));

    String s;
    while ((s = br.readLine()) != null) {
        tweetids.add(Long.parseLong(s));
    }
    br.close();
    fin.close();
    LOG.info("Read " + tweetids.size() + " tweetids.");

    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    LongOpenHashSet seen = new LongOpenHashSet();
    TreeMap<Long, String> tweets = Maps.newTreeMap();

    PrintStream out = new PrintStream(System.out, true, "UTF-8");
    StatusStream stream = new JsonStatusCorpusReader(file);
    Status status;
    int cnt = 0;
    while ((status = stream.next()) != null) {
        if (!tweetids.contains(status.getId())) {
            LOG.error("tweetid " + status.getId() + " doesn't belong in collection");
            continue;
        }
        if (seen.contains(status.getId())) {
            LOG.error("tweetid " + status.getId() + " already seen!");
            continue;
        }

        tweets.put(status.getId(), status.getJsonObject().toString());
        seen.add(status.getId());
        cnt++;
    }
    LOG.info("total of " + cnt + " tweets in subcollection.");

    for (Map.Entry<Long, String> entry : tweets.entrySet()) {
        out.println(entry.getValue());
    }

    stream.close();
    out.close();
}

From source file:com.servioticy.dispatcher.DispatcherTopology.java

/**
 * @param args/*from   w  w  w . j a  v a2s. c o m*/
 * @throws InvalidTopologyException
 * @throws AlreadyAliveException
 * @throws InterruptedException
 */
public static void main(String[] args)
        throws AlreadyAliveException, InvalidTopologyException, InterruptedException, ParseException {

    Options options = new Options();

    options.addOption(
            OptionBuilder.withArgName("file").hasArg().withDescription("Config file path.").create("f"));
    options.addOption(OptionBuilder.withArgName("topology").hasArg()
            .withDescription("Name of the topology in storm. If no name is given it will run in local mode.")
            .create("t"));
    options.addOption(OptionBuilder.withDescription("Enable debugging").create("d"));

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

    String path = null;
    if (cmd.hasOption("f")) {
        path = cmd.getOptionValue("f");
    }

    DispatcherContext dc = new DispatcherContext();
    dc.loadConf(path);

    TopologyBuilder builder = new TopologyBuilder();

    // TODO Auto-assign workers to the spout in function of the number of Kestrel IPs
    builder.setSpout("updates", new KestrelThriftSpout(Arrays.asList(dc.updatesAddresses), dc.updatesPort,
            dc.updatesQueue, new UpdateDescriptorScheme()));
    builder.setSpout("actions", new KestrelThriftSpout(Arrays.asList(dc.actionsAddresses), dc.actionsPort,
            dc.actionsQueue, new ActuationScheme()));

    builder.setBolt("prepare", new PrepareBolt(dc)).shuffleGrouping("updates");

    builder.setBolt("actuationdispatcher", new ActuationDispatcherBolt(dc)).shuffleGrouping("actions");

    builder.setBolt("subretriever", new SubscriptionRetrieveBolt(dc)).shuffleGrouping("prepare",
            "subscription");

    builder.setBolt("externaldispatcher", new ExternalDispatcherBolt(dc)).fieldsGrouping("subretriever",
            "externalSub", new Fields("subid"));
    builder.setBolt("internaldispatcher", new InternalDispatcherBolt(dc)).fieldsGrouping("subretriever",
            "internalSub", new Fields("subid"));

    builder.setBolt("streamdispatcher", new StreamDispatcherBolt(dc))
            .shuffleGrouping("subretriever", "streamSub").shuffleGrouping("prepare", "stream");
    builder.setBolt("streamprocessor", new StreamProcessorBolt(dc)).shuffleGrouping("streamdispatcher",
            "default");

    if (dc.benchmark) {
        builder.setBolt("benchmark", new BenchmarkBolt(dc)).shuffleGrouping("streamdispatcher", "benchmark")
                .shuffleGrouping("subretriever", "benchmark").shuffleGrouping("streamprocessor", "benchmark")
                .shuffleGrouping("prepare", "benchmark");
    }

    Config conf = new Config();
    conf.setDebug(cmd.hasOption("d"));
    if (cmd.hasOption("t")) {
        StormSubmitter.submitTopology(cmd.getOptionValue("t"), conf, builder.createTopology());
    } else {
        conf.setMaxTaskParallelism(4);
        LocalCluster cluster = new LocalCluster();
        cluster.submitTopology("dispatcher", conf, builder.createTopology());

    }

}

From source file:edu.washington.data.sentimentreebank.StanfordNLPDict.java

public static void main(String args[]) {
    Options options = new Options();
    options.addOption("d", "dict", true, "dictionary file.");
    options.addOption("s", "sentiment", true, "sentiment value file.");

    CommandLineParser parser = new GnuParser();
    try {/*from   ww  w  .  j  a  v  a 2s.com*/
        CommandLine line = parser.parse(options, args);
        if (!line.hasOption("dict") && !line.hasOption("sentiment")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("StanfordNLPDict", options);
            return;
        }

        Path dictPath = Paths.get(line.getOptionValue("dict"));
        Path sentimentPath = Paths.get(line.getOptionValue("sentiment"));

        StanfordNLPDict snlp = new StanfordNLPDict(dictPath, sentimentPath);
        String sentence = "take off";
        System.out.printf("sentence [%1$s] %2$s\n", sentence,
                String.valueOf(snlp.getPhraseSentiment(sentence)));

    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("StanfordNLPDict", options);
    } catch (IOException ex) {
        Logger.getLogger(StanfordNLPDict.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.temenos.interaction.rimdsl.generator.launcher.MainSpringPRD.java

public static void main(String[] args) {
    // handle command line options
    final Options options = new Options();
    OptionBuilder.withArgName("src");
    OptionBuilder.withDescription("Model source");
    OptionBuilder.hasArg();/*from w  ww. java 2  s .  c o m*/
    OptionBuilder.isRequired();
    OptionBuilder.withValueSeparator(' ');
    Option optSrc = OptionBuilder.create("src");

    OptionBuilder.withArgName("targetdir");
    OptionBuilder.withDescription("Generator target directory");
    OptionBuilder.hasArg();
    OptionBuilder.isRequired();
    OptionBuilder.withValueSeparator(' ');
    Option optTargetDir = OptionBuilder.create("targetdir");

    options.addOption(optSrc);
    options.addOption(optTargetDir);

    // create the command line parser
    final CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (final ParseException exp) {
        System.err.println("Parsing arguments failed.  Reason: " + exp);
        wrongCall(options);
        return;
    }

    // execute the generator
    Injector injector = new RIMDslStandaloneSetupSpringPRD().createInjectorAndDoEMFRegistration();
    Generator generator = injector.getInstance(Generator.class);
    File srcFile = new File(line.getOptionValue(optSrc.getArgName()));
    if (srcFile.exists()) {
        boolean result = false;
        if (srcFile.isDirectory()) {
            result = generator.runGeneratorDir(srcFile.getPath(),
                    line.getOptionValue(optTargetDir.getArgName()));
        } else {
            result = generator.runGenerator(srcFile.getPath(), line.getOptionValue(optTargetDir.getArgName()));
        }
        System.out.println("Code generation finished [" + result + "]");
    } else {
        System.out.println("Src dir not found.");
    }

}