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: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(/*  w ww  . j a  va  2  s.c  om*/
            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.k42b3.quantum.Entry.java

public static void main(String[] args) throws Exception {
    // logging//  ww  w  .j  av  a2 s. com
    Layout layout = new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN);

    Logger.getLogger("com.k42b3.quantum").addAppender(new WriterAppender(layout, System.out));

    // options
    Options options = new Options();
    options.addOption("p", "port", false, "Port for the web server default is 8080");
    options.addOption("i", "interval", false,
            "The interval how often each worker gets triggered in minutes default is 2");
    options.addOption("d", "database", false, "Path to the sqlite database default is \"quantum.db\"");
    options.addOption("l", "log", false,
            "Defines the log level default is ERROR possible is (ALL, TRACE, DEBUG, INFO, WARN, ERROR, FATAL, OFF)");
    options.addOption("v", "version", false, "Shows the current version");
    options.addOption("h", "help", false, "Shows the help");

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

    // start app
    Quantum app = new Quantum();

    if (cmd.hasOption("p")) {
        try {
            int port = Integer.parseInt(cmd.getOptionValue("p"));

            app.setPort(port);
        } catch (NumberFormatException e) {
            Logger.getLogger("com.k42b3.quantum").info("Port must be an integer");
        }
    }

    if (cmd.hasOption("i")) {
        try {
            int pollInterval = Integer.parseInt(cmd.getOptionValue("i"));

            app.setPollInterval(pollInterval);
        } catch (NumberFormatException e) {
            Logger.getLogger("com.k42b3.quantum").info("Interval must be an integer");
        }
    }

    if (cmd.hasOption("d")) {
        String dbPath = cmd.getOptionValue("d");

        if (!dbPath.isEmpty()) {
            app.setDbPath(dbPath);
        }
    }

    if (cmd.hasOption("l")) {
        Logger.getLogger("com.k42b3.quantum").setLevel(Level.toLevel(cmd.getOptionValue("l")));
    } else {
        Logger.getLogger("com.k42b3.quantum").setLevel(Level.ERROR);
    }

    if (cmd.hasOption("v")) {
        System.out.println("Version: " + Quantum.VERSION);
        System.exit(0);
    }

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("quantum.jar", options);
        System.exit(0);
    }

    app.run();
}

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 www. j a  va  2  s. c  om*/
    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.zarkonnen.longan.Main.java

public static void main(String[] args) throws IOException {
    // Use Apache Commons CLI (packaged into the Jar) to parse command line options.
    Options options = new Options();
    Option helpO = OptionBuilder.withDescription("print help").create("h");
    Option versionO = OptionBuilder.withDescription("print version").create("v");
    Option outputO = OptionBuilder.withDescription("output file").withLongOpt("out").hasArg()
            .withArgName("file").create("o");
    Option formatO = OptionBuilder
            .withDescription("output format: one of plaintext (default) and visualize (debug output in png)")
            .hasArg().withArgName("format").withLongOpt("format").create();
    Option serverO = OptionBuilder.withDescription("launches server mode: Server mode reads "
            + "command line strings one per line exactly as above. If no output file is "
            + "specified, returns a line containing the number of output lines before the "
            + "output. If there is an error, returns a single line with the error message. "
            + "Shut down server by sending \"quit\".").withLongOpt("server").create();
    Option openCLO = OptionBuilder
            .withDescription(//from w w w . ja v a 2  s  . c o  m
                    "enables use of the graphics card to " + "support the OCR system. Defaults to true.")
            .withLongOpt("enable-opencl").hasArg().withArgName("enabled").create();
    options.addOption(helpO);
    options.addOption(versionO);
    options.addOption(outputO);
    options.addOption(formatO);
    options.addOption(serverO);
    options.addOption(openCLO);
    CommandLineParser clp = new GnuParser();
    try {
        CommandLine line = clp.parse(options, args);
        if (line.hasOption("h")) {
            new HelpFormatter().printHelp(INVOCATION, options);
            System.exit(0);
        }
        if (line.hasOption("v")) {
            System.out.println(Longan.VERSION);
            System.exit(0);
        }
        boolean enableOpenCL = true;
        if (line.hasOption("enable-opencl")) {
            enableOpenCL = line.getOptionValue("enable-opencl").toLowerCase().equals("true")
                    || line.getOptionValue("enable-opencl").equals("1");
        }
        if (line.hasOption("server")) {
            Longan longan = Longan.getDefaultImplementation(enableOpenCL);
            BufferedReader inputR = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String input = inputR.readLine();
                if (input.trim().equals("quit")) {
                    return;
                }
                String[] args2 = splitInput(input);
                Options o2 = new Options();
                o2.addOption(outputO);
                o2.addOption(formatO);
                try {
                    line = clp.parse(o2, args2);

                    File outFile = null;
                    if (line.hasOption("o")) {
                        outFile = new File(line.getOptionValue("o"));
                    }

                    ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
                    if (format != DEFAULT_FORMAT && outFile == null) {
                        System.out.println("You must specify an output file for non-plaintext output.");
                        continue;
                    }

                    if (line.getArgList().isEmpty()) {
                        System.out.println("Please specify an input image.");
                        continue;
                    }
                    if (line.getArgList().size() > 1) {
                        System.err.println("Please specify one input image at a time");
                        continue;
                    }

                    File inFile = new File((String) line.getArgList().get(0));

                    if (!inFile.exists()) {
                        System.out.println("The input image does not exist.");
                        continue;
                    }

                    try {
                        Result result = longan.process(ImageIO.read(inFile));
                        if (outFile == null) {
                            String txt = DEFAULT_FORMAT.convert(result);
                            System.out.println(numNewlines(txt) + 1);
                            System.out.print(txt);
                        } else {
                            if (outFile.getAbsoluteFile().getParentFile() != null
                                    && !outFile.getAbsoluteFile().getParentFile().exists()) {
                                outFile.getParentFile().mkdirs();
                            }
                            FileOutputStream fos = new FileOutputStream(outFile);
                            try {
                                format.write(result, fos);
                            } finally {
                                fos.close();
                            }
                        }
                    } catch (Exception e) {
                        System.out.println("Processing error: " + exception(e));
                    }
                } catch (ParseException e) {
                    System.out.println("Input not recognized: " + exception(e));
                }
            } // End server loop
        } else {
            // Single invocation
            File outFile = null;
            if (line.hasOption("o")) {
                outFile = new File(line.getOptionValue("o"));
            }

            ResultConverter format = FORMATS.get(line.getOptionValue("format", "plaintext"));
            if (format != DEFAULT_FORMAT && outFile == null) {
                System.err.println("You must specify an output file for non-plaintext output.");
                System.exit(1);
            }

            if (line.getArgList().isEmpty()) {
                System.err.println("Please specify an input image.");
                new HelpFormatter().printHelp(INVOCATION, options);
                System.exit(1);
            }
            if (line.getArgList().size() > 1) {
                System.err.println("Please specify one input image only. To process multiple "
                        + "images, use server mode.");
                System.exit(1);
            }
            File inFile = new File((String) line.getArgList().get(0));

            if (!inFile.exists()) {
                System.err.println("The input image does not exist.");
                System.exit(1);
            }

            try {
                Result result = Longan.getDefaultImplementation(enableOpenCL).process(ImageIO.read(inFile));
                if (outFile == null) {
                    String txt = DEFAULT_FORMAT.convert(result);
                    System.out.print(txt);
                } else {
                    if (outFile.getAbsoluteFile().getParentFile() != null
                            && !outFile.getAbsoluteFile().getParentFile().exists()) {
                        outFile.getParentFile().mkdirs();
                    }
                    FileOutputStream fos = new FileOutputStream(outFile);
                    try {
                        format.write(format.convert(result), fos);
                    } finally {
                        fos.close();
                    }
                }
            } catch (Exception e) {
                System.err.println("Processing error: " + exception(e));
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        System.err.println("Parsing command line input failed: " + exception(e));
        System.exit(1);
    }
}

From source file:de.l3s.content.mapred.WikipediaPagesBz2InputStream.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("gzipped XML dump file")
            .create(INPUT_OPTION));/*from   www .  j  a v  a  2s .co m*/
    options.addOption(OptionBuilder.withArgName("lang").hasArg().withDescription("output location")
            .create(LANGUAGE_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(INPUT_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(WikipediaPagesBz2InputStream.class.getCanonicalName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String path = cmdline.getOptionValue(INPUT_OPTION);
    String lang = cmdline.hasOption(LANGUAGE_OPTION) ? cmdline.getOptionValue(LANGUAGE_OPTION) : "en";
    WikipediaPage p = WikipediaPageFactory.createWikipediaPage(lang);

    WikipediaPagesBz2InputStream stream = new WikipediaPagesBz2InputStream(path);
    while (stream.readNext(p)) {
        System.out.println(p.getTitle() + "\t" + p.getDocid());
    }
}

From source file:UploadUrlGenerator.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();

    opts.addOption(Option.builder().longOpt(ENDPOINT_OPTION).required().hasArg().argName("url")
            .desc("Sets the ECS S3 endpoint to use, e.g. https://ecs.company.com:9021").build());
    opts.addOption(Option.builder().longOpt(ACCESS_KEY_OPTION).required().hasArg().argName("access-key")
            .desc("Sets the Access Key (user) to sign the request").build());
    opts.addOption(Option.builder().longOpt(SECRET_KEY_OPTION).required().hasArg().argName("secret")
            .desc("Sets the secret key to sign the request").build());
    opts.addOption(Option.builder().longOpt(BUCKET_OPTION).required().hasArg().argName("bucket-name")
            .desc("The bucket containing the object").build());
    opts.addOption(Option.builder().longOpt(KEY_OPTION).required().hasArg().argName("object-key")
            .desc("The object name (key) to access with the URL").build());
    opts.addOption(Option.builder().longOpt(EXPIRES_OPTION).hasArg().argName("minutes")
            .desc("Minutes from local time to expire the request.  1 day = 1440, 1 week=10080, "
                    + "1 month (30 days)=43200, 1 year=525600.  Defaults to 1 hour (60).")
            .build());//from   w  ww . j  a  v  a  2 s. c  o  m
    opts.addOption(Option.builder().longOpt(VERB_OPTION).hasArg().argName("http-verb").type(HttpMethod.class)
            .desc("The HTTP verb that will be used with the URL (PUT, GET, etc).  Defaults to GET.").build());
    opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPTION).hasArg().argName("mimetype")
            .desc("Sets the Content-Type header (e.g. image/jpeg) that will be used with the request.  "
                    + "Must match exactly.  Defaults to application/octet-stream for PUT/POST and "
                    + "null for all others")
            .build());

    DefaultParser dp = new DefaultParser();

    CommandLine cmd = null;
    try {
        cmd = dp.parse(opts, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar UploadUrlGenerator-xxx.jar", opts, true);
        System.exit(255);
    }

    URI endpoint = URI.create(cmd.getOptionValue(ENDPOINT_OPTION));
    String accessKey = cmd.getOptionValue(ACCESS_KEY_OPTION);
    String secretKey = cmd.getOptionValue(SECRET_KEY_OPTION);
    String bucket = cmd.getOptionValue(BUCKET_OPTION);
    String key = cmd.getOptionValue(KEY_OPTION);
    HttpMethod method = HttpMethod.GET;
    if (cmd.hasOption(VERB_OPTION)) {
        method = HttpMethod.valueOf(cmd.getOptionValue(VERB_OPTION).toUpperCase());
    }
    int expiresMinutes = 60;
    if (cmd.hasOption(EXPIRES_OPTION)) {
        expiresMinutes = Integer.parseInt(cmd.getOptionValue(EXPIRES_OPTION));
    }
    String contentType = null;
    if (method == HttpMethod.PUT || method == HttpMethod.POST) {
        contentType = "application/octet-stream";
    }

    if (cmd.hasOption(CONTENT_TYPE_OPTION)) {
        contentType = cmd.getOptionValue(CONTENT_TYPE_OPTION);
    }

    BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    ClientConfiguration cc = new ClientConfiguration();
    // Force use of v2 Signer.  ECS does not support v4 signatures yet.
    cc.setSignerOverride("S3SignerType");
    AmazonS3Client s3 = new AmazonS3Client(credentials, cc);
    s3.setEndpoint(endpoint.toString());
    S3ClientOptions s3c = new S3ClientOptions();
    s3c.setPathStyleAccess(true);
    s3.setS3ClientOptions(s3c);

    // Sign the URL
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, expiresMinutes);
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key).withExpiration(c.getTime())
            .withMethod(method);
    if (contentType != null) {
        req = req.withContentType(contentType);
    }
    URL u = s3.generatePresignedUrl(req);
    System.out.printf("URL: %s\n", u.toURI().toASCIIString());
    System.out.printf("HTTP Verb: %s\n", method);
    System.out.printf("Expires: %s\n", c.getTime());
    System.out.println("To Upload with curl:");

    StringBuilder sb = new StringBuilder();
    sb.append("curl ");

    if (method != HttpMethod.GET) {
        sb.append("-X ");
        sb.append(method.toString());
        sb.append(" ");
    }

    if (contentType != null) {
        sb.append("-H \"Content-Type: ");
        sb.append(contentType);
        sb.append("\" ");
    }

    if (method == HttpMethod.POST || method == HttpMethod.PUT) {
        sb.append("-T <filename> ");
    }

    sb.append("\"");
    sb.append(u.toURI().toASCIIString());
    sb.append("\"");

    System.out.println(sb.toString());

    System.exit(0);
}

From source file:frankhassanabad.com.github.Jasperize.java

/**
 * Main method to call through Java in order to take a LinkedInProfile on disk and load it.
 *
 * @param args command line arguments where the options are stored
 * @throws FileNotFoundException Thrown if any file its expecting cannot be found.
 * @throws JRException  If there's generic overall Jasper issues.
 * @throws ParseException If there's command line parsing issues.
 *///www  .  ja  v  a2 s. co  m
public static void main(String[] args) throws IOException, JRException, ParseException {

    Options options = new Options();
    options.addOption("h", "help", false, "Shows the help documentation");
    options.addOption("v", "version", false, "Shows the help documentation");
    options.addOption("cl", "coverLetter", false, "Utilizes a cover letter defined in coverletter.xml");
    options.addOption("sig", true, "Picture of your signature to add to the cover letter.");
    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Jasperize [OPTIONS] [InputJrxmlFile] [OutputExportFile]", options);
        System.exit(0);
    }
    if (cmd.hasOption("v")) {
        System.out.println("Version:" + version);
        System.exit(0);
    }
    boolean useCoverLetter = cmd.hasOption("cl");
    String signatureLocation = cmd.getOptionValue("sig");
    BufferedImage signatureImage = null;
    if (signatureLocation != null) {
        signatureImage = ImageIO.read(new File(signatureLocation));
        ;
    }

    @SuppressWarnings("unchecked")
    List<String> arguments = cmd.getArgList();

    final String jrxmlFile;
    final String jasperOutput;
    if (arguments.size() == 2) {
        jrxmlFile = arguments.get(0);
        jasperOutput = arguments.get(1);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else if (arguments.size() == 3) {
        jrxmlFile = arguments.get(1);
        jasperOutput = arguments.get(2);
        System.out.println("*Detected* the command line arguments of:");
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    } else {
        System.out.println("Using the default arguments of:");
        jrxmlFile = "data/jasperTemplates/resume1.jrxml";
        jasperOutput = "data/jasperOutput/linkedInResume.pdf";
        System.out.println("    [InputjrxmlFile] " + jrxmlFile);
        System.out.println("    [OutputExportFile] " + jasperOutput);
    }

    final String compiledMasterFile;
    final String outputType;
    final String jrPrintFile;
    //Split the inputFile
    final String[] inputSplit = jrxmlFile.split("\\.");
    if (inputSplit.length != 2 || !(inputSplit[1].equalsIgnoreCase("jrxml"))) {
        //Error
        System.out.println("Your [InputjrxmlFile] (1st argument) should have a jrxml extension like such:");
        System.out.println("    data/jasperTemplates/resume1.jrxml");
        System.exit(1);
    }
    //Split the outputFile
    final String[] outputSplit = jasperOutput.split("\\.");
    if (outputSplit.length != 2) {
        //Error
        System.out.println("Your [OutputExportFile] (2nd argument) should have a file extension like such:");
        System.out.println("    data/jasperOutput/linkedInResume.pdf");
        System.exit(1);
    }

    File inputFile = new File(inputSplit[0]);
    String inputFileName = inputFile.getName();
    String inputFileParentPath = inputFile.getParent();

    File outputFile = new File(outputSplit[0]);
    String outputFileParentPath = outputFile.getParent();

    System.out.println("Compiling report(s)");
    compileAllJrxmlTemplateFiles(inputFileParentPath, outputFileParentPath);
    System.out.println("Done compiling report(s)");

    compiledMasterFile = outputFileParentPath + File.separator + inputFileName + ".jasper";
    jrPrintFile = outputFileParentPath + File.separator + inputFileName + ".jrprint";

    System.out.println("Filling report: " + compiledMasterFile);
    Reporting.fill(compiledMasterFile, useCoverLetter, signatureImage);
    System.out.println("Done filling reports");
    outputType = outputSplit[1];
    System.out.println("Creating output export file of: " + jasperOutput);
    if (outputType.equalsIgnoreCase("pdf")) {
        Reporting.pdf(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("pptx")) {
        Reporting.pptx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("docx")) {
        Reporting.docx(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("odt")) {
        Reporting.odt(jrPrintFile, jasperOutput);
    }
    if (outputType.equalsIgnoreCase("xhtml")) {
        Reporting.xhtml(jrPrintFile, jasperOutput);
    }
    System.out.println("Done creating output export file of: " + jasperOutput);
}

From source file:com.ibm.zurich.Main.java

public static void main(String[] args) throws NoSuchAlgorithmException, IOException {
    Option help = new Option(HELP, "print this message");
    Option version = new Option(VERSION, "print the version information");

    Options options = new Options();

    Option useCurve = Option.builder(USECURVE).hasArg().argName("curve")
            .desc("Specify the BN Curve. Options: " + curveOptions()).build();
    Option isskeygen = Option.builder(IKEYGEN).numberOfArgs(3).argName("ipk><isk><RL")
            .desc("Generate Issuer key pair and empty revocation list and store it in files").build();
    Option join1 = Option.builder(JOIN1).numberOfArgs(3).argName("ipk><authsk><msg1")
            .desc("Create an authenticator secret key and perform the first step of the join protocol").build();
    Option join2 = Option.builder(JOIN2).numberOfArgs(4).argName("ipk><isk><msg1><msg2")
            .desc("Complete the join protocol").build();
    Option verify = Option.builder(VERIFY).numberOfArgs(5).argName("ipk><sig><krd><appId><RL")
            .desc("Verify a signature").build();
    Option sign = Option.builder(SIGN).numberOfArgs(6).argName("ipk><authsk><msg2><appId><krd><sig")
            .desc("create a signature").build();

    options.addOption(help);//from  w w  w  . j ava  2  s  . com
    options.addOption(version);
    options.addOption(useCurve);
    options.addOption(isskeygen);
    options.addOption(sign);
    options.addOption(verify);
    options.addOption(join1);
    options.addOption(join2);

    HelpFormatter formatter = new HelpFormatter();
    CommandLineParser parser = new DefaultParser();

    //FIXME Choose a proper instantiation of SecureRandom depending on the platform
    SecureRandom random = new SecureRandom();
    Base64.Encoder encoder = Base64.getUrlEncoder();
    Base64.Decoder decoder = Base64.getUrlDecoder();
    try {
        CommandLine line = parser.parse(options, args);
        BNCurveInstantiation instantiation = null;
        BNCurve curve = null;
        if (line.hasOption(HELP) || line.getOptions().length == 0) {
            formatter.printHelp(USAGE, options);
        } else if (line.hasOption(VERSION)) {
            System.out.println("Version " + Main.class.getPackage().getImplementationVersion());
        } else if (line.hasOption(USECURVE)) {
            instantiation = BNCurveInstantiation.valueOf(line.getOptionValue(USECURVE));
            curve = new BNCurve(instantiation);
        } else {
            System.out.println("Specify the curve to use.");
            return;
        }

        if (line.hasOption(IKEYGEN)) {
            String[] optionValues = line.getOptionValues(IKEYGEN);

            // Create secret key
            IssuerSecretKey sk = Issuer.createIssuerKey(curve, random);

            // Store pk
            writeToFile((new IssuerPublicKey(curve, sk, random)).toJSON(curve), optionValues[0]);

            // Store sk
            writeToFile(sk.toJson(curve), optionValues[1]);

            // Create empty revocation list and store
            HashSet<BigInteger> rl = new HashSet<BigInteger>();
            writeToFile(Verifier.revocationListToJson(rl, curve), optionValues[2]);
        } else if (line.hasOption(SIGN)) {
            //("ipk><authsk><msg2><appId><krd><sig")

            String[] optionValues = line.getOptionValues(SIGN);
            IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));

            BigInteger authsk = curve.bigIntegerFromB(decoder.decode(readFromFile(optionValues[1])));
            JoinMessage2 msg2 = new JoinMessage2(curve, readStringFromFile(optionValues[2]));

            // setup a new authenticator
            Authenticator auth = new Authenticator(curve, ipk, authsk);
            auth.EcDaaJoin1(curve.getRandomModOrder(random));
            if (auth.EcDaaJoin2(msg2)) {
                EcDaaSignature sig = auth.EcDaaSign(optionValues[3]);

                // Write krd to file
                writeToFile(sig.krd, optionValues[4]);

                // Write signature to file
                writeToFile(sig.encode(curve), optionValues[5]);

                System.out.println("Signature written to " + optionValues[5]);
            } else {
                System.out.println("JoinMsg2 invalid");
            }
        } else if (line.hasOption(VERIFY)) {
            Verifier ver = new Verifier(curve);
            String[] optionValues = line.getOptionValues(VERIFY);
            String pkFile = optionValues[0];
            String sigFile = optionValues[1];
            String krdFile = optionValues[2];
            String appId = optionValues[3];
            String rlPath = optionValues[4];
            byte[] krd = Files.readAllBytes(Paths.get(krdFile));
            IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(pkFile));
            EcDaaSignature sig = new EcDaaSignature(Files.readAllBytes(Paths.get(sigFile)), krd, curve);
            boolean valid = ver.verify(sig, appId, pk,
                    Verifier.revocationListFromJson(readStringFromFile(rlPath), curve));
            System.out.println("Signature is " + (valid ? "valid." : "invalid."));
        } else if (line.hasOption(JOIN1)) {
            String[] optionValues = line.getOptionValues(JOIN1);
            IssuerPublicKey ipk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));

            // Create authenticator key
            BigInteger sk = curve.getRandomModOrder(random);
            writeToFile(encoder.encodeToString(curve.bigIntegerToB(sk)), optionValues[1]);
            Authenticator auth = new Authenticator(curve, ipk, sk);
            JoinMessage1 msg1 = auth.EcDaaJoin1(curve.getRandomModOrder(random));
            writeToFile(msg1.toJson(curve), optionValues[2]);
        } else if (line.hasOption(JOIN2)) {
            String[] optionValues = line.getOptionValues(JOIN2);

            // create issuer with the specified key
            IssuerPublicKey pk = new IssuerPublicKey(curve, readStringFromFile(optionValues[0]));
            IssuerSecretKey sk = new IssuerSecretKey(curve, readStringFromFile(optionValues[1]));
            Issuer iss = new Issuer(curve, sk, pk);

            JoinMessage1 msg1 = new JoinMessage1(curve, readStringFromFile(optionValues[2]));

            // Note that we do not check for nonce freshness.
            JoinMessage2 msg2 = iss.EcDaaIssuerJoin(msg1, false);
            if (msg2 == null) {
                System.out.println("Join message invalid.");
            } else {
                System.out.println("Join message valid, msg2 written to file.");
                writeToFile(msg2.toJson(curve), optionValues[3]);
            }
        }
    } catch (ParseException e) {
        System.out.println("Error parsing input.");
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:io.personium.recovery.Recovery.java

/**
 * main.//from w  w w. j  ava2  s.c  o m
 * @param args 
 */
public static void main(String[] args) {
    loadProperties();
    Option optIndex = new Option("i", "index", true, "?");
    Option optProp = new Option("p", "prop", true, "");
    // t??????????????????????
    Option optType = new Option("t", "type", true, "??type");
    Option optClear = new Option("c", "clear", false,
            "???elasticsearch?");
    Option optReplicas = new Option("r", "replicas", true, "??");
    Option optVersion = new Option("v", "version", false, "??");
    // 
    // optIndex.setRequired(true);
    //        optProp.setRequired(true);
    Options options = new Options();
    options.addOption(optIndex);
    options.addOption(optProp);
    options.addOption(optType);
    options.addOption(optClear);
    options.addOption(optReplicas);
    options.addOption(optVersion);
    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args, true);
    } catch (ParseException e) {
        (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options);
        log.warn("Recovery failure");
        System.exit(1);
    }

    if (commandLine.hasOption("v")) {
        log.info("Version:" + versionNumber);
        System.exit(0);
    }
    if (!commandLine.hasOption("p")) {
        (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options);
        log.warn("Recovery failure");
        System.exit(1);
    }
    if (commandLine.hasOption("t")) {
        log.info("Command line option \"t\" or \"type\" is deprecated. Option ignored.");
    }
    if (!commandLine.hasOption("r")) {
        (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options);
        log.warn("Command line option \"r\" is required.");
        System.exit(1);
    }

    RecoveryManager recoveryManager = new RecoveryManager();
    // ??index
    recoveryManager.setIndexNames(commandLine.getOptionValue("i"));
    // elasticsearch
    recoveryManager.setClear(commandLine.hasOption("c"));

    // ??
    // 0 ?ES??????????int???????
    try {
        int replicas = Integer.parseInt(commandLine.getOptionValue("r"));
        if (replicas < 0) {
            log.warn("Command line option \"r\"'s value is not integer.");
            System.exit(1);
        }
        recoveryManager.setReplicas(replicas);
    } catch (NumberFormatException e) {
        log.warn("Command line option \"r\"'s value is not integer.");
        System.exit(1);
    }

    try {
        // Properties?
        Properties properties = new Properties();
        // ?
        properties.load(new FileInputStream(commandLine.getOptionValue("p")));
        if ((!properties.containsKey(ES_HOSTS)) || (!properties.containsKey(ES_CLUSTER_NAME))
                || (!properties.containsKey(ADS_JDBC_URL)) || (!properties.containsKey(ADS_JDBC_USER))
                || (!properties.containsKey(ADS_JDBC_PASSWORD)) || (!properties.containsKey(ES_ROUTING_FLAG))) {
            log.warn("properties file error");
            log.warn("Recovery failure");
            System.exit(1);
        } else {
            recoveryManager.setEsHosts(properties.getProperty(ES_HOSTS));
            recoveryManager.setEsClusetrName(properties.getProperty(ES_CLUSTER_NAME));
            recoveryManager.setAdsJdbcUrl(properties.getProperty(ADS_JDBC_URL));
            recoveryManager.setAdsUser(properties.getProperty(ADS_JDBC_USER));
            recoveryManager.setAdsPassword(properties.getProperty(ADS_JDBC_PASSWORD));
            recoveryManager.setExecuteCnt(properties.getProperty(EXECUTE_COUNT));
            recoveryManager.setCheckCount(properties.getProperty(CHECK_COUNT));
            recoveryManager.setUnitPrefix(properties.getProperty(UNIT_PREFIX));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        log.warn("properties file error");
        log.warn("Recovery failure");
        System.exit(1);
    } catch (IOException e) {
        e.printStackTrace();
        log.warn("properties file error");
        log.warn("Recovery failure");
        System.exit(1);
    }

    String[] indexList = recoveryManager.getIndexNames();
    boolean isClear = recoveryManager.isClear();
    if (isClear && (indexList != null && null != indexList[0])) {
        String ad = recoveryManager.getUnitPrefix() + "_" + EsIndex.CATEGORY_AD;
        if (Arrays.asList(indexList).contains(ad)) {
            log.warn("Cannot specify both -c and -i " + recoveryManager.getUnitPrefix() + "_ad option.");
            log.warn("Recovery failure");
            System.exit(1);
        }
    }

    // ??????
    try {
        LockUtility.lock();
    } catch (AlreadyStartedException e) {
        log.info("Recovery has already started");
        log.info("Recovery failure");
        return;
    } catch (Exception e) {
        log.error("Failed to get lock for the double start control");
        e.printStackTrace();
        LockUtility.release();
        log.error("Recovery failure");
        System.exit(1);
    }

    // ??
    try {
        recoveryManager.recovery();
    } catch (Exception e) {
        LockUtility.release();
        log.error("Recovery failure");
        System.exit(1);
    }
    LockUtility.release();
    log.info("Recovery Success");
    return;
}

From source file:com.cws.esolutions.core.main.SQLUtility.java

public static final void main(final String[] args) {
    final String methodName = SQLUtility.CNAME + "#main(final String[] args)";

    if (DEBUG) {//from  w  w w  .  ja v a 2s .  c om
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", (Object) args);
    }

    if (args.length == 0) {
        HelpFormatter usage = new HelpFormatter();
        usage.printHelp(SQLUtility.CNAME, options, true);

        return;
    }

    final String coreConfiguration = (StringUtils.isBlank(System.getProperty("coreConfigFile")))
            ? SQLUtility.CORE_SVC_CONFIG
            : System.getProperty("coreConfigFile");
    final String securityConfiguration = (StringUtils.isBlank(System.getProperty("secConfigFile")))
            ? SQLUtility.CORE_LOG_CONFIG
            : System.getProperty("secConfigFile");
    final String coreLogging = (StringUtils.isBlank(System.getProperty("coreLogConfig")))
            ? SQLUtility.SEC_SVC_CONFIG
            : System.getProperty("coreLogConfig");
    final String securityLogging = (StringUtils.isBlank(System.getProperty("secLogConfig")))
            ? SQLUtility.SEC_LOG_CONFIG
            : System.getProperty("secLogConfig");

    if (DEBUG) {
        DEBUGGER.debug("String coreConfiguration: {}", coreConfiguration);
        DEBUGGER.debug("String securityConfiguration: {}", securityConfiguration);
        DEBUGGER.debug("String coreLogging: {}", coreLogging);
        DEBUGGER.debug("String securityLogging: {}", securityLogging);
    }

    try {
        SecurityServiceInitializer.initializeService(securityConfiguration, securityLogging, false);
        CoreServiceInitializer.initializeService(coreConfiguration, coreLogging, false, true);
    } catch (CoreServiceException csx) {
        System.err
                .println("An error occurred while loading configuration data: " + csx.getCause().getMessage());

        System.exit(1);
    } catch (SecurityServiceException sx) {
        System.err.println("An error occurred while loading configuration data: " + sx.getCause().getMessage());

        System.exit(1);
    }

    Options options = new Options();

    try {
        throw new ParseException("nothing to see here");
    } catch (ParseException px) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(SQLUtility.CNAME, options, true);
    }
}