Example usage for org.apache.commons.cli Option getLongOpt

List of usage examples for org.apache.commons.cli Option getLongOpt

Introduction

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

Prototype

public String getLongOpt() 

Source Link

Document

Retrieve the long name of this Option.

Usage

From source file:eu.edisonproject.utility.execute.Main.java

public static void main(String args[]) {
    Options options = new Options();
    Option operation = new Option("op", "operation", true,
            "type of operation to perform. " + "To move cached terms from org.mapdb.DB 'm'");
    operation.setRequired(true);//  w ww  .  jav  a  2  s  .  co m
    options.addOption(operation);

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(true);
    options.addOption(input);

    String helpmasg = "Usage: \n";
    for (Object obj : options.getOptions()) {
        Option op = (Option) obj;
        helpmasg += op.getOpt() + ", " + op.getLongOpt() + "\t Required: " + op.isRequired() + "\t\t"
                + op.getDescription() + "\n";
    }

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

        switch (cmd.getOptionValue("operation")) {
        case "m":
            DBTools.portTermCache2Hbase(cmd.getOptionValue("input"));
            DBTools.portBabelNetCache2Hbase(cmd.getOptionValue("input"));
            break;
        default:
            System.out.println(helpmasg);
        }

    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, helpmasg, ex);
    }
}

From source file:glacierpipe.GlacierPipeMain.java

public static void main(String[] args) throws IOException, ParseException {
    CommandLineParser parser = new GnuParser();

    CommandLine cmd = parser.parse(OPTIONS, args);

    if (cmd.hasOption("help")) {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            printHelp(writer);/*ww w .  jav a  2 s.  co m*/
        }

        System.exit(0);
    } else if (cmd.hasOption("upload")) {

        // Turn the CommandLine into Properties
        Properties cliProperties = new Properties();
        for (Iterator<?> i = cmd.iterator(); i.hasNext();) {
            Option o = (Option) i.next();

            String opt = o.getLongOpt();
            opt = opt != null ? opt : o.getOpt();

            String value = o.getValue();
            value = value != null ? value : "";

            cliProperties.setProperty(opt, value);
        }

        // Build up a configuration
        ConfigBuilder configBuilder = new ConfigBuilder();

        // Archive name
        List<?> archiveList = cmd.getArgList();
        if (archiveList.size() > 1) {
            throw new ParseException("Too many arguments");
        } else if (archiveList.isEmpty()) {
            throw new ParseException("No archive name provided");
        }

        configBuilder.setArchive(archiveList.get(0).toString());

        // All other arguments on the command line
        configBuilder.setFromProperties(cliProperties);

        // Load any config from the properties file
        Properties fileProperties = new Properties();
        try (InputStream in = new FileInputStream(configBuilder.propertiesFile)) {
            fileProperties.load(in);
        } catch (IOException e) {
            System.err.printf("Warning: unable to read properties file %s; %s%n", configBuilder.propertiesFile,
                    e);
        }

        configBuilder.setFromProperties(fileProperties);

        // ...
        Config config = new Config(configBuilder);

        IOBuffer buffer = new MemoryIOBuffer(config.partSize);

        AmazonGlacierClient client = new AmazonGlacierClient(
                new BasicAWSCredentials(config.accessKey, config.secretKey));
        client.setEndpoint(config.endpoint);

        // Actual upload
        try (InputStream in = new BufferedInputStream(System.in, 4096);
                PrintWriter writer = new PrintWriter(System.err);
                ObservableProperties configMonitor = config.reloadProperties
                        ? new ObservableProperties(config.propertiesFile)
                        : null;
                ProxyingThrottlingStrategy throttlingStrategy = new ProxyingThrottlingStrategy(config);) {
            TerminalGlacierPipeObserver observer = new TerminalGlacierPipeObserver(writer);

            if (configMonitor != null) {
                configMonitor.registerObserver(throttlingStrategy);
            }

            GlacierPipe pipe = new GlacierPipe(buffer, observer, config.maxRetries, throttlingStrategy);
            pipe.pipe(client, config.vault, config.archive, in);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }

        System.exit(0);
    } else {
        try (PrintWriter writer = new PrintWriter(System.err)) {
            writer.println("No action specified.");
            printHelp(writer);
        }

        System.exit(-1);
    }
}

From source file:gpframework.RunExperiment.java

/**
 * Application's entry point.//  w  w  w  .  ja  v  a2 s. co  m
 * 
 * @param args
 * @throws ParseException
 * @throws ParameterException 
 */
public static void main(String[] args) throws ParseException, ParameterException {
    // Failsafe parameters
    if (args.length == 0) {
        args = new String[] { "-f", "LasSortednessFunction", "-n", "5", "-ff", "JoinFactory", "-tf",
                "SortingElementFactory", "-pf", "SortingProgramFactory", "-s", "SMOGPSelection", "-a", "SMOGP",
                "-t", "50", "-e", "1000000000", "-mf", "SingleMutationFactory", "-d", "-bn", "other" };
    }

    // Create options
    Options options = new Options();
    setupOptions(options);

    // Read options from the command line
    CommandLineParser parser = new PosixParser();
    CommandLine cmd;

    // Print help if parameter requirements are not met
    try {
        cmd = parser.parse(options, args);
    }

    // If some parameters are missing, print help
    catch (MissingOptionException e) {
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar GPFramework \n", options);
        System.out.println();
        System.out.println("Missing parameters: " + e.getMissingOptions());
        return;
    }

    // Re-initialize PRNG
    long seed = System.currentTimeMillis();
    Utils.random = new Random(seed);

    // Set the problem size
    int problemSize = Integer.parseInt(cmd.getOptionValue("n"));

    // Set debug mode and cluster mode
    Utils.debug = cmd.hasOption("d");
    RunExperiment.cluster = cmd.hasOption("c");

    // Initialize fitness function and some factories
    FitnessFunction fitnessFunction = fromName(cmd.getOptionValue("f"), problemSize);
    MutationFactory mutationFactory = fromName(cmd.getOptionValue("mf"));
    Selection selectionCriterion = fromName(cmd.getOptionValue("s"));
    FunctionFactory functionFactory = fromName(cmd.getOptionValue("ff"));
    TerminalFactory terminalFactory = fromName(cmd.getOptionValue("tf"), problemSize);
    ProgramFactory programFactory = fromName(cmd.getOptionValue("pf"), functionFactory, terminalFactory);

    // Initialize algorithm
    Algorithm algorithm = fromName(cmd.getOptionValue("a"), mutationFactory, selectionCriterion);
    algorithm.setParameter("evaluationsBudget", cmd.getOptionValue("e"));
    algorithm.setParameter("timeBudget", cmd.getOptionValue("t"));

    // Initialize problem
    Problem problem = new Problem(programFactory, fitnessFunction);
    Program solution = algorithm.solve(problem);

    Utils.debug("Population results: ");
    Utils.debug(algorithm.getPopulation().toString());
    Utils.debug(algorithm.getPopulation().parse());

    Map<String, Object> entry = new HashMap<String, Object>();

    // Copy algorithm setup
    for (Object o : options.getRequiredOptions()) {
        Option option = options.getOption(o.toString());
        entry.put(option.getLongOpt(), cmd.getOptionValue(option.getOpt()));
    }
    entry.put("seed", seed);

    // Copy results
    entry.put("bestProgram", solution.toString());
    entry.put("bestSolution", fitnessFunction.normalize(solution));

    // Copy all statistics
    entry.putAll(algorithm.getStatistics());

    Utils.debug("Maximum encountered population size: "
            + algorithm.getStatistics().get("maxPopulationSizeToCompleteFront"));
    Utils.debug("Maximum encountered tree size: "
            + algorithm.getStatistics().get("maxProgramComplexityToCompleteFront"));
    Utils.debug("Solution complexity: " + solution.complexity() + "/" + (2 * problemSize - 1));
}

From source file:com.sludev.mssqlapplylog.MSSQLApplyLogMain.java

public static void main(String[] args) {
    CommandLineParser parser = new DefaultParser();
    Options options = new Options();

    // Most of the following defaults should be changed in
    // the --conf or "conf.properties" file
    String sqlURL = null;/*w ww .j  ava2 s  .c  o m*/
    String sqlUser = null;
    String sqlPass = null;
    String sqlDb = null;
    String sqlHost = "127.0.0.1";
    String backupDirStr = null;
    String laterThanStr = "";
    String fullBackupPathStr = null;
    String fullBackupPatternStr = "(?:[\\w_-]+?)(\\d+)\\.bak";
    String fullBackupDatePatternStr = "yyyyMMddHHmm";
    String sqlProcessUser = null;
    String logBackupPatternStr = "(.*)\\.trn";
    String logBackupDatePatternStr = "yyyyMMddHHmmss";

    boolean doFullRestore = false;
    Boolean useLogFileLastMode = null;
    Boolean monitorLogBackupDir = null;

    options.addOption(Option.builder().longOpt("conf").desc("Configuration file.").hasArg().build());

    options.addOption(Option.builder().longOpt("laterthan").desc("'Later Than' file filter.").hasArg().build());

    options.addOption(Option.builder().longOpt("restore-full")
            .desc("Restore the full backup before continuing.").build());

    options.addOption(Option.builder().longOpt("use-lastmod")
            .desc("Sort/filter the log backups using their File-System 'Last Modified' date.").build());

    options.addOption(Option.builder().longOpt("monitor-backup-dir")
            .desc("Monitor the backup directory for new log backups, and apply them.").build());

    CommandLine line = null;
    try {
        try {
            line = parser.parse(options, args);
        } catch (ParseException ex) {
            throw new MSSQLApplyLogException(String.format("Error parsing command line.'%s'", ex.getMessage()),
                    ex);
        }

        String confFile = null;

        // Process the command line arguments
        Iterator cmdI = line.iterator();
        while (cmdI.hasNext()) {
            Option currOpt = (Option) cmdI.next();
            String currOptName = currOpt.getLongOpt();

            switch (currOptName) {
            case "conf":
                // Parse the configuration file
                confFile = currOpt.getValue();
                break;

            case "laterthan":
                // "Later Than" file date filter
                laterThanStr = currOpt.getValue();
                break;

            case "restore-full":
                // Do a full backup restore before restoring logs
                doFullRestore = true;
                break;

            case "monitor-backup-dir":
                // Monitor the backup directory for new logs
                monitorLogBackupDir = true;
                break;

            case "use-lastmod":
                // Use the last-modified date on Log Backup files for sorting/filtering
                useLogFileLastMode = true;
                break;
            }
        }

        Properties confProperties = null;

        if (StringUtils.isBlank(confFile) || Files.isReadable(Paths.get(confFile)) == false) {
            throw new MSSQLApplyLogException(
                    "Missing or unreadable configuration file.  Please specify --conf");
        } else {
            // Process the conf.properties file
            confProperties = new Properties();
            try {
                confProperties.load(Files.newBufferedReader(Paths.get(confFile)));
            } catch (IOException ex) {
                throw new MSSQLApplyLogException("Error loading properties file", ex);
            }

            sqlURL = confProperties.getProperty("sqlURL", "");
            sqlUser = confProperties.getProperty("sqlUser", "");
            sqlPass = confProperties.getProperty("sqlPass", "");
            sqlDb = confProperties.getProperty("sqlDb", "");
            sqlHost = confProperties.getProperty("sqlHost", "");
            backupDirStr = confProperties.getProperty("backupDir", "");

            if (StringUtils.isBlank(laterThanStr)) {
                laterThanStr = confProperties.getProperty("laterThan", "");
            }

            fullBackupPathStr = confProperties.getProperty("fullBackupPath", fullBackupPathStr);
            fullBackupPatternStr = confProperties.getProperty("fullBackupPattern", fullBackupPatternStr);
            fullBackupDatePatternStr = confProperties.getProperty("fullBackupDatePattern",
                    fullBackupDatePatternStr);
            sqlProcessUser = confProperties.getProperty("sqlProcessUser", "");

            logBackupPatternStr = confProperties.getProperty("logBackupPattern", logBackupPatternStr);
            logBackupDatePatternStr = confProperties.getProperty("logBackupDatePattern",
                    logBackupDatePatternStr);

            if (useLogFileLastMode == null) {
                String useLogFileLastModeStr = confProperties.getProperty("useLogFileLastMode", "false");
                useLogFileLastMode = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(useLogFileLastModeStr)));
            }

            if (monitorLogBackupDir == null) {
                String monitorBackupDirStr = confProperties.getProperty("monitorBackupDir", "false");
                monitorLogBackupDir = Boolean
                        .valueOf(StringUtils.lowerCase(StringUtils.trim(monitorBackupDirStr)));
            }
        }
    } catch (MSSQLApplyLogException ex) {
        try (StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw)) {
            pw.append(String.format("Error : '%s'\n\n", ex.getMessage()));

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(pw, 80, "\njava -jar mssqlapplylog.jar ",
                    "\nThe MSSQLApplyLog application can be used in a variety of options and modes.\n", options,
                    0, 2, " All Rights Reserved.", true);

            System.out.println(sw.toString());
        } catch (IOException iex) {
            LOGGER.debug("Error processing usage", iex);
        }

        System.exit(1);
    }

    MSSQLApplyLogConfig config = MSSQLApplyLogConfig.from(backupDirStr, fullBackupPathStr,
            fullBackupDatePatternStr, laterThanStr, fullBackupPatternStr, logBackupPatternStr,
            logBackupDatePatternStr, sqlHost, sqlDb, sqlUser, sqlPass, sqlURL, sqlProcessUser,
            useLogFileLastMode, doFullRestore, monitorLogBackupDir);

    MSSQLApplyLog logProc = MSSQLApplyLog.from(config);

    BasicThreadFactory thFactory = new BasicThreadFactory.Builder().namingPattern("restoreThread-%d").build();

    ExecutorService mainThreadExe = Executors.newSingleThreadExecutor(thFactory);

    Future<Integer> currRunTask = mainThreadExe.submit(logProc);

    mainThreadExe.shutdown();

    Integer resp = 0;
    try {
        resp = currRunTask.get();
    } catch (InterruptedException ex) {
        LOGGER.error("Application 'main' thread was interrupted", ex);
    } catch (ExecutionException ex) {
        LOGGER.error("Application 'main' thread execution error", ex);
    } finally {
        // If main leaves for any reason, shutdown all threads
        mainThreadExe.shutdownNow();
    }

    System.exit(resp);
}

From source file:eu.edisonproject.training.execute.Main.java

public static void main(String args[]) {
    Options options = new Options();
    Option operation = new Option("op", "operation", true,
            "type of operation to perform. " + "For term extraction use 'x'.\n"
                    + "Example: -op x -i E-COCO/documentation/sampleTextFiles/databases.txt "
                    + "-o E-COCO/documentation/sampleTextFiles/databaseTerms.csv"
                    + "For word sense disambiguation use 'w'.\n"
                    + "Example: -op w -i E-COCO/documentation/sampleTextFiles/databaseTerms.csv "
                    + "-o E-COCO/documentation/sampleTextFiles/databse.avro\n"
                    + "For tf-idf vector extraction use 't'.\n" + "For running the apriori algorithm use 'a'");
    operation.setRequired(true);//from w  ww  . ja v a 2  s  .c o m
    options.addOption(operation);

    Option input = new Option("i", "input", true, "input file path");
    input.setRequired(true);
    options.addOption(input);

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

    Option popertiesFile = new Option("p", "properties", true, "path for a properties file");
    popertiesFile.setRequired(false);
    options.addOption(popertiesFile);

    Option termsFile = new Option("t", "terms", true, "terms file");
    termsFile.setRequired(false);
    options.addOption(termsFile);

    String helpmasg = "Usage: \n";
    for (Object obj : options.getOptions()) {
        Option op = (Option) obj;
        helpmasg += op.getOpt() + ", " + op.getLongOpt() + "\t Required: " + op.isRequired() + "\t\t"
                + op.getDescription() + "\n";
    }

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

        String propPath = cmd.getOptionValue("properties");
        if (propPath == null) {
            prop = ConfigHelper
                    .getProperties(".." + File.separator + "etc" + File.separator + "configure.properties");
        } else {
            prop = ConfigHelper.getProperties(propPath);
        }
        //            ${user.home}

        switch (cmd.getOptionValue("operation")) {
        case "x":
            termExtraction(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        case "w":
            wsd(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        case "t":
            calculateTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        //                case "tt":
        //                    calculateTermTFIDF(cmd.getOptionValue("input"), cmd.getOptionValue("terms"), cmd.getOptionValue("output"));
        //                    break;
        case "a":
            apriori(cmd.getOptionValue("input"), cmd.getOptionValue("output"));
            break;
        default:
            System.out.println(helpmasg);
        }

    } catch (Exception ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, helpmasg, ex);
    }
}

From source file:edu.cwru.jpdg.JPDG.java

public static void main(String[] argv) throws pDG_Builder.Error {
    final Option helpOpt = new Option("h", "help", false, "print this message");
    final Option outputOpt = new Option("o", "output", true, "output file location");
    final Option baseOpt = new Option("b", "base-dir", true, "base directory to analyze");
    final Option excludeOpt = new Option("e", "exclude", true, "exclude these directories");
    final Option classOpt = new Option("c", "classpath", true, "classpath for soot");
    final Option labelOpt = new Option("l", "label-type", true,
            "label type, valid choices are: expr-tree, inst");
    final org.apache.commons.cli.Options options = new org.apache.commons.cli.Options();

    options.addOption(helpOpt);//  w w w  .  j a  va2s .  c  o m
    options.addOption(outputOpt);
    options.addOption(baseOpt);
    options.addOption(classOpt);
    options.addOption(labelOpt);
    options.addOption(excludeOpt);

    String cp = null;
    String base_dir = null;
    String label_type = "expr-tree";
    String output_file = null;
    List<String> excluded = new ArrayList<String>();

    try {
        GnuParser parser = new GnuParser();
        CommandLine line = parser.parse(options, argv);

        if (line.hasOption(helpOpt.getLongOpt())) {
            Usage(options);
        }

        cp = line.getOptionValue(classOpt.getLongOpt());
        base_dir = line.getOptionValue(baseOpt.getLongOpt());
        label_type = line.getOptionValue(labelOpt.getLongOpt());
        output_file = line.getOptionValue(outputOpt.getLongOpt());
        String[] ex = line.getOptionValues(excludeOpt.getLongOpt());
        if (ex != null) {
            excluded = Arrays.asList(ex);
        }
    } catch (final MissingOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final UnrecognizedOptionException e) {
        System.err.println(e.getMessage());
        Usage(options);
    } catch (final ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    List<String> dirs = new ArrayList<String>();
    dirs.add(base_dir);

    soot.Scene S = runSoot(cp, dirs, excluded);
    writeGraph(build_PDG(S, excluded, label_type), output_file);
}

From source file:de.onyxbits.raccoon.cli.Router.java

public static void main(String[] args) {
    Options options = new Options();

    Option property = Option.builder("D").argName("property=value").numberOfArgs(2).valueSeparator()
            .desc(Messages.getString(DESC + "D")).build();
    options.addOption(property);/*from w ww.jav a  2  s .c o m*/

    Option help = new Option("h", "help", false, Messages.getString(DESC + "h"));
    options.addOption(help);

    Option version = new Option("v", "version", false, Messages.getString(DESC + "v"));
    options.addOption(version);

    // GPA: Google Play Apps (we might add different markets later)
    Option playAppDetails = new Option(null, "gpa-details", true, Messages.getString(DESC + "gpa-details"));
    playAppDetails.setArgName("package");
    options.addOption(playAppDetails);

    Option playAppBulkDetails = new Option(null, "gpa-bulkdetails", true,
            Messages.getString(DESC + "gpa-bulkdetails"));
    playAppBulkDetails.setArgName("file");
    options.addOption(playAppBulkDetails);

    Option playAppBatchDetails = new Option(null, "gpa-batchdetails", true,
            Messages.getString(DESC + "gpa-batchdetails"));
    playAppBatchDetails.setArgName("file");
    options.addOption(playAppBatchDetails);

    Option playAppSearch = new Option(null, "gpa-search", true, Messages.getString(DESC + "gpa-search"));
    playAppSearch.setArgName("query");
    options.addOption(playAppSearch);

    CommandLine commandLine = null;
    try {
        commandLine = new DefaultParser().parse(options, args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }

    if (commandLine.hasOption(property.getOpt())) {
        System.getProperties().putAll(commandLine.getOptionProperties(property.getOpt()));
    }

    if (commandLine.hasOption(help.getOpt())) {
        new HelpFormatter().printHelp("raccoon", Messages.getString("header"), options,
                Messages.getString("footer"), true);
        System.exit(0);
    }

    if (commandLine.hasOption(version.getOpt())) {
        System.out.println(GlobalsProvider.getGlobals().get(Version.class));
        System.exit(0);
    }

    if (commandLine.hasOption(playAppDetails.getLongOpt())) {
        Play.details(commandLine.getOptionValue(playAppDetails.getLongOpt()));
        System.exit(0);
    }

    if (commandLine.hasOption(playAppBulkDetails.getLongOpt())) {
        Play.bulkDetails(new File(commandLine.getOptionValue(playAppBulkDetails.getLongOpt())));
        System.exit(0);
    }

    if (commandLine.hasOption(playAppBatchDetails.getLongOpt())) {
        Play.details(new File(commandLine.getOptionValue(playAppBatchDetails.getLongOpt())));
        System.exit(0);
    }

    if (commandLine.hasOption(playAppSearch.getLongOpt())) {
        Play.search(commandLine.getOptionValue(playAppSearch.getLongOpt()));
        System.exit(0);
    }
}

From source file:gobblin.runtime.util.JobStateToJsonConverter.java

@SuppressWarnings("all")
public static void main(String[] args) throws Exception {
    Option sysConfigOption = Option.builder("sc").argName("system configuration file")
            .desc("Gobblin system configuration file").longOpt("sysconfig").hasArgs().build();
    Option storeUrlOption = Option.builder("u").argName("gobblin state store URL")
            .desc("Gobblin state store root path URL").longOpt("storeurl").hasArgs().required().build();
    Option jobNameOption = Option.builder("n").argName("gobblin job name").desc("Gobblin job name")
            .longOpt("name").hasArgs().required().build();
    Option jobIdOption = Option.builder("i").argName("gobblin job id").desc("Gobblin job id").longOpt("id")
            .hasArgs().build();/*from ww w  .  j a  v  a2s.co  m*/
    Option convertAllOption = Option.builder("a")
            .desc("Whether to convert all past job states of the given job").longOpt("all").build();
    Option keepConfigOption = Option.builder("kc").desc("Whether to keep all configuration properties")
            .longOpt("keepConfig").build();
    Option outputToFile = Option.builder("t").argName("output file name").desc("Output file name")
            .longOpt("toFile").hasArgs().build();

    Options options = new Options();
    options.addOption(sysConfigOption);
    options.addOption(storeUrlOption);
    options.addOption(jobNameOption);
    options.addOption(jobIdOption);
    options.addOption(convertAllOption);
    options.addOption(keepConfigOption);
    options.addOption(outputToFile);

    CommandLine cmd = null;
    try {
        CommandLineParser parser = new DefaultParser();
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("JobStateToJsonConverter", options);
        System.exit(1);
    }

    Properties sysConfig = new Properties();
    if (cmd.hasOption(sysConfigOption.getLongOpt())) {
        sysConfig = JobConfigurationUtils.fileToProperties(cmd.getOptionValue(sysConfigOption.getLongOpt()));
    }

    JobStateToJsonConverter converter = new JobStateToJsonConverter(sysConfig, cmd.getOptionValue('u'),
            cmd.hasOption("kc"));
    StringWriter stringWriter = new StringWriter();
    if (cmd.hasOption('i')) {
        converter.convert(cmd.getOptionValue('n'), cmd.getOptionValue('i'), stringWriter);
    } else {
        if (cmd.hasOption('a')) {
            converter.convertAll(cmd.getOptionValue('n'), stringWriter);
        } else {
            converter.convert(cmd.getOptionValue('n'), stringWriter);
        }
    }

    if (cmd.hasOption('t')) {
        Closer closer = Closer.create();
        try {
            FileOutputStream fileOutputStream = closer.register(new FileOutputStream(cmd.getOptionValue('t')));
            OutputStreamWriter outputStreamWriter = closer.register(
                    new OutputStreamWriter(fileOutputStream, ConfigurationKeys.DEFAULT_CHARSET_ENCODING));
            BufferedWriter bufferedWriter = closer.register(new BufferedWriter(outputStreamWriter));
            bufferedWriter.write(stringWriter.toString());
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    } else {
        System.out.println(stringWriter.toString());
    }
}

From source file:com.nextdoor.bender.Bender.java

/**
 * Main entrypoint for the Bender CLI tool - handles the argument parsing and triggers the
 * appropriate methods for ultimately invoking a Bender Handler.
 *
 * @param args/*from ww  w.  j a  v a  2s .  com*/
 * @throws ParseException
 */
public static void main(String[] args) throws ParseException {

    /*
     * Create the various types of options that we support
     */
    Option help = Option.builder("H").longOpt("help").desc("Print this message").build();
    Option handler = Option.builder("h").longOpt("handler").hasArg()
            .desc("Which Event Handler do you want to simulate? \n"
                    + "Your options are: KinesisHandler, S3Handler. \n" + "Default: KinesisHandler")
            .build();
    Option source_file = Option.builder("s").longOpt("source_file").required().hasArg()
            .desc("Reference to the file that you want to process. Usage depends "
                    + "on the Handler you chose. If you chose KinesisHandler "
                    + "then this is a local file (file://path/to/file). If you chose "
                    + "S3Handler, then this is the path to the file in S3 that you want to process "
                    + "(s3://bucket/file...)")
            .build();
    Option kinesis_stream_name = Option.builder().longOpt("kinesis_stream_name").hasArg()
            .desc("What stream name should we mimic? " + "Default: " + KINESIS_STREAM_NAME
                    + " (Kinesis Handler Only)")
            .build();

    /*
     * Build out the option handler and parse the options
     */
    Options options = new Options();
    options.addOption(help);
    options.addOption(handler);
    options.addOption(kinesis_stream_name);
    options.addOption(source_file);

    /*
     * Prepare our help formatter
     */
    HelpFormatter formatter = new HelpFormatter();
    formatter.setWidth(100);
    formatter.setSyntaxPrefix("usage: BENDER_CONFIG=file://config.yaml java -jar");

    /*
     * Parse the options themselves. Throw an error and help if necessary.
     */
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;

    try {
        cmd = parser.parse(options, args);
    } catch (UnrecognizedOptionException | MissingOptionException | MissingArgumentException e) {
        logger.error(e.getMessage());
        formatter.printHelp(name, options);
        System.exit(1);
    }

    /*
     * The CLI tool doesn't have any configuration files built into it. We require that the user set
     * BENDER_CONFIG to something reasonable.
     */
    if (System.getenv("BENDER_CONFIG") == null) {
        logger.error("You must set the BENDER_CONFIG environment variable. \n"
                + "Valid options include: file://<file>");
        formatter.printHelp(name, options);
        System.exit(1);
    }

    if (cmd.hasOption("help")) {
        formatter.printHelp(name, options);
        System.exit(0);
    }

    /*
     * Depending on the desired Handler, we invoke a specific method and pass in the options (or
     * defaults) required for that handler.
     */
    String handler_value = cmd.getOptionValue(handler.getLongOpt(), KINESIS);
    try {

        switch (handler_value.toLowerCase()) {

        case KINESIS:
            invokeKinesisHandler(cmd.getOptionValue(kinesis_stream_name.getLongOpt(), KINESIS_STREAM_NAME),
                    cmd.getOptionValue(source_file.getLongOpt()));
            break;

        case S3:
            invokeS3Handler(cmd.getOptionValue(source_file.getLongOpt()));
            break;

        /*
         * Error out if an invalid handler was supplied.
         */
        default:
            logger.error("Invalid Handler Option (" + handler_value + "), valid options are: " + KINESIS);
            formatter.printHelp(name, options);
            System.exit(1);
        }
    } catch (HandlerException e) {
        logger.error("Error executing handler: " + e);
        System.exit(1);
    }
}

From source file:de.topobyte.utilities.apache.commons.cli.OptionUtil.java

/**
 * This method provides the same functionality as the {@link Option}'s
 * {@code getKey()} method, which has package private visibility however. It
 * returns {@link Option#getOpt()} if the return value of that method is
 * non-null and {@link Option#getLongOpt()} otherwise.
 * /*w ww  . j  av a 2  s  .co m*/
 * @param option
 *            the option to get the key for.
 */
public static String getKey(Option option) {
    String opt = option.getOpt();
    return opt != null ? opt : option.getLongOpt();
}