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:io.apicurio.studio.tools.release.ReleaseTool.java

/**
 * Main method./*from w w w. j av  a 2  s. c  o m*/
 * @param args
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("n", "release-name", true, "The name of the new release.");
    options.addOption("p", "prerelease", false, "Indicate that this is a pre-release.");
    options.addOption("t", "release-tag", true, "The tag name of the new release.");
    options.addOption("o", "previous-tag", true, "The tag name of the previous release.");
    options.addOption("g", "github-pat", true, "The GitHub PAT (for authentication/authorization).");
    options.addOption("a", "artifact", true, "The binary release artifact (full path).");
    options.addOption("d", "output-directory", true, "Where to store output file(s).");

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

    if (!cmd.hasOption("n") || !cmd.hasOption("t") || !cmd.hasOption("o") || !cmd.hasOption("g")
            || !cmd.hasOption("a")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("release-studio", options);
        System.exit(1);
    }

    // Arguments (command line)
    String releaseName = cmd.getOptionValue("n");
    boolean isPrerelease = cmd.hasOption("p");
    String releaseTag = cmd.getOptionValue("t");
    String oldReleaseTag = cmd.getOptionValue("o");
    String githubPAT = cmd.getOptionValue("g");
    String artifact = cmd.getOptionValue("a");
    File outputDir = new File("");
    if (cmd.hasOption("d")) {
        outputDir = new File(cmd.getOptionValue("d"));
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }
    }

    File releaseArtifactFile = new File(artifact);
    File releaseArtifactSigFile = new File(artifact + ".asc");

    String releaseArtifact = releaseArtifactFile.getName();
    String releaseArtifactSig = releaseArtifactSigFile.getName();

    if (!releaseArtifactFile.isFile()) {
        System.err.println("Missing file: " + releaseArtifactFile.getAbsolutePath());
        System.exit(1);
    }
    if (!releaseArtifactSigFile.isFile()) {
        System.err.println("Missing file: " + releaseArtifactSigFile.getAbsolutePath());
        System.exit(1);
    }

    System.out.println("=========================================");
    System.out.println("Creating Release: " + releaseTag);
    System.out.println("Previous Release: " + oldReleaseTag);
    System.out.println("            Name: " + releaseName);
    System.out.println("        Artifact: " + releaseArtifact);
    System.out.println("     Pre-Release: " + isPrerelease);
    System.out.println("=========================================");

    String releaseNotes = "";

    // Step #1 - Generate Release Notes
    //   * Grab info about the previous release (extract publish date)
    //   * Query all Issues for ones closed since that date
    //   * Generate Release Notes from the resulting Issues
    try {
        System.out.println("Getting info about release " + oldReleaseTag);
        HttpResponse<JsonNode> response = Unirest
                .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/tags/v" + oldReleaseTag)
                .header("Accept", "application/json").header("Authorization", "token " + githubPAT).asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to get old release info: " + response.getStatusText());
        }
        JsonNode body = response.getBody();
        String publishedDate = body.getObject().getString("published_at");
        if (publishedDate == null) {
            throw new Exception("Could not find Published Date for previous release " + oldReleaseTag);
        }
        System.out.println("Release " + oldReleaseTag + " was published on " + publishedDate);

        List<JSONObject> issues = getIssuesForRelease(publishedDate, githubPAT);
        System.out.println("Found " + issues.size() + " issues closed in release " + releaseTag);
        System.out.println("Generating Release Notes");

        releaseNotes = generateReleaseNotes(releaseName, releaseTag, issues);
        System.out.println("------------ Release Notes --------------");
        System.out.println(releaseNotes);
        System.out.println("-----------------------------------------");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    String assetUploadUrl = null;

    // Step #2 - Create a GitHub Release
    try {
        System.out.println("\nCreating GitHub Release " + releaseTag);
        JSONObject body = new JSONObject();
        body.put("tag_name", "v" + releaseTag);
        body.put("name", releaseName);
        body.put("body", releaseNotes);
        body.put("prerelease", isPrerelease);

        HttpResponse<JsonNode> response = Unirest
                .post("https://api.github.com/repos/apicurio/apicurio-studio/releases")
                .header("Accept", "application/json").header("Content-Type", "application/json")
                .header("Authorization", "token " + githubPAT).body(body).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to create release in GitHub: " + response.getStatusText());
        }

        assetUploadUrl = response.getBody().getObject().getString("upload_url");
        if (assetUploadUrl == null || assetUploadUrl.trim().isEmpty()) {
            throw new Exception("Failed to get Asset Upload URL for newly created release!");
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    // Step #3 - Upload Release Artifact (zip file)
    System.out.println("\nUploading Quickstart Artifact: " + releaseArtifact);
    try {
        String artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifact);
        byte[] artifactData = loadArtifactData(releaseArtifactFile);
        System.out.println("Uploading artifact asset: " + artifactUploadUrl);
        HttpResponse<JsonNode> response = Unirest.post(artifactUploadUrl).header("Accept", "application/json")
                .header("Content-Type", "application/zip").header("Authorization", "token " + githubPAT)
                .body(artifactData).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to upload asset: " + releaseArtifact,
                    new Exception(response.getStatus() + "::" + response.getStatusText()));
        }

        Thread.sleep(1000);

        artifactUploadUrl = createUploadUrl(assetUploadUrl, releaseArtifactSig);
        artifactData = loadArtifactData(releaseArtifactSigFile);
        System.out.println("Uploading artifact asset: " + artifactUploadUrl);
        response = Unirest.post(artifactUploadUrl).header("Accept", "application/json")
                .header("Content-Type", "text/plain").header("Authorization", "token " + githubPAT)
                .body(artifactData).asJson();
        if (response.getStatus() != 201) {
            throw new Exception("Failed to upload asset: " + releaseArtifactSig,
                    new Exception(response.getStatus() + "::" + response.getStatusText()));
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    Thread.sleep(1000);

    // Step #4 - Download Latest Release JSON for inclusion in the project web site
    try {
        System.out.println("Getting info about the release.");
        HttpResponse<JsonNode> response = Unirest
                .get("https://api.github.com/repos/apicurio/apicurio-studio/releases/latest")
                .header("Accept", "application/json").asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to get release info: " + response.getStatusText());
        }
        JsonNode body = response.getBody();
        String publishedDate = body.getObject().getString("published_at");
        if (publishedDate == null) {
            throw new Exception("Could not find Published Date for release.");
        }
        String fname = publishedDate.replace(':', '-');
        File outFile = new File(outputDir, fname + ".json");

        System.out.println("Writing latest release info to: " + outFile.getAbsolutePath());

        String output = body.getObject().toString(4);
        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            fos.write(output.getBytes("UTF-8"));
            fos.flush();
        }

        System.out.println("Release info successfully written.");
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    System.out.println("=========================================");
    System.out.println("All Done!");
    System.out.println("=========================================");
}

From source file:com.twentyn.patentScorer.PatentScorer.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();/*from   w  w w .  ja v a2 s.co  m*/
    Options opts = new Options();
    opts.addOption(Option.builder("i").longOpt("input").hasArg().required()
            .desc("Input file or directory to score").build());
    opts.addOption(Option.builder("o").longOpt("output").hasArg().required()
            .desc("Output file to which to write score JSON").build());
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
    opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }

    if (cmdLine.hasOption("verbose")) {
        // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2
        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration ctxConfig = ctx.getConfiguration();
        LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
        logConfig.setLevel(Level.DEBUG);

        ctx.updateLoggers();
        LOGGER.debug("Verbose logging enabled");
    }

    String inputFileOrDir = cmdLine.getOptionValue("input");
    File splitFileOrDir = new File(inputFileOrDir);
    if (!(splitFileOrDir.exists())) {
        LOGGER.error("Unable to find directory at " + inputFileOrDir);
        System.exit(1);
    }

    try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"))) {
        PatentScorer scorer = new PatentScorer(PatentModel.getModel(), writer);
        PatentCorpusReader corpusReader = new PatentCorpusReader(scorer, splitFileOrDir);
        corpusReader.readPatentCorpus();
    }
}

From source file:com.twentyn.patentTextProcessor.WordCountProcessor.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();/*from w  w  w. j  a  va  2 s  .co  m*/
    Options opts = new Options();
    opts.addOption(Option.builder("i").longOpt("input").hasArg().required()
            .desc("Input file or directory to score").build());
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
    opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("WordCountProcessor", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }

    String inputFileOrDir = cmdLine.getOptionValue("input");
    File splitFileOrDir = new File(inputFileOrDir);
    if (!(splitFileOrDir.exists())) {
        LOGGER.error("Unable to find directory at " + inputFileOrDir);
        System.exit(1);
    }

    WordCountProcessor wcp = new WordCountProcessor();
    PatentCorpusReader corpusReader = new PatentCorpusReader(wcp, splitFileOrDir);
    corpusReader.readPatentCorpus();
}

From source file:com.threadswarm.imagefeedarchiver.driver.CommandLineDriver.java

public static void main(String[] args) throws InterruptedException, ExecutionException, ParseException {
    // define available command-line options
    Options options = new Options();
    options.addOption("h", "help", false, "display usage information");
    options.addOption("u", "url", true, "RSS feed URL");
    options.addOption("a", "user-agent", true, "User-Agent header value to use when making HTTP requests");
    options.addOption("o", "output-directory", true, "output directory for downloaded images");
    options.addOption("t", "thread-count", true, "number of worker threads, defaults to cpu-count + 1");
    options.addOption("d", "delay", true, "delay between image downloads (in milliseconds)");
    options.addOption("p", "notrack", false, "tell websites that you don't wish to be tracked (DNT)");
    options.addOption("s", "https", false, "Rewrite image URLs to leverage SSL/TLS");

    CommandLineParser commandLineParser = new BasicParser();
    CommandLine commandLine = commandLineParser.parse(options, args);

    // print usage information if 'h'/'help' or no-args were given
    if (args.length == 0 || commandLine.hasOption("h")) {
        HelpFormatter helpFormatter = new HelpFormatter();
        helpFormatter.printHelp("java -jar ImageFeedArchiver.jar", options);
        return; //abort execution
    }//from   w  w  w. ja v  a2s  . c  o m

    URI rssFeedUri = null;
    if (commandLine.hasOption("u")) {
        String rssFeedUrlString = commandLine.getOptionValue("u");
        try {
            rssFeedUri = FeedUtils.getUriFromUrlString(rssFeedUrlString);
        } catch (MalformedURLException | URISyntaxException e) {
            LOGGER.error("The Feed URL you supplied was malformed or violated syntax rules.. exiting", e);
            System.exit(1);
        }
        LOGGER.info("Target RSS feed URL: {}", rssFeedUri);
    } else {
        throw new IllegalStateException("RSS feed URL was not specified!");
    }

    File outputDirectory = null;
    if (commandLine.hasOption("o")) {
        outputDirectory = new File(commandLine.getOptionValue("o"));
        if (!outputDirectory.isDirectory())
            throw new IllegalArgumentException("output directory must be a *directory*!");
        LOGGER.info("Using output directory: '{}'", outputDirectory);
    } else {
        throw new IllegalStateException("output directory was not specified!");
    }

    String userAgentString = null;
    if (commandLine.hasOption("a")) {
        userAgentString = commandLine.getOptionValue("a");
        LOGGER.info("Setting 'User-Agent' header value to '{}'", userAgentString);
    }

    int threadCount;
    if (commandLine.hasOption("t")) {
        threadCount = Integer.parseInt(commandLine.getOptionValue("t"));
    } else {
        threadCount = Runtime.getRuntime().availableProcessors() + 1;
    }
    LOGGER.info("Using {} worker threads", threadCount);

    long downloadDelay = 0;
    if (commandLine.hasOption("d")) {
        String downloadDelayString = commandLine.getOptionValue("d");
        downloadDelay = Long.parseLong(downloadDelayString);
    }
    LOGGER.info("Using a download-delay of {} milliseconds", downloadDelay);

    boolean doNotTrackRequested = commandLine.hasOption("p");

    boolean forceHttps = commandLine.hasOption("s");

    ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
    ((ConfigurableApplicationContext) context).registerShutdownHook();

    HttpClient httpClient = (HttpClient) context.getBean("httpClient");
    if (userAgentString != null)
        httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgentString);

    ProcessedRssItemDAO processedRssItemDAO = (ProcessedRssItemDAO) context.getBean("processedRssItemDAO");

    CommandLineDriver.Builder driverBuilder = new CommandLineDriver.Builder(rssFeedUri);
    driverBuilder.setDoNotTrackRequested(doNotTrackRequested).setOutputDirectory(outputDirectory)
            .setDownloadDelay(downloadDelay).setThreadCount(threadCount).setHttpClient(httpClient)
            .setForceHttps(forceHttps).setProcessedRssItemDAO(processedRssItemDAO);

    CommandLineDriver driver = driverBuilder.build();
    driver.run();
}

From source file:com.hpe.nv.samples.basic.BasicNVTest.java

public static void main(String[] args) {
    try {//from   w  w  w.  j  av  a2 s. co m
        // program arguments
        Options options = new Options();
        options.addOption("i", "server-ip", true, "[mandatory] NV Test Manager IP");
        options.addOption("o", "server-port", true, "[mandatory] NV Test Manager port");
        options.addOption("u", "username", true, "[mandatory] NV username");
        options.addOption("w", "password", true, "[mandatory] NV password");
        options.addOption("e", "ssl", true, "[optional] Pass true to use SSL. Default: false");
        options.addOption("y", "proxy", true, "[optional] Proxy server host:port");
        options.addOption("b", "browser", true,
                "[optional] The browser for which the Selenium WebDriver is built. Possible values: Chrome and Firefox. Default: Firefox");
        options.addOption("d", "debug", true,
                "[optional] Pass true to view console debug messages during execution. Default: false");
        options.addOption("h", "help", false, "[optional] Generates and prints help information");

        // parse and validate the command line arguments
        CommandLineParser parser = new DefaultParser();
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            // print help if help argument is passed
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("BasicNVTest.java", options);
            return;
        }

        if (line.hasOption("server-ip")) {
            serverIp = line.getOptionValue("server-ip");
            if (serverIp.equals("0.0.0.0")) {
                throw new Exception(
                        "Please replace the server IP argument value (0.0.0.0) with your NV Test Manager IP");
            }
        } else {
            throw new Exception("Missing argument -i/--server-ip <serverIp>");
        }

        if (line.hasOption("server-port")) {
            serverPort = Integer.parseInt(line.getOptionValue("server-port"));
        } else {
            throw new Exception("Missing argument -o/--server-port <serverPort>");
        }

        if (line.hasOption("username")) {
            username = line.getOptionValue("username");
        } else {
            throw new Exception("Missing argument -u/--username <username>");
        }

        if (line.hasOption("password")) {
            password = line.getOptionValue("password");
        } else {
            throw new Exception("Missing argument -w/--password <password>");
        }

        if (line.hasOption("ssl")) {
            ssl = Boolean.parseBoolean(line.getOptionValue("ssl"));
        }

        if (line.hasOption("proxy")) {
            proxySetting = line.getOptionValue("proxy");
        }

        if (line.hasOption("browser")) {
            browser = line.getOptionValue("browser");
        } else {
            browser = "Firefox";
        }

        if (line.hasOption("debug")) {
            debug = Boolean.parseBoolean(line.getOptionValue("debug"));
        }

        String newLine = System.getProperty("line.separator");
        String testDescription = "***   This sample demonstrates the use of the most basic NV methods.                               ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   First, the sample creates a TestManager object and initializes it.                           ***"
                + newLine
                + "***   The sample starts an NV test over an emulated \"3G Busy\" network.                             ***"
                + newLine
                + "***   (\"3G Busy\" is one of NV's built-in network profiles. A network profile specifies the         ***"
                + newLine
                + "***   network traffic behavior, including latency, packet loss, and incoming/outgoing bandwidth.   ***"
                + newLine
                + "***   Network profiles are used to emulate traffic over real-world networks.)                      ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Next, the sample navigates to the home page in the HPE Network Virtualization website        ***"
                + newLine
                + "***   using the Selenium WebDriver.                                                                ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   Finally, the sample stops the NV test.                                                       ***"
                + newLine
                + "***                                                                                                ***"
                + newLine
                + "***   You can view the actual steps of this sample in the BasicNVTest.java file.                   ***"
                + newLine;

        // print the sample's description
        System.out.println(testDescription);

        // start console spinner
        if (!debug) {
            spinner = new Thread(new Spinner());
            spinner.start();
        }

        // sample execution steps
        /*****    Part 1 - Create a TestManager object and initialize it                                   *****/
        printPartDescription("\b------    Part 1 - Create a TestManager object and initialize it");
        initTestManager();
        printPartSeparator();
        /*****    Part 2 - Start the NV test with the "3G Busy" network scenario                           *****/
        printPartDescription("------    Part 2 - Start the NV test with the \"3G Busy\" network scenario");
        startTest();
        testRunning = true;
        printPartSeparator();
        /*****    Part 3 - Navigate to the HPE Network Virtualization website                              *****/
        printPartDescription("------    Part 3 - Navigate to the HPE Network Virtualization website");
        buildSeleniumWebDriver();
        seleniumNavigateToPage();
        driverCloseAndQuit();
        printPartSeparator();
        /*****    Part 4 - Stop the NV test                                                                *****/
        printPartDescription("------    Part 4 - Stop the NV test");
        stopTest();
        testRunning = false;
        printPartSeparator();
        doneCallback();
    } catch (Exception e) {
        try {
            handleError(e.getMessage());
        } catch (Exception e2) {
            System.out.println("Error occurred: " + e2.getMessage());
        }
    }
}

From source file:com.github.braully.graph.UtilResultCompare.java

public static void main(String... args) throws Exception {
    Options options = new Options();

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(false);/*  ww w.jav  a2 s  . c om*/
    options.addOption(input);

    Option output = new Option("o", "output", true, "output file");
    output.setRequired(false);
    options.addOption(output);

    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("UtilResult", options);

        System.exit(1);
        return;
    }

    String inputFilePath = cmd.getOptionValue("input");
    if (inputFilePath == null) {
        inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-quartic-ht.txt";

        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-mft-parcial-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-highlyirregular-ht.txt";
        //            inputFilePath = "/home/strike/Documentos/grafos-processados/mtf/resultado-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-hypo-parcial-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-eul-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-almhypo-ht.txt";
        //            inputFilePath = "/home/strike/Dropbox/documentos/mestrado/resultado-processamento-grafos/resultado-Almost_hypohamiltonian_graphs_cubic-parcial-ht.txt";
    }
    if (inputFilePath != null) {
        if (inputFilePath.toLowerCase().endsWith(".txt")) {
            processFileTxt(inputFilePath);
        } else if (inputFilePath.toLowerCase().endsWith(".json")) {
            processFileJson(inputFilePath);
        }
    }
}

From source file:com.twentyn.patentSearch.DocumentIndexer.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();//  w w  w. ja  v  a 2s .  com
    Options opts = new Options();
    opts.addOption(Option.builder("i").longOpt("input").hasArg().required()
            .desc("Input file or directory to index").build());
    opts.addOption(Option.builder("x").longOpt("index").hasArg().required()
            .desc("Path to index file to generate").build());
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
    opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }

    if (cmdLine.hasOption("verbose")) {
        // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2
        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration ctxConfig = ctx.getConfiguration();
        LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
        logConfig.setLevel(Level.DEBUG);

        ctx.updateLoggers();
        LOGGER.debug("Verbose logging enabled");
    }

    LOGGER.info("Opening index at " + cmdLine.getOptionValue("index"));
    Directory indexDir = FSDirectory.open(new File(cmdLine.getOptionValue("index")).toPath());

    /* The standard analyzer is too aggressive with chemical entities (it strips structural annotations, for one
     * thing), and the whitespace analyzer doesn't do any case normalization or stop word elimination.  This custom
     * analyzer appears to treat chemical entities better than the standard analyzer without admitting too much
     * cruft to the index. */
    Analyzer analyzer = CustomAnalyzer.builder().withTokenizer("whitespace").addTokenFilter("lowercase")
            .addTokenFilter("stop").build();

    IndexWriterConfig writerConfig = new IndexWriterConfig(analyzer);
    writerConfig.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
    writerConfig.setRAMBufferSizeMB(1 << 10);
    IndexWriter indexWriter = new IndexWriter(indexDir, writerConfig);

    String inputFileOrDir = cmdLine.getOptionValue("input");
    File splitFileOrDir = new File(inputFileOrDir);
    if (!(splitFileOrDir.exists())) {
        LOGGER.error("Unable to find directory at " + inputFileOrDir);
        System.exit(1);
    }

    DocumentIndexer indexer = new DocumentIndexer(indexWriter);
    PatentCorpusReader corpusReader = new PatentCorpusReader(indexer, splitFileOrDir);
    corpusReader.readPatentCorpus();
    indexer.commitAndClose();
}

From source file:com.jwm123.loggly.reporter.AppLauncher.java

public static void main(String args[]) throws Exception {
    try {//from w  w  w  .  j a v  a  2 s . c om
        CommandLine cl = parseCLI(args);
        try {
            config = new Configuration();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("ERROR: Failed to read in persisted configuration.");
        }
        if (cl.hasOption("h")) {

            HelpFormatter help = new HelpFormatter();
            String jarName = AppLauncher.class.getProtectionDomain().getCodeSource().getLocation().getFile();
            if (jarName.contains("/")) {
                jarName = jarName.substring(jarName.lastIndexOf("/") + 1);
            }
            help.printHelp("java -jar " + jarName + " [options]", opts);
        }
        if (cl.hasOption("c")) {
            config.update();
        }
        if (cl.hasOption("q")) {
            Client client = new Client(config);
            client.setQuery(cl.getOptionValue("q"));
            if (cl.hasOption("from")) {
                client.setFrom(cl.getOptionValue("from"));
            }
            if (cl.hasOption("to")) {
                client.setTo(cl.getOptionValue("to"));
            }
            List<Map<String, Object>> report = client.getReport();

            if (report != null) {
                List<Map<String, String>> reportContent = new ArrayList<Map<String, String>>();
                ReportGenerator generator = null;
                if (cl.hasOption("file")) {
                    generator = new ReportGenerator(new File(cl.getOptionValue("file")));
                }
                byte reportFile[] = null;

                if (cl.hasOption("g")) {
                    System.out.println("Search results: " + report.size());
                    Set<Object> values = new TreeSet<Object>();
                    Map<Object, Integer> counts = new HashMap<Object, Integer>();
                    for (String groupBy : cl.getOptionValues("g")) {
                        for (Map<String, Object> result : report) {
                            if (mapContains(result, groupBy)) {
                                Object value = mapGet(result, groupBy);
                                values.add(value);
                                if (counts.containsKey(value)) {
                                    counts.put(value, counts.get(value) + 1);
                                } else {
                                    counts.put(value, 1);
                                }
                            }
                        }
                        System.out.println("For key: " + groupBy);
                        for (Object value : values) {
                            System.out.println("  " + value + ": " + counts.get(value));
                        }
                    }
                    if (cl.hasOption("file")) {
                        Map<String, String> reportAddition = new LinkedHashMap<String, String>();
                        reportAddition.put("Month", MONTH_FORMAT.format(new Date()));
                        reportContent.add(reportAddition);
                        for (Object value : values) {
                            reportAddition = new LinkedHashMap<String, String>();
                            reportAddition.put(value.toString(), "" + counts.get(value));
                            reportContent.add(reportAddition);
                        }
                        reportAddition = new LinkedHashMap<String, String>();
                        reportAddition.put("Total", "" + report.size());
                        reportContent.add(reportAddition);
                    }
                } else {
                    System.out.println("The Search [" + cl.getOptionValue("q") + "] yielded " + report.size()
                            + " results.");
                    if (cl.hasOption("file")) {
                        Map<String, String> reportAddition = new LinkedHashMap<String, String>();
                        reportAddition.put("Month", MONTH_FORMAT.format(new Date()));
                        reportContent.add(reportAddition);
                        reportAddition = new LinkedHashMap<String, String>();
                        reportAddition.put("Count", "" + report.size());
                        reportContent.add(reportAddition);
                    }
                }
                if (cl.hasOption("file")) {
                    reportFile = generator.build(reportContent);
                    File reportFileObj = new File(cl.getOptionValue("file"));
                    FileUtils.writeByteArrayToFile(reportFileObj, reportFile);
                    if (cl.hasOption("e")) {
                        ReportMailer mailer = new ReportMailer(config, cl.getOptionValues("e"),
                                cl.getOptionValue("s"), reportFileObj.getName(), reportFile);
                        mailer.send();
                    }
                }
            }
        }

    } catch (IllegalArgumentException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}

From source file:de.zib.scalaris.Main.java

/**
 * Queries the command line options for an action to perform.
 * /*  w ww. j a v a2s .com*/
 * <pre>
 * <code>
 * > java -jar scalaris.jar -help
 * usage: scalaris [Options]
 *  -b,--minibench                   run mini benchmark
 *  -d,--delete <key> <[timeout]>    delete an item (default timeout: 2000ms)
 *                                   WARNING: This function can lead to
 *                                   inconsistent data (e.g. deleted items
 *                                   can re-appear). Also when re-creating an
 *                                   item the version before the delete can
 *                                   re-appear.
 *  -g,--getsubscribers <topic>      get subscribers of a topic
 *  -h,--help                        print this message
 *  -lh,--localhost                  gets the local host's name as known to
 *                                   Java (for debugging purposes)
 *  -p,--publish <topic> <message>   publish a new message for the given
 *                                   topic
 *  -r,--read <key>                  read an item
 *  -s,--subscribe <topic> <url>     subscribe to a topic
 *  -u,--unsubscribe <topic> <url>   unsubscribe from a topic
 *  -v,--verbose                     print verbose information, e.g. the
 *                                   properties read
 *  -w,--write <key> <value>         write an item
 * </code>
 * </pre>
 * 
 * @param args
 *            command line arguments
 */
public static void main(String[] args) {
    boolean verbose = false;
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    Options options = getOptions();
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        printException("Parsing failed", e, false);
    }

    if (line.hasOption("verbose")) {
        verbose = true;
        ConnectionFactory.getInstance().printProperties();
    }

    if (line.hasOption("minibench")) {
        Benchmark.minibench();
    } else if (line.hasOption("r")) { // read
        String key = line.getOptionValue("read");
        checkArguments(key, options, "r");
        try {
            Scalaris sc = new Scalaris();
            String value = sc.read(key);
            System.out.println("read(" + key + ") == " + value);
        } catch (ConnectionException e) {
            printException("read failed with connection error", e, verbose);
        } catch (TimeoutException e) {
            printException("read failed with timeout", e, verbose);
        } catch (NotFoundException e) {
            printException("read failed with not found", e, verbose);
        } catch (UnknownException e) {
            printException("read failed with unknown", e, verbose);
        }
    } else if (line.hasOption("w")) { // write
        String[] optionValues = line.getOptionValues("write");
        checkArguments(optionValues, 2, options, "w");
        String key = optionValues[0];
        String value = optionValues[1];
        try {
            Scalaris sc = new Scalaris();
            sc.write(key, value);
            System.out.println("write(" + key + ", " + value + ")");
        } catch (ConnectionException e) {
            printException("write failed with connection error", e, verbose);
        } catch (TimeoutException e) {
            printException("write failed with timeout", e, verbose);
        } catch (UnknownException e) {
            printException("write failed with unknown", e, verbose);
        }
    } else if (line.hasOption("p")) { // publish
        String[] optionValues = line.getOptionValues("publish");
        checkArguments(optionValues, 2, options, "p");
        String topic = optionValues[0];
        String content = optionValues[1];
        if (content == null) {
            // parsing methods of commons.cli only checks the first argument :(
            printException("Parsing failed", new ParseException("missing content for option p"), verbose);
        }
        try {
            Scalaris sc = new Scalaris();
            sc.publish(topic, content);
            System.out.println("publish(" + topic + ", " + content + ")");
        } catch (ConnectionException e) {
            printException("publish failed with connection error", e, verbose);
        }
    } else if (line.hasOption("s")) { // subscribe
        String[] optionValues = line.getOptionValues("subscribe");
        checkArguments(optionValues, 2, options, "s");
        String topic = optionValues[0];
        String url = optionValues[1];
        try {
            Scalaris sc = new Scalaris();
            sc.subscribe(topic, url);
            System.out.println("subscribe(" + topic + ", " + url + ")");
        } catch (ConnectionException e) {
            printException("subscribe failed with connection error", e, verbose);
        } catch (TimeoutException e) {
            printException("subscribe failed with timeout", e, verbose);
        } catch (UnknownException e) {
            printException("subscribe failed with unknown", e, verbose);
        }
    } else if (line.hasOption("u")) { // unsubscribe
        String[] optionValues = line.getOptionValues("unsubscribe");
        checkArguments(optionValues, 2, options, "u");
        String topic = optionValues[0];
        String url = optionValues[1];
        try {
            Scalaris sc = new Scalaris();
            sc.unsubscribe(topic, url);
            System.out.println("unsubscribe(" + topic + ", " + url + ")");
        } catch (ConnectionException e) {
            printException("unsubscribe failed with connection error", e, verbose);
        } catch (TimeoutException e) {
            printException("unsubscribe failed with timeout", e, verbose);
        } catch (NotFoundException e) {
            printException("unsubscribe failed with not found", e, verbose);
        } catch (UnknownException e) {
            printException("unsubscribe failed with unknown", e, verbose);
        }
    } else if (line.hasOption("g")) { // getsubscribers
        String topic = line.getOptionValue("getsubscribers");
        checkArguments(topic, options, "g");
        try {
            Scalaris sc = new Scalaris();
            ArrayList<String> subscribers = sc.getSubscribers(topic);
            System.out.println("getSubscribers(" + topic + ") == " + subscribers);
        } catch (ConnectionException e) {
            printException("getSubscribers failed with connection error", e, verbose);
        } catch (UnknownException e) {
            printException("getSubscribers failed with unknown error", e, verbose);
        }
    } else if (line.hasOption("d")) { // delete
        String[] optionValues = line.getOptionValues("delete");
        checkArguments(optionValues, 1, options, "d");
        String key = optionValues[0];
        int timeout = 2000;
        if (optionValues.length >= 2) {
            try {
                timeout = Integer.parseInt(optionValues[1]);
            } catch (Exception e) {
                printException("Parsing failed",
                        new ParseException("wrong type for timeout parameter of option d" + " (parameters: <"
                                + options.getOption("d").getArgName() + ">)"),
                        verbose);
            }
        }
        try {
            Scalaris sc = new Scalaris();
            sc.delete(key, timeout);
            DeleteResult deleteResult = sc.getLastDeleteResult();
            System.out.println("delete(" + key + ", " + timeout + "): " + deleteResult.ok + " ok, "
                    + deleteResult.locks_set + " locks_set, " + deleteResult.undef + " undef");
        } catch (ConnectionException e) {
            printException("delete failed with connection error", e, verbose);
        } catch (TimeoutException e) {
            printException("delete failed with timeout", e, verbose);
        } catch (NodeNotFoundException e) {
            printException("delete failed with node not found", e, verbose);
        } catch (UnknownException e) {
            printException("delete failed with unknown error", e, verbose);
        }
    } else if (line.hasOption("lh")) { // get local host name
        System.out.println(ConnectionFactory.getLocalhostName());
    } else {
        // print help if no other option was given
        //      if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("scalaris [Options]", getOptions());
    }
}

From source file:net.mybox.mybox.ClientGUI.java

/**
* @param args the command line arguments
*///from w ww.jav a2  s.c  om
public static void main(String args[]) {

    Options options = new Options();
    options.addOption("c", "config", true, "configuration directory (default=~/.mybox)");
    options.addOption("a", "apphome", true, "application home directory");
    options.addOption("d", "debug", false, "enable debug mode");
    options.addOption("h", "help", false, "show help screen");
    options.addOption("V", "version", false, "print the Mybox version");

    CommandLineParser line = new GnuParser();
    CommandLine cmd = null;

    String configDir = Client.defaultConfigDir;

    try {
        cmd = line.parse(options, args);
    } catch (Exception exp) {
        System.err.println(exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ClientGUI.class.getName(), options);
        return;
    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(ClientGUI.class.getName(), options);
        return;
    }

    if (cmd.hasOption("V")) {
        Client.printMessage("version " + Common.appVersion);
        return;
    }

    if (cmd.hasOption("d")) {
        debugMode = true;
    }

    if (cmd.hasOption("a")) {
        String appHomeDir = cmd.getOptionValue("a");
        try {
            Common.updatePaths(appHomeDir);
        } catch (FileNotFoundException e) {
            printErrorExit(e.getMessage());
        }

        Client.updatePaths();
    }

    if (cmd.hasOption("c")) {
        configDir = cmd.getOptionValue("c");
    }

    Client.setConfigDir(configDir);

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new ClientGUI(Client.configFile);
        }
    });
}