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:microbiosima.Microbiosima.java

/**
 * @param args// w w w.j  a v  a 2 s .c  om
 *            the command line arguments
 * @throws java.io.FileNotFoundException
 * @throws java.io.UnsupportedEncodingException
 */
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
    //Init with default values
    int populationSize = 500;
    int microSize = 1000;
    int numberOfSpecies = 150;
    int numberOfGeneration = 10000;
    int numberOfObservation = 100;
    int numberOfReplication = 1;
    double pctEnv = 0;
    double pctPool = 0;

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option version = new Option("v", "version", false, "print the version information and exit");
    options.addOption(help);
    options.addOption(version);

    options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS")
            .desc("Number generation for observation [default: 100]").build());
    options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP")
            .desc("Number of replication [default: 1]").build());

    Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen")
            .desc("Four Parameters in the following orders: "
                    + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation"
                    + " [default: 500 1000 150 10000]");
    options.addOption(C.build());

    HelpFormatter formatter = new HelpFormatter();
    String syntax = "microbiosima pctEnv pctPool";
    String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n"
            + "required arguments:\n" + "  pctEnv             Percentage of environmental acquisition\n"
            + "  pctPool            Percentage of pooled environmental component\n" + "\noptional arguments:\n";
    String footer = "\n";

    formatter.setWidth(80);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
        String[] pct_config = cmd.getArgs();

        if (cmd.hasOption("h") || args.length == 0) {
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(0);
        }
        if (cmd.hasOption("v")) {
            System.out.println("Microbiosima " + VERSION);
            System.exit(0);
        }
        if (pct_config.length != 2) {
            System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got "
                    + pct_config.length + ": " + Arrays.toString(pct_config));
            formatter.printHelp(syntax, header, options, footer, true);
            System.exit(3);
        } else {
            pctEnv = Double.parseDouble(pct_config[0]);
            pctPool = Double.parseDouble(pct_config[1]);
            if (pctEnv < 0 || pctEnv > 1) {
                System.out.println(
                        "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv="
                                + pctEnv + ")! EXIT");
                System.exit(3);
            }
            if (pctPool < 0 || pctPool > 1) {
                System.out.println(
                        "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool="
                                + pctPool + ")! EXIT");
                System.exit(3);
            }

        }
        if (cmd.hasOption("config")) {
            String[] configs = cmd.getOptionValues("config");
            populationSize = Integer.parseInt(configs[0]);
            microSize = Integer.parseInt(configs[1]);
            numberOfSpecies = Integer.parseInt(configs[2]);
            numberOfGeneration = Integer.parseInt(configs[3]);
        }
        if (cmd.hasOption("obs")) {
            numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs"));
        }
        if (cmd.hasOption("rep")) {
            numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep"));
        }

    } catch (ParseException e) {
        e.printStackTrace();
        System.exit(3);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize)
            .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ")
            .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration)
            .append("\n\tNumber generation for observation: ").append(numberOfObservation)
            .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n");
    System.out.println(sb.toString());

    //      System.exit(3);
    // LogNormalDistribution lgd=new LogNormalDistribution(0,1);
    // environment=lgd.sample(150);
    // double environment_sum=0;
    // for (int i=0;i<No;i++){
    // environment_sum+=environment[i];
    // }
    // for (int i=0;i<No;i++){
    // environment[i]/=environment_sum;
    // }

    double[] environment = new double[numberOfSpecies];
    for (int i = 0; i < numberOfSpecies; i++) {
        environment[i] = 1 / (double) numberOfSpecies;
    }

    for (int rep = 0; rep < numberOfReplication; rep++) {
        String prefix = "" + (rep + 1) + "_";
        String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt";

        System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix);
        try {

            PrintWriter file1 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix)));
            PrintWriter file2 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix)));
            PrintWriter file3 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix)));
            PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix)));
            PrintWriter file5 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix)));
            PrintWriter file6 = new PrintWriter(
                    new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix)));

            Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0,
                    0);

            while (population.getNumberOfGeneration() < numberOfGeneration) {
                population.sumSpecies();
                if (population.getNumberOfGeneration() % numberOfObservation == 0) {
                    file1.println(population.gammaDiversity(true));
                    file2.println(population.alphaDiversity(true));
                    file3.print(population.betaDiversity(true));
                    file3.print("\t");
                    file3.println(population.BrayCurtis(true));
                    file4.println(population.printOut());
                    file5.println(population.interGenerationDistance());
                    file6.println(population.environmentPopulationDistance());
                }
                population.getNextGen();
            }
            file1.close();
            file2.close();
            file3.close();
            file4.close();
            file5.close();
            file6.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:io.wcm.devops.conga.plugins.aem.tooling.crypto.cli.AemCryptoCli.java

/**
 * CLI entry point/* w w  w.j  a v a 2s .  co  m*/
 * @param args Command line arguments
 * @throws Exception Exception
 */
//CHECKSTYLE:OFF
public static void main(String[] args) throws Exception {
    //CHECKSTYLE:ON
    CommandLine commandLine = new DefaultParser().parse(CLI_OPTIONS, args, true);

    boolean generateCryptoKeys = commandLine.hasOption(CRYPTO_KEYS_GENERATE);
    boolean ansibleVaultEncrypt = commandLine.hasOption(CRYPTO_KEYS_ANSIBLE_VAULT_ENCRYPT);
    File targetDir = new File(commandLine.getOptionValue(TARGET, "target"));
    String ansibleVaultEncryptPath = commandLine.getOptionValue(ANSIBLE_VAULT_ENCRYPT);
    String ansibleVaultDecryptPath = commandLine.getOptionValue(ANSIBLE_VAULT_DECRYPT);

    if (generateCryptoKeys) {
        CryptoKeys.generate(targetDir, ansibleVaultEncrypt)
                .forEach(file -> System.out.println("Generated: " + file.getPath()));
        return;
    } else if (StringUtils.isNotBlank(ansibleVaultEncryptPath)) {
        AnsibleVault.encrypt(new File(ansibleVaultEncryptPath));
        return;
    } else if (StringUtils.isNotBlank(ansibleVaultDecryptPath)) {
        AnsibleVault.decrypt(new File(ansibleVaultDecryptPath));
        return;
    }

    // print usage help
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(150);
    formatter.printHelp("java -jar conga-aem-crypto-cli-<version>.jar <arguments>", CLI_OPTIONS);
}

From source file:cc.twittertools.search.api.RunQueriesThrift.java

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

    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(//from ww w  . j av a 2s  . c  o m
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    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(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)
            || !cmdline.hasOption(QUERIES_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueriesThrift.class.getName(), options);
        System.exit(-1);
    }

    String queryFile = cmdline.getOptionValue(QUERIES_OPTION);
    if (!new File(queryFile).exists()) {
        System.err.println("Error: " + queryFile + " doesn't exist!");
        System.exit(-1);
    }

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    TrecTopicSet topicsFile = TrecTopicSet.fromFile(new File(queryFile));

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

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

    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    for (cc.twittertools.search.TrecTopic query : topicsFile) {
        List<TResult> results = client.search(query.getQuery(), query.getQueryTweetTime(), numResults);
        int i = 1;
        Set<Long> tweetIds = new HashSet<Long>();
        for (TResult result : results) {
            if (!tweetIds.contains(result.id)) {
                tweetIds.add(result.id);
                out.println(
                        String.format("%s Q0 %d %d %f %s", query.getId(), result.id, i, result.rsv, runtag));
                if (verbose) {
                    out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
                }
                i++;
            }
        }
    }
    out.close();
}

From source file:de.topobyte.osm4j.pbf.executables.EntitySplit.java

public static void main(String[] args) throws IOException {
    // @formatter:off
    Options options = new Options();
    OptionHelper.add(options, OPTION_INPUT, true, false, "input file");
    OptionHelper.add(options, OPTION_OUTPUT_NODES, true, false, "the file to write nodes to");
    OptionHelper.add(options, OPTION_OUTPUT_WAYS, true, false, "the file to write ways to");
    OptionHelper.add(options, OPTION_OUTPUT_RELATIONS, true, false, "the file to write relations to");
    // @formatter:on

    CommandLine line = null;/*  w  ww  . ja  v  a  2s .com*/
    try {
        line = new GnuParser().parse(options, args);
    } catch (ParseException e) {
        System.out.println("unable to parse command line: " + e.getMessage());
        new HelpFormatter().printHelp(HELP_MESSAGE, options);
        System.exit(1);
    }

    if (line == null) {
        return;
    }

    InputStream in = null;
    if (line.hasOption(OPTION_INPUT)) {
        String inputPath = line.getOptionValue(OPTION_INPUT);
        File file = new File(inputPath);
        FileInputStream fis = new FileInputStream(file);
        in = new BufferedInputStream(fis);
    } else {
        in = new BufferedInputStream(System.in);
    }

    OutputStream outNodes = null, outWays = null, outRelations = null;
    if (line.hasOption(OPTION_OUTPUT_NODES)) {
        String path = line.getOptionValue(OPTION_OUTPUT_NODES);
        FileOutputStream fos = new FileOutputStream(path);
        outNodes = new BufferedOutputStream(fos);
    }
    if (line.hasOption(OPTION_OUTPUT_WAYS)) {
        String path = line.getOptionValue(OPTION_OUTPUT_WAYS);
        FileOutputStream fos = new FileOutputStream(path);
        outWays = new BufferedOutputStream(fos);
    }
    if (line.hasOption(OPTION_OUTPUT_RELATIONS)) {
        String path = line.getOptionValue(OPTION_OUTPUT_RELATIONS);
        FileOutputStream fos = new FileOutputStream(path);
        outRelations = new BufferedOutputStream(fos);
    }

    if (outNodes == null && outWays == null && outRelations == null) {
        System.out.println("You should specify an output for at least one entity");
        System.exit(1);
    }

    EntitySplit task = new EntitySplit(in, outNodes, outWays, outRelations);
    task.execute();
}

From source file:edu.ksu.cis.indus.xmlizer.JimpleXMLizerCLI.java

/**
 * The entry point to execute this xmlizer from command prompt.
 * /*from w ww  . j ava2s  . com*/
 * @param s is the command-line arguments.
 * @throws RuntimeException when jimple xmlization fails.
 * @pre s != null
 */
public static void main(final String[] s) {
    final Scene _scene = Scene.v();

    final Options _options = new Options();
    Option _o = new Option("d", "dump directory", true, "The directory in which to write the xml files.  "
            + "If unspecified, the xml output will be directed standard out.");
    _o.setArgs(1);
    _o.setArgName("path");
    _o.setOptionalArg(false);
    _options.addOption(_o);
    _o = new Option("h", "help", false, "Display message.");
    _options.addOption(_o);
    _o = new Option("p", "soot-classpath", true, "Prepend this to soot class path.");
    _o.setArgs(1);
    _o.setArgName("classpath");
    _o.setOptionalArg(false);
    _options.addOption(_o);

    final HelpFormatter _help = new HelpFormatter();

    try {
        final CommandLine _cl = (new BasicParser()).parse(_options, s);
        final String[] _args = _cl.getArgs();

        if (_cl.hasOption('h')) {
            final String _cmdLineSyn = "java " + JimpleXMLizerCLI.class.getName() + "<options> <class names>";
            _help.printHelp(_cmdLineSyn.length(), _cmdLineSyn, "", _options, "", true);
        } else {
            if (_args.length > 0) {
                if (_cl.hasOption('p')) {
                    _scene.setSootClassPath(
                            _cl.getOptionValue('p') + File.pathSeparator + _scene.getSootClassPath());
                }

                final NamedTag _tag = new NamedTag("JimpleXMLizer");

                for (int _i = 0; _i < _args.length; _i++) {
                    final SootClass _sc = _scene.loadClassAndSupport(_args[_i]);
                    _sc.addTag(_tag);
                }
                final IProcessingFilter _filter = new TagBasedProcessingFilter(_tag.getName());
                writeJimpleAsXML(new Environment(_scene), _cl.getOptionValue('d'), null,
                        new UniqueJimpleIDGenerator(), _filter);
            } else {
                System.out.println("No classes were specified.");
            }
        }
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        printUsage(_options);
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

From source file:com.example.dlp.Metadata.java

/** Retrieve infoTypes. */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    Option languageCodeOption = new Option("language", null, true, "BCP-47 language code");
    languageCodeOption.setRequired(false);
    options.addOption(languageCodeOption);

    Option categoryOption = new Option("category", null, true, "Category of info types to list.");
    categoryOption.setRequired(false);/*from w ww.  j a  v  a  2 s . co  m*/
    options.addOption(categoryOption);

    CommandLineParser parser = new DefaultParser();
    HelpFormatter formatter = new HelpFormatter();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(Metadata.class.getName(), options);
        System.exit(1);
        return;
    }
    String languageCode = cmd.getOptionValue(languageCodeOption.getOpt(), "en-US");
    if (cmd.hasOption(categoryOption.getOpt())) {
        String category = cmd.getOptionValue(categoryOption.getOpt());
        listInfoTypes(category, languageCode);
    } else {
        listRootCategories(languageCode);
    }
}

From source file:cc.twittertools.search.api.RunQueriesBaselineThrift.java

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

    options.addOption(OptionBuilder.withArgName("string").hasArg().withDescription("host").create(HOST_OPTION));
    options.addOption(OptionBuilder.withArgName("port").hasArg().withDescription("port").create(PORT_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(/*w  w w . j a  v  a  2 s .  c om*/
            OptionBuilder.withArgName("string").hasArg().withDescription("group id").create(GROUP_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("access token").create(TOKEN_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_OPTION));
    options.addOption(new Option(VERBOSE_OPTION, "print out complete document"));

    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(HOST_OPTION) || !cmdline.hasOption(PORT_OPTION)
            || !cmdline.hasOption(QUERIES_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueriesThrift.class.getName(), options);
        System.exit(-1);
    }

    String queryFile = cmdline.getOptionValue(QUERIES_OPTION);
    if (!new File(queryFile).exists()) {
        System.err.println("Error: " + queryFile + " doesn't exist!");
        System.exit(-1);
    }

    String runtag = cmdline.hasOption(RUNTAG_OPTION) ? cmdline.getOptionValue(RUNTAG_OPTION) : DEFAULT_RUNTAG;

    TrecTopicSet topicsFile = TrecTopicSet.fromFile(new File(queryFile));

    int numResults = 1000;
    try {
        if (cmdline.hasOption(NUM_RESULTS_OPTION)) {
            numResults = Integer.parseInt(cmdline.getOptionValue(NUM_RESULTS_OPTION));
        }
    } catch (NumberFormatException e) {
        System.err.println("Invalid " + NUM_RESULTS_OPTION + ": " + cmdline.getOptionValue(NUM_RESULTS_OPTION));
        System.exit(-1);
    }

    String group = cmdline.hasOption(GROUP_OPTION) ? cmdline.getOptionValue(GROUP_OPTION) : null;
    String token = cmdline.hasOption(TOKEN_OPTION) ? cmdline.getOptionValue(TOKEN_OPTION) : null;

    boolean verbose = cmdline.hasOption(VERBOSE_OPTION);

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

    TrecSearchThriftClient client = new TrecSearchThriftClient(cmdline.getOptionValue(HOST_OPTION),
            Integer.parseInt(cmdline.getOptionValue(PORT_OPTION)), group, token);

    for (cc.twittertools.search.TrecTopic query : topicsFile) {
        List<TResult> results = client.search(query.getQuery(), query.getQueryTweetTime(), numResults);

        SortedSet<TResultComparable> sortedResults = new TreeSet<TResultComparable>();
        for (TResult result : results) {
            // Throw away retweets.
            if (result.getRetweeted_status_id() == 0) {
                sortedResults.add(new TResultComparable(result));
            }
        }

        int i = 1;
        int dupliCount = 0;
        double rsvPrev = 0;
        for (TResultComparable sortedResult : sortedResults) {
            TResult result = sortedResult.getTResult();
            double rsvCurr = result.rsv;
            if (Math.abs(rsvCurr - rsvPrev) > 0.0000001) {
                dupliCount = 0;
            } else {
                dupliCount++;
                rsvCurr = rsvCurr - 0.000001 / numResults * dupliCount;
            }
            out.println(String.format("%s Q0 %d %d %." + (int) (6 + Math.ceil(Math.log10(numResults))) + "f %s",
                    query.getId(), result.id, i, rsvCurr, runtag));
            if (verbose) {
                out.println("# " + result.toString().replaceAll("[\\n\\r]+", " "));
            }
            i++;
            rsvPrev = result.rsv;
        }

    }
    out.close();
}

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

/**
 * language maindir query temp_query/*from  w  w w.  j a  va2  s .  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.google.oacurl.Fetch.java

public static void main(String[] args) throws Exception {
    FetchOptions options = new FetchOptions();
    CommandLine line = options.parse(args);
    args = line.getArgs();//from ww w  .  j a  v  a 2  s .  c  o m

    if (options.isHelp()) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(0);
    }

    if (args.length != 1) {
        new HelpFormatter().printHelp("url", options.getOptions());
        System.exit(-1);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isVerbose()) {
        LoggingConfig.enableWireLog();
    }

    String url = args[0];

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao();
    AccessorDao accessorDao = new AccessorDao();

    Properties loginProperties = null;
    try {
        loginProperties = new PropertiesProvider(options.getLoginFileName()).get();
    } catch (FileNotFoundException e) {
        System.err.println(".oacurl.properties file not found in homedir");
        System.err.println("Make sure you've run oacurl-login first!");
        System.exit(-1);
    }

    OAuthServiceProvider serviceProvider = serviceProviderDao.nullServiceProvider();
    OAuthConsumer consumer = consumerDao.loadConsumer(loginProperties, serviceProvider);
    OAuthAccessor accessor = accessorDao.loadAccessor(loginProperties, consumer);

    OAuthClient client = new OAuthClient(new HttpClient4(SingleClient.HTTP_CLIENT_POOL));

    OAuthVersion version = (loginProperties.containsKey("oauthVersion"))
            ? OAuthVersion.valueOf(loginProperties.getProperty("oauthVersion"))
            : OAuthVersion.V1;

    OAuthEngine engine;
    switch (version) {
    case V1:
        engine = new V1OAuthEngine();
        break;
    case V2:
        engine = new V2OAuthEngine();
        break;
    case WRAP:
        engine = new WrapOAuthEngine();
        break;
    default:
        throw new IllegalArgumentException("Unknown version: " + version);
    }

    try {
        OAuthMessage request;

        List<Entry<String, String>> related = options.getRelated();

        Method method = options.getMethod();
        if (method == Method.POST || method == Method.PUT) {
            InputStream bodyStream;
            if (related != null) {
                bodyStream = new MultipartRelatedInputStream(related);
            } else if (options.getFile() != null) {
                bodyStream = new FileInputStream(options.getFile());
            } else {
                bodyStream = System.in;
            }
            request = newRequestMessage(accessor, method, url, bodyStream, engine);
            request.getHeaders().add(new OAuth.Parameter("Content-Type", options.getContentType()));
        } else {
            request = newRequestMessage(accessor, method, url, null, engine);
        }

        List<Parameter> headers = options.getHeaders();
        addHeadersToRequest(request, headers);

        HttpResponseMessage httpResponse;
        if (version == OAuthVersion.V1) {
            OAuthResponseMessage response;
            response = client.access(request, ParameterStyle.AUTHORIZATION_HEADER);
            httpResponse = response.getHttpResponse();
        } else {
            HttpMessage httpRequest = new HttpMessage(request.method, new URL(request.URL),
                    request.getBodyAsStream());
            httpRequest.headers.addAll(request.getHeaders());
            httpResponse = client.getHttpClient().execute(httpRequest, client.getHttpParameters());
            httpResponse = HttpMessageDecoder.decode(httpResponse);
        }

        System.err.flush();

        if (options.isInclude()) {
            Map<String, Object> dump = new HashMap<String, Object>();
            httpResponse.dump(dump);
            System.out.print(dump.get(HttpMessage.RESPONSE));
        }

        // Dump the bytes in the response's encoding.
        InputStream bodyStream = httpResponse.getBody();
        byte[] buf = new byte[1024];
        int count;
        while ((count = bodyStream.read(buf)) > -1) {
            System.out.write(buf, 0, count);
        }
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    }
}

From source file:de.uni_koblenz.west.splendid.tools.NQuadSourceAggregator.java

public static void main(String[] args) {

    try {//from www  .  j a va  2 s  .co  m
        // parse the command line arguments
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(OPTIONS, args);

        // print help message
        if (cmd.hasOption("h") || cmd.hasOption("help")) {
            new HelpFormatter().printHelp(USAGE, OPTIONS);
            System.exit(0);
        }

        // get input files (from option -i or all remaining parameters)
        String[] inputFiles = cmd.getOptionValues("i");
        if (inputFiles == null)
            inputFiles = cmd.getArgs();
        if (inputFiles.length == 0) {
            System.out.println("need at least one input file.");
            new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE);
            System.exit(1);
        }
        String outputFile = cmd.getOptionValue("o");

        // process all input files
        new NQuadSourceAggregator().process(outputFile, inputFiles);

    } catch (ParseException exp) {
        // print parse error and display usage message
        System.out.println(exp.getMessage());
        new HelpFormatter().printUsage(new PrintWriter(System.out, true), 80, USAGE, OPTIONS);
    }
}