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

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

Introduction

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

Prototype

public void printHelp(String cmdLineSyntax, Options options) 

Source Link

Document

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

Usage

From source file:com.fiveclouds.jasper.JasperRunner.java

public static void main(String[] args) {

    // Set-up the options for the utility
    Options options = new Options();
    Option report = new Option("report", true, "jasper report to run (i.e. /path/to/report.jrxml)");
    options.addOption(report);// w w  w. j  a  v  a  2  s. co m

    Option driver = new Option("driver", true, "the jdbc driver class (i.e. com.mysql.jdbc.Driver)");
    driver.setRequired(true);
    options.addOption(driver);

    options.addOption("jdbcurl", true, "database jdbc url (i.e. jdbc:mysql://localhost:3306/database)");
    options.addOption("excel", true, "Will override the PDF default and export to Microsoft Excel");
    options.addOption("username", true, "database username");
    options.addOption("password", true, "database password");
    options.addOption("output", true, "the output filename (i.e. path/to/report.pdf");
    options.addOption("help", false, "print this message");

    Option propertyOption = OptionBuilder.withArgName("property=value").hasArgs(2).withValueSeparator()
            .withDescription("use value as report property").create("D");

    options.addOption(propertyOption);

    // Parse the options and build the report
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("help")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("jasper-runner", options);
        } else {

            System.out.println("Building report " + cmd.getOptionValue("report"));
            try {
                Class.forName(cmd.getOptionValue("driver"));
                Connection connection = DriverManager.getConnection(cmd.getOptionValue("jdbcurl"),
                        cmd.getOptionValue("username"), cmd.getOptionValue("password"));
                System.out.println("Connected to " + cmd.getOptionValue("jdbcurl"));
                JasperReport jasperReport = JasperCompileManager.compileReport(cmd.getOptionValue("report"));

                JRPdfExporter pdfExporter = new JRPdfExporter();

                Properties properties = cmd.getOptionProperties("D");
                Map<String, Object> parameters = new HashMap<String, Object>();

                Map<String, JRParameter> reportParameters = new HashMap<String, JRParameter>();

                for (JRParameter param : jasperReport.getParameters()) {
                    reportParameters.put(param.getName(), param);
                }

                for (Object propertyKey : properties.keySet()) {
                    String parameterName = String.valueOf(propertyKey);
                    String parameterValue = String.valueOf(properties.get(propertyKey));
                    JRParameter reportParam = reportParameters.get(parameterName);

                    if (reportParam != null) {
                        if (reportParam.getValueClass().equals(String.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to String = " + parameterValue);
                            parameters.put(parameterName, parameterValue);
                        } else if (reportParam.getValueClass().equals(Integer.class)) {
                            System.out.println(
                                    "Property " + parameterName + " set to Integer = " + parameterValue);
                            parameters.put(parameterName, Integer.parseInt(parameterValue));
                        } else {
                            System.err.print("Unsupported type for property " + parameterName);
                            System.exit(1);

                        }
                    } else {
                        System.out.println("Property " + parameterName + " not found in the report! IGNORING");

                    }
                }

                JasperPrint print = JasperFillManager.fillReport(jasperReport, parameters, connection);

                pdfExporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
                pdfExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, cmd.getOptionValue("output"));
                System.out.println("Exporting report to " + cmd.getOptionValue("output"));
                pdfExporter.exportReport();
            } catch (JRException e) {
                System.err.print("Unable to parse report file (" + cmd.getOptionValue("r") + ")");
                e.printStackTrace();
                System.exit(1);
            } catch (ClassNotFoundException e) {
                System.err.print("Unable to find the database driver,  is it on the classpath?");
                e.printStackTrace();
                System.exit(1);
            } catch (SQLException e) {
                System.err.print("An SQL exception has occurred (" + e.getMessage() + ")");
                e.printStackTrace();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.print("Unable to parse command line options (" + e.getMessage() + ")");
        System.exit(1);
    }
}

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramRelativeFrequencyJson.java

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

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;/*from  w w w  . j a v a 2  s.  c o m*/
    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)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramRelativeFrequencyJson.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);

    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> pairs = SequenceFileUtils
            .readDirectory(new Path(inputPath));

    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list1 = Lists.newArrayList();
    List<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> list2 = Lists.newArrayList();

    for (PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p : pairs) {
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();

        if (bigram.getJsonObject().get("Left").getAsString().equals("light")) {
            list1.add(p);
        }

        if (bigram.getJsonObject().get("Left").getAsString().equals("contain")) {
            list2.add(p);
        }
    }

    Collections.sort(list1,
            new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() {
                public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1,
                        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) {
                    if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                        return e1.getLeftElement().compareTo(e2.getLeftElement());
                    }

                    return e2.getRightElement().compareTo(e1.getRightElement());
                }
            });

    Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter1 = Iterators
            .limit(list1.iterator(), 10);
    while (iter1.hasNext()) {
        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter1.next();
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }

    Collections.sort(list2,
            new Comparator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>>() {
                public int compare(PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e1,
                        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> e2) {
                    if (e1.getRightElement().compareTo(e2.getRightElement()) == 0) {
                        return e1.getLeftElement().compareTo(e2.getLeftElement());
                    }

                    return e2.getRightElement().compareTo(e1.getRightElement());
                }
            });

    Iterator<PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable>> iter2 = Iterators
            .limit(list2.iterator(), 10);
    while (iter2.hasNext()) {
        PairOfWritables<BigramRelativeFrequencyJson.MyTuple, FloatWritable> p = iter2.next();
        BigramRelativeFrequencyJson.MyTuple bigram = p.getLeftElement();
        System.out.println(bigram + "\t" + p.getRightElement());
    }
}

From source file:io.scigraph.owlapi.loader.BatchOwlLoader.java

public static void main(String[] args) throws Exception {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;/* w  w  w  .j  av  a  2s.c  o  m*/
    try {
        cmd = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(BatchOwlLoader.class.getSimpleName(), getOptions());
        System.exit(-1);
    }

    OwlLoadConfigurationLoader owlLoadConfigurationLoader = new OwlLoadConfigurationLoader(
            new File(cmd.getOptionValue('c').trim()));
    OwlLoadConfiguration config = owlLoadConfigurationLoader.loadConfig();
    load(config);
    // TODO: Is Guice causing this to hang? #44
    System.exit(0);
}

From source file:com.asksunny.tool.RemoteDataStreamer.java

/**
 * @param args//from  w ww  .ja  v  a 2s  . c  om
 */
public static void main(String[] args) throws Exception {
    RemoteDataStreamer streamer = new RemoteDataStreamer();
    Options options = CLIOptionAnnotationBasedBinder.getOptions(streamer);
    CLIOptionAnnotationBasedBinder.bindPosix(options, args, streamer);

    if (streamer.isHelp() || streamer.isVersion() || streamer.getFilePath() == null) {
        HelpFormatter hfmt = new HelpFormatter();
        if (streamer.isHelp()) {
            hfmt.printHelp(streamer.getClass().getName() + " <options>", options);
            System.exit(0);
        } else if (streamer.isVersion()) {
            System.out.println(VERSION);
            System.exit(0);
        } else {
            hfmt.printHelp(streamer.getClass().getName() + " <options>", options);
            System.exit(1);
        }
    }
    File f = new File(streamer.getFilePath());
    boolean sender = f.exists() && f.isFile();
    if (sender && streamer.getHost() == null) {
        System.err.println("Host option is required for sender");
        HelpFormatter hfmt = new HelpFormatter();
        hfmt.printHelp(streamer.getClass().getName() + " <options>", options);
        System.exit(1);
    }

    if (sender && streamer.isCompress()) {
        streamer.sendCompress();
    } else if (sender && !streamer.isCompress()) {
        streamer.send();
    } else if (!sender && streamer.isCompress()) {
        streamer.receiveCompress();
    } else {
        streamer.receive();
    }

    System.out.printf("File %s transfer complete.", streamer.getFilePath());

}

From source file:com.redhat.akashche.wixgen.cli.Launcher.java

public static void main(String[] args) throws Exception {
    try {/*from   w  ww  . jav  a 2s . c o m*/
        CommandLine cline = new GnuParser().parse(OPTIONS, args);
        if (cline.hasOption(VERSION_OPTION)) {
            out.println(VERSION);
        } else if (cline.hasOption(HELP_OPTION)) {
            throw new ParseException("Printing help page:");
        } else if (1 == cline.getArgs().length && cline.hasOption(CONFIG_OPTION)
                && cline.hasOption(OUTPUT_OPTION) && !cline.hasOption(XSL_OPTION)) {
            WixConfig conf = parseConf(cline.getOptionValue(CONFIG_OPTION));
            Wix wix = new DirectoryGenerator().createFromDir(new File(cline.getArgs()[0]), conf);
            Marshaller marshaller = createMarshaller();
            writeXml(marshaller, wix, cline.getOptionValue(OUTPUT_OPTION), false);
            if (cline.hasOption(DIRECTORY_OPTION)) {
                Directory dir = findWixDirectory(wix);
                writeXml(marshaller, dir, cline.getOptionValue(DIRECTORY_OPTION), true);
            }
            if (cline.hasOption(FEATURE_OPTION)) {
                Feature feature = findWixFeature(wix);
                writeXml(marshaller, feature, cline.getOptionValue(FEATURE_OPTION), true);
            }
        } else if (1 == cline.getArgs().length && cline.hasOption(XSL_OPTION)
                && cline.hasOption(OUTPUT_OPTION)) {
            transformWithXsl(cline.getArgs()[0], cline.getOptionValue(XSL_OPTION),
                    cline.getOptionValue(OUTPUT_OPTION));
        } else {
            throw new ParseException("Incorrect arguments received!");
        }
    } catch (ParseException e) {
        HelpFormatter formatter = new HelpFormatter();
        out.println(e.getMessage());
        out.println(VERSION);
        formatter.printHelp("java -jar wixgen.jar input_dir -c config.json -o output.wxs", OPTIONS);
    }
}

From source file:com.yahoo.pasc.paxos.server.PaxosServer.java

/**
 * @param args//w w  w.j  a  v  a 2 s  .co  m
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws IOException 
 * @throws MalformedURLException
 */
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IOException {

    CommandLineParser parser = new PosixParser();
    Options options;

    {
        Option id = new Option("i", true, "client id");
        Option port = new Option("p", true, "port used by server");
        Option buffer = new Option("b", true, "number of batched messages");
        //            Option clients      = new Option("c", true, "clients (hostname:port,...)");
        Option servers = new Option("s", true, "servers (hostname:port,...)");
        Option maxInstances = new Option("m", true, "max number of instances");
        Option anm = new Option("a", false, "protection against ANM faults");
        Option udp = new Option("u", false, "use UDP");
        Option cWindow = new Option("w", true, "congestion window");
        Option threads = new Option("t", true, "number of threads");
        Option digests = new Option("d", true, "max digests");
        Option ckPeriod = new Option("k", true, "checkpointing period");
        Option inlineThresh = new Option("n", true, "threshold for sending requests iNline with accepts ");
        Option twoStages = new Option("2", false, "2 stages");
        Option digestQuorum = new Option("q", true, "digest quorum");
        Option leaderReplies = new Option("r", false, "leader replies");
        Option zookeeper = new Option("z", true, "zookeeper connection string");

        options = new Options();
        options.addOption(id).addOption(port).addOption(buffer).addOption(servers).addOption(threads)
                .addOption(anm).addOption(udp).addOption(maxInstances) //.addOption(leader)
                .addOption(cWindow).addOption(digests).addOption(ckPeriod).addOption(inlineThresh)
                .addOption(twoStages).addOption(digestQuorum).addOption(leaderReplies).addOption(zookeeper);
    }

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

        String serverAddresses[] = line.hasOption('s') ? line.getOptionValue('s').split(",")
                : new String[] { "10.78.36.104:20548", "10.78.36.104:20748" };
        //            String clientAddresses[] = line.hasOption('c') ? line.getOptionValue('c').split(",") : new String[] { "localhost:9000" };
        String zookeeper = line.hasOption('z') ? line.getOptionValue('z') : "localhost:2181";
        int serverId = line.hasOption('i') ? Integer.parseInt(line.getOptionValue('i')) : 0;
        int batchSize = line.hasOption('b') ? Integer.parseInt(line.getOptionValue('b')) : 1;
        int port = line.hasOption('p') ? Integer.parseInt(line.getOptionValue('p')) : 20548;
        int maxInstances = line.hasOption('m') ? Integer.parseInt(line.getOptionValue('m')) : 16 * 1024;
        int congestionWindow = line.hasOption('w') ? Integer.parseInt(line.getOptionValue('w')) : 1;
        int digests = line.hasOption('d') ? Integer.parseInt(line.getOptionValue('d')) : 16;
        int inlineThreshold = line.hasOption('n') ? Integer.parseInt(line.getOptionValue('n')) : 1000;
        boolean protection = line.hasOption('a');
        boolean udp = line.hasOption('u');
        boolean twoStages = line.hasOption('2');
        int quorum = serverAddresses.length / 2 + 1;
        int digestQuorum = line.hasOption('q') ? Integer.parseInt(line.getOptionValue('q')) : quorum;
        int threads = line.hasOption('t') ? Integer.parseInt(line.getOptionValue('t'))
                : Runtime.getRuntime().availableProcessors() * 2 + 1;

        if (batchSize <= 0) {
            throw new RuntimeException("BatchSize must be greater than 0");
        }

        PaxosState state = new PaxosState(maxInstances, batchSize, serverId, quorum, digestQuorum,
                serverAddresses.length, congestionWindow, digests);
        if (line.hasOption('k'))
            state.setCheckpointPeriod(Integer.parseInt(line.getOptionValue('k')));
        if (line.hasOption('r'))
            state.setLeaderReplies(true);
        state.setRequestThreshold(inlineThreshold);

        if (!protection) {
            System.out.println("PANM disabled!");
        }

        final PascRuntime<PaxosState> runtime = new PascRuntime<PaxosState>(protection);
        runtime.setState(state);
        runtime.addHandler(Accept.class, new AcceptorAccept());
        runtime.addHandler(Prepare.class, new AcceptorPrepare());
        runtime.addHandler(Accepted.class, new Learner());
        runtime.addHandler(Prepared.class, new ProposerPrepared());
        runtime.addHandler(Request.class, new ProposerRequest());
        runtime.addHandler(InlineRequest.class, new ProposerRequest());
        runtime.addHandler(Digest.class, new DigestHandler());
        runtime.addHandler(PreReply.class, new LearnerPreReply());
        runtime.addHandler(Leader.class, new LeadershipHandler());

        if (udp) {
            new UdpServer(runtime, serverAddresses, null, port, threads, serverId).run();
        } else {
            new TcpServer(runtime, new EmptyStateMachine(), null, zookeeper, serverAddresses, port, threads,
                    serverId, twoStages).run();
        }
    } catch (Exception e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Paxos", options);

        System.err.println("Unexpected exception: " + e);
        e.printStackTrace();

        System.exit(-1);
    }
}

From source file:javadepchecker.Main.java

/**
 * @param args the command line arguments
 *//*from   ww  w . j  av  a2s.  c  o  m*/
public static void main(String[] args) throws IOException {
    int exit = 0;
    try {
        CommandLineParser parser = new PosixParser();
        Options options = new Options();
        options.addOption("h", "help", false, "print help");
        options.addOption("i", "image", true, "image directory");
        options.addOption("v", "verbose", false, "print verbose output");
        CommandLine line = parser.parse(options, args);
        String[] files = line.getArgs();
        if (line.hasOption("h") || files.length == 0) {
            HelpFormatter h = new HelpFormatter();
            h.printHelp("java-dep-check [-i <image] <package.env>+", options);
        } else {
            image = line.getOptionValue("i", "");

            for (String arg : files) {
                if (line.hasOption('v'))
                    System.out.println("Checking " + arg);
                if (!checkPkg(new File(arg))) {
                    exit = 1;
                }
            }
        }
    } catch (ParseException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.exit(exit);
}

From source file:io.anserini.search.SearchTweets.java

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

    options.addOption(new Option(RM3_OPTION, "apply relevance feedback with rm3"));

    options.addOption(//ww w .j  a va2s  . co  m
            OptionBuilder.withArgName("path").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("num").hasArg().withDescription("number of results to return")
            .create(NUM_RESULTS_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("file containing topics in TREC format").create(QUERIES_OPTION));
    options.addOption(OptionBuilder.withArgName("similarity").hasArg()
            .withDescription("similarity to use (BM25, LM)").create(SIMILARITY_OPTION));
    options.addOption(
            OptionBuilder.withArgName("string").hasArg().withDescription("runtag").create(RUNTAG_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(QUERIES_OPTION) || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SearchTweets.class.getName(), options);
        System.exit(-1);
    }

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

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

    String topicsFile = cmdline.getOptionValue(QUERIES_OPTION);

    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 similarity = "LM";
    if (cmdline.hasOption(SIMILARITY_OPTION)) {
        similarity = cmdline.getOptionValue(SIMILARITY_OPTION);
    }

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

    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexLocation.getAbsolutePath())));
    IndexSearcher searcher = new IndexSearcher(reader);

    if (similarity.equalsIgnoreCase("BM25")) {
        searcher.setSimilarity(new BM25Similarity());
    } else if (similarity.equalsIgnoreCase("LM")) {
        searcher.setSimilarity(new LMDirichletSimilarity(2500.0f));
    }

    MicroblogTopicSet topics = MicroblogTopicSet.fromFile(new File(topicsFile));
    for (MicroblogTopic topic : topics) {
        Filter filter = NumericRangeFilter.newLongRange(StatusField.ID.name, 0L, topic.getQueryTweetTime(),
                true, true);
        Query query = AnalyzerUtils.buildBagOfWordsQuery(StatusField.TEXT.name, IndexTweets.ANALYZER,
                topic.getQuery());

        TopDocs rs = searcher.search(query, filter, numResults);

        RerankerContext context = new RerankerContext(searcher, query, topic.getQuery(), filter);
        RerankerCascade cascade = new RerankerCascade(context);

        if (cmdline.hasOption(RM3_OPTION)) {
            cascade.add(new Rm3Reranker(IndexTweets.ANALYZER, StatusField.TEXT.name));
            cascade.add(new RemoveRetweetsTemporalTiebreakReranker());
        } else {
            cascade.add(new RemoveRetweetsTemporalTiebreakReranker());
        }

        ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher));

        for (int i = 0; i < docs.documents.length; i++) {
            String qid = topic.getId().replaceFirst("^MB0*", "");
            out.println(String.format("%s Q0 %s %d %f %s", qid,
                    docs.documents[i].getField(StatusField.ID.name).numericValue(), (i + 1), docs.scores[i],
                    runtag));
        }
    }
    reader.close();
    out.close();
}

From source file:com.github.zk1931.pulsefs.Main.java

public static void main(String[] args) throws Exception {
    // Options for command arguments.
    Options options = new Options();

    Option port = OptionBuilder.withArgName("port").hasArg(true).isRequired(true).withDescription("port number")
            .create("port");

    Option addr = OptionBuilder.withArgName("addr").hasArg(true).withDescription("addr (ip:port) for Zab.")
            .create("addr");

    Option join = OptionBuilder.withArgName("join").hasArg(true).withDescription("the addr of server to join.")
            .create("join");

    Option dir = OptionBuilder.withArgName("dir").hasArg(true).withDescription("the directory for logs.")
            .create("dir");

    Option help = OptionBuilder.withArgName("h").hasArg(false).withLongOpt("help")
            .withDescription("print out usages.").create("h");

    Option timeout = OptionBuilder.withArgName("timeout").hasArg(true)
            .withDescription("session timeout(seconds)").create("timeout");

    options.addOption(port).addOption(addr).addOption(join).addOption(dir).addOption(timeout).addOption(help);

    CommandLineParser parser = new BasicParser();
    CommandLine cmd;//from  ww  w  .  ja v a  2 s . c o m
    String usage = "./bin/pulsefs -port port [Options]";
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(usage, options);
            return;
        }
    } catch (ParseException exp) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(usage, options);
        return;
    }

    PulseFSConfig config = new PulseFSConfig();

    if (cmd.hasOption("addr")) {
        config.setServerId(cmd.getOptionValue("addr"));
    }
    if (cmd.hasOption("join")) {
        config.setJoinPeer(cmd.getOptionValue("join"));
    }
    if (cmd.hasOption("dir")) {
        config.setLogDir(cmd.getOptionValue("dir"));
    }
    if (cmd.hasOption("timeout")) {
        String sessionTimeout = cmd.getOptionValue("timeout");
        config.setSessionTimeout(Integer.parseInt(sessionTimeout));
    }
    if (cmd.hasOption("port")) {
        config.setPort(Integer.parseInt(cmd.getOptionValue("port")));
    }

    Server server = new Server(config.getPort());
    // Suppress "Server" header in HTTP response.
    for (Connector y : server.getConnectors()) {
        for (ConnectionFactory x : y.getConnectionFactories()) {
            if (x instanceof HttpConnectionFactory) {
                ((HttpConnectionFactory) x).getHttpConfiguration().setSendServerVersion(false);
            }
        }
    }

    PulseFS fs = new PulseFS(config);
    SessionFilter sessionFilter = new SessionFilter(fs);
    FilterHolder filters = new FilterHolder(sessionFilter);

    ServletContextHandler pulsefs = new ServletContextHandler(ServletContextHandler.SESSIONS);
    pulsefs.setContextPath(PulseFSConfig.PULSEFS_ROOT);
    pulsefs.setAllowNullPathInfo(true);
    pulsefs.addServlet(new ServletHolder(new PulseFSHandler(fs)), "/*");
    pulsefs.addFilter(filters, "/*", EnumSet.of(DispatcherType.REQUEST));

    ServletContextHandler servers = new ServletContextHandler(ServletContextHandler.SESSIONS);
    servers.setContextPath(PulseFSConfig.PULSEFS_SERVERS_PATH);
    // Redirects /pulsefs/servers to /pulsefs/servers/
    servers.setAllowNullPathInfo(true);
    servers.addServlet(new ServletHolder(new PulseFSServersHandler(fs)), "/*");
    servers.addFilter(filters, "/*", EnumSet.of(DispatcherType.REQUEST));

    ServletContextHandler tree = new ServletContextHandler(ServletContextHandler.SESSIONS);
    tree.setContextPath("/");
    tree.addServlet(new ServletHolder(new TreeHandler(fs)), "/*");
    tree.addFilter(filters, "/*", EnumSet.of(DispatcherType.REQUEST));

    ServletContextHandler sessions = new ServletContextHandler(ServletContextHandler.SESSIONS);
    sessions.setContextPath(PulseFSConfig.PULSEFS_SESSIONS_PATH);
    // Redirects /pulsefs/sessions to /pulsefs/sessions/
    sessions.setAllowNullPathInfo(true);
    sessions.addServlet(new ServletHolder(new PulseFSSessionsHandler(fs)), "/*");
    sessions.addFilter(filters, "/*", EnumSet.of(DispatcherType.REQUEST));

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] { sessions, servers, pulsefs, tree });
    server.setHandler(contexts);
    server.start();
    server.join();
}

From source file:com.alexoree.jenkins.Main.java

public static void main(String[] args) throws Exception {
    // create Options object
    Options options = new Options();

    options.addOption("t", false, "throttle the downloads, waits 5 seconds in between each d/l");

    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("jenkins-sync", options);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    boolean throttle = cmd.hasOption("t");

    String plugins = "https://updates.jenkins-ci.org/latest/";
    List<String> ps = new ArrayList<String>();
    Document doc = Jsoup.connect(plugins).get();
    for (Element file : doc.select("td a")) {
        //System.out.println(file.attr("href"));
        if (file.attr("href").endsWith(".hpi") || file.attr("href").endsWith(".war")) {
            ps.add(file.attr("href"));
        }//from www.j  a va2 s.com
    }

    File root = new File(".");
    //https://updates.jenkins-ci.org/latest/AdaptivePlugin.hpi
    new File("./latest").mkdirs();

    //output zip file
    String zipFile = "jenkinsSync.zip";
    // create byte buffer
    byte[] buffer = new byte[1024];
    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    //download the plugins
    for (int i = 0; i < ps.size(); i++) {
        System.out.println("[" + i + "/" + ps.size() + "] downloading " + plugins + ps.get(i));
        String outputFile = download(root.getAbsolutePath() + "/latest/" + ps.get(i), plugins + ps.get(i));

        FileInputStream fis = new FileInputStream(outputFile);
        // begin writing a new ZIP entry, positions the stream to the start of the entry data
        zos.putNextEntry(new ZipEntry(outputFile.replace(root.getAbsolutePath(), "")
                .replace("updates.jenkins-ci.org/", "").replace("https:/", "")));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
        if (throttle)
            Thread.sleep(WAIT);
        new File(root.getAbsolutePath() + "/latest/" + ps.get(i)).deleteOnExit();
    }

    //download the json metadata
    plugins = "https://updates.jenkins-ci.org/";
    ps = new ArrayList<String>();
    doc = Jsoup.connect(plugins).get();
    for (Element file : doc.select("td a")) {
        //System.out.println(file.attr("href"));
        if (file.attr("href").endsWith(".json")) {
            ps.add(file.attr("href"));
        }
    }
    for (int i = 0; i < ps.size(); i++) {
        download(root.getAbsolutePath() + "/" + ps.get(i), plugins + ps.get(i));

        FileInputStream fis = new FileInputStream(root.getAbsolutePath() + "/" + ps.get(i));
        // begin writing a new ZIP entry, positions the stream to the start of the entry data
        zos.putNextEntry(new ZipEntry(plugins + ps.get(i)));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
        new File(root.getAbsolutePath() + "/" + ps.get(i)).deleteOnExit();
        if (throttle)
            Thread.sleep(WAIT);
    }

    // close the ZipOutputStream
    zos.close();
}