Example usage for org.apache.commons.cli BasicParser BasicParser

List of usage examples for org.apache.commons.cli BasicParser BasicParser

Introduction

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

Prototype

BasicParser

Source Link

Usage

From source file:com.adobe.aem.demomachine.Base64Encoder.java

public static void main(String[] args) throws IOException {

    String value = null;//from   w  w  w  . ja  v a  2  s  .  c  om

    // Command line options for this tool
    Options options = new Options();
    options.addOption("v", true, "Value");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("v")) {
            value = cmd.getOptionValue("v");
        }

        if (value == null) {
            System.out.println("Command line parameters: -v value");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    byte[] encodedBytes = Base64.encodeBase64(value.getBytes());
    System.out.println(new String(encodedBytes));

}

From source file:com.ikanow.infinit.e.utility.MongoIndexerMain.java

/**
 * This is just a placeholder to invoke MongoDocumentTxfer, MongoEventFeatureTxfer, or MongoEntityFeatureTxfer
 * @param args//from  ww w. j ava2 s  .co  m
 * @throws ParseException 
 * @throws MongoException 
 * @throws NumberFormatException 
 * @throws IOException 
 */

public static void main(String[] args) {

    try {
        CommandLineParser cliParser = new BasicParser();
        Options allOps = new Options();
        // Fork
        allOps.addOption("d", "doc", false, "Document transfer");
        allOps.addOption("n", "entity", false, "Entity feature transfer");
        allOps.addOption("a", "assoc", false, "Association feature transfer");
        allOps.addOption("A", "associations", false, "Association feature transfer");
        // Common
        allOps.addOption("q", "query", true, "MongoDB query to select records to transfer");
        allOps.addOption("D", "delete", false,
                "Delete the records in both MongoDB and Elasticsearch (instead of transferring them)");
        allOps.addOption("c", "config", true, "Override the default config path");
        allOps.addOption("l", "limit", true, "Caps the number of records to act upon");
        allOps.addOption("s", "skip", true, "The record at which to start (not in delete mode)");
        allOps.addOption("r", "rebuild", false, "Rebuild the index before transferring");
        allOps.addOption("v", "verify", false,
                "Verifies the document indexes all exist | resync the entity frequencies (INTERNAL ONLY)");
        allOps.addOption("f", "features", false,
                "Updates features present in the queried documents (--doc only; INTERNAL ONLY)");
        allOps.addOption("C", "chunks", true,
                "Loop over chunks, '--chunks all' for all chunks, '--chunks A,B,..' for specific chunks, '--chunks +A' for all chunks after A (currently -doc only)");

        CommandLine cliOpts = cliParser.parse(allOps, args);

        //Set up common parameters

        String configOverride = null;
        String query = null;
        String chunksDescription = null;
        boolean bDelete = false;
        boolean bRebuildIndex = false;
        boolean bVerifyIndex = false;
        boolean bUpdateFeatures = false;
        int nLimit = 0;
        int nSkip = 0;
        if (cliOpts.hasOption("config")) {
            configOverride = (String) cliOpts.getOptionValue("config");
        }
        if (cliOpts.hasOption("query")) {
            query = (String) cliOpts.getOptionValue("query");
        }
        if (cliOpts.hasOption("delete")) {
            bDelete = true;
        }
        if (cliOpts.hasOption("limit")) {
            try {
                nLimit = Integer.parseInt((String) cliOpts.getOptionValue("limit"));
            } catch (Exception e) {
                System.out.println("Error parsing --limit: " + (String) cliOpts.getOptionValue("limit"));
                query = null; // exit in if clause below
            }
        }
        if (cliOpts.hasOption("skip")) {
            try {
                nSkip = Integer.parseInt((String) cliOpts.getOptionValue("skip"));
            } catch (Exception e) {
                System.out.println("Error parsing --skip: " + (String) cliOpts.getOptionValue("skip"));
                query = null; // exit in if clause below
            }
        }
        if (cliOpts.hasOption("rebuild")) {
            bRebuildIndex = true;
        }
        if (cliOpts.hasOption("features")) {
            bUpdateFeatures = true;
        }
        if (cliOpts.hasOption("verify")) {
            if (cliOpts.hasOption("doc") && !bRebuildIndex) {
                bVerifyIndex = true; // (doc only)
            } else if (cliOpts.hasOption("entity")) {
                bVerifyIndex = true; // (ents only)               
            }
        }
        if (cliOpts.hasOption("chunks")) {
            if (bDelete) {
                System.out.println("Can't specify --chunks in conjunction with --delete");
                query = null; // exit in if clause below
            } else if ((nSkip != 0) || (nLimit != 0)) {
                System.out.println("Can't specify --chunks in conjunction with --skip or --limit");
                query = null; // exit in if clause below
            }
            chunksDescription = (String) cliOpts.getOptionValue("chunks");
        }
        if ((0 == args.length)
                || ((null == query) && (0 == nLimit) && !bVerifyIndex && (null == chunksDescription))) {
            System.out.println(
                    "Usage: MongoIndexerMain --doc|--assoc|--entity [--rebuild] [--verify] [--query <query>] [--chunks all|<chunklist>|+<chunk>] [--config <path>] [--delete] [--skip <start record>] [--limit <max records>]");
            if (args.length > 0) {
                System.out.println(
                        "(Note you must either specify a limit or a query or chunks - the query can be {} to get all records)");
            }
            System.exit(-1);
        }

        // Invoke appropriate manager to perform processing

        if (cliOpts.hasOption("doc")) {
            MongoDocumentTxfer.main(configOverride, query, bDelete, bRebuildIndex, bVerifyIndex,
                    bUpdateFeatures, nSkip, nLimit, chunksDescription);
        } else if (cliOpts.hasOption("assoc") || cliOpts.hasOption("association")) {
            MongoAssociationFeatureTxfer.main(configOverride, query, bDelete, bRebuildIndex, nSkip, nLimit,
                    chunksDescription);
        } else if (cliOpts.hasOption("entity")) {
            if (bVerifyIndex) {
                String[] dbDotColl = query.split("\\.");
                MongoEntitySyncFreq.syncFreq(dbDotColl[0], dbDotColl[1], configOverride);
            } else {
                MongoEntityFeatureTxfer.main(configOverride, query, bDelete, bRebuildIndex, nSkip, nLimit,
                        chunksDescription);
            }
        } else {
            System.out.println(
                    "Usage: MongoIndexerMain --doc|--assoc|--entity [--rebuild] [--query <query>] [--config <path>] [--delete] [--skip <start record>] [--limit <max records>]");
            System.exit(-1);
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

From source file:com.floreantpos.main.Main.java

/**
 * @param args/*from  w  ww.j  a  v  a2 s. co m*/
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(DEVELOPMENT_MODE, true, "State if this is developmentMode"); //$NON-NLS-1$
    CommandLineParser parser = new BasicParser();
    CommandLine commandLine = parser.parse(options, args);
    String optionValue = commandLine.getOptionValue(DEVELOPMENT_MODE);
    Locale defaultLocale = TerminalConfig.getDefaultLocale();
    if (defaultLocale != null) {
        Locale.setDefault(defaultLocale);
    }

    Application application = Application.getInstance();

    if (optionValue != null) {
        application.setDevelopmentMode(Boolean.valueOf(optionValue));
    }

    application.start();
}

From source file:it.iit.genomics.cru.genomics.misc.apps.Vcf2tabApp.java

public static void main(String[] args) throws IOException, ParseException {

    Options options = new Options();

    Option helpOpt = new Option("help", "print this message.");
    options.addOption(helpOpt);// w ww. ja  v a  2 s.c  o  m

    Option option1 = new Option("f", "filename", true, "VCF file to load");
    option1.setRequired(true);
    options.addOption(option1);

    option1 = new Option("o", "outputfile", true, "outputfilene");
    option1.setRequired(true);
    options.addOption(option1);

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

    try {
        // parse the command line arguments
        cmd = parser.parse(options, args, true);
    } catch (ParseException exp) {
        displayUsage("vcf2tab", options);
        System.exit(1);
    }
    if (cmd.hasOption("help")) {
        displayUsage("vcf2tab", options);
        System.exit(0);
    }

    String filename = cmd.getOptionValue("f");
    String outputfilename = cmd.getOptionValue("o");

    Vcf2tab loader = new Vcf2tab();

    loader.file2tab(filename, outputfilename); //(args[0]);

}

From source file:com.sr.eb.compiler.Main.java

public static void main(String[] args) throws Throwable {
    try {/*  w  w w. j ava  2 s  .c o  m*/
        Options options = new Options();

        options.addOption("v", "verbose", false, "Enables verbose compiler output.");
        options.addOption("ee", "easterEgg", false, "Enables compiler easter eggs, DO NOT USE!");

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

        if (cmd.getArgs().length > 0) {
            int start = -1;
            while (true) {
                start++;
                if (options.getOption(cmd.getArgs()[start]) == null)
                    break;
            }

            String[] sourceFiles = Arrays.copyOfRange(cmd.getArgs(), start, cmd.getArgs().length);

            // TODO
        } else {
            System.out.println("Expected source files, got none!");
            System.out.println("Usage: ebc [options] <source files>");
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    /* ----- Testing ----- */
    Lexer lexer = Lexer.newInstance();
    Parser parser = Parser.newInstance();

    try (InputStream in = new FileInputStream("test.eb")) {
        lexer.reset(Utils.readAll(in));
    }

    List<Token> tokens = lexer.tokenize();
    parser.reset(tokens);
    SyntaxTree t = parser.parse();

    ASTPrettyPrinter.print(t);
}

From source file:it.polimi.tower4clouds.rules.batch.BatchTool.java

public static void main(String[] args) {
    Options options = buildOptions();//  w w w.  ja v  a  2s  .  c o  m
    CommandLineParser parser = new BasicParser();
    HelpFormatter formatter = new HelpFormatter();
    FileInputStream inputFile = null;
    try {
        // parse the command line arguments
        CommandLine cmd = parser.parse(options, args);
        if (cmd.getOptions().length != 1) {
            System.err.println("Parsing failed: Reason: one and only one option is required");
            formatter.printHelp("qos-models", options);
        } else if (cmd.hasOption("h")) {
            formatter.printHelp("qos-models", options);
        } else if (cmd.hasOption("v")) {
            String file = cmd.getOptionValue("v");
            inputFile = new FileInputStream(file);
            MonitoringRules rules = XMLHelper.deserialize(inputFile, MonitoringRules.class);
            RulesValidator validator = new RulesValidator();
            Set<Problem> problems = validator.validateAllRules(rules);
            printResult(problems);
        } else if (cmd.hasOption("c")) {
            String file = cmd.getOptionValue("c");
            inputFile = new FileInputStream(file);
            Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class);
            QoSValidator validator = new QoSValidator();
            Set<Problem> problems = validator.validateAllConstraints(constraints);
            printResult(problems);
        } else if (cmd.hasOption("r")) {
            String file = cmd.getOptionValue("r");
            inputFile = new FileInputStream(file);
            Constraints constraints = XMLHelper.deserialize(inputFile, Constraints.class);
            MonitoringRuleFactory factory = new MonitoringRuleFactory();
            MonitoringRules rules = factory.makeRulesFromQoSConstraints(constraints);
            XMLHelper.serialize(rules, System.out);
        }
    } catch (ParseException e) {
        System.err.println("Parsing failed.  Reason: " + e.getMessage());
        formatter.printHelp("qos-models", options);
    } catch (FileNotFoundException e) {
        System.err.println("Could not locate input file: " + e.getMessage());
    } catch (JAXBException | SAXException e) {
        System.err.println("Input file could not be parsed: ");
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println("Unknown error: ");
        e.printStackTrace();
    } finally {
        if (inputFile != null) {
            try {
                inputFile.close();
            } catch (IOException e) {
            }
        }
    }
}

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);//  ww  w  .jav  a2 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:com.adobe.aem.demomachine.Checksums.java

public static void main(String[] args) {

    String rootFolder = null;//from w w  w.j av  a 2 s. c om

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();
    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String md5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]), false);
                logger.debug("MD5 is: " + md5);
                md5properties.setProperty("demo.path." + path[0], path[1]);
                md5properties.setProperty("demo.md5." + path[0], md5);
            } else {
                logger.error("Folder cannot be found");
            }
        }
    }

    File md5 = new File(rootFolder + File.separator + "conf" + File.separator + "checksums.properties");
    try {

        @SuppressWarnings("serial")
        Properties tmpProperties = new Properties() {
            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<Object>(super.keySet()));
            }
        };
        tmpProperties.putAll(md5properties);
        tmpProperties.store(new FileOutputStream(md5), null);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }

    System.out.println("MD5 checkums generated");

}

From source file:com.adobe.aem.demomachine.Updates.java

public static void main(String[] args) {

    String rootFolder = null;//from   w  w w . j  a v a  2s .  c  o  m

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();

    try {
        URL url = new URL(
                "https://raw.githubusercontent.com/Adobe-Marketing-Cloud/aem-demo-machine/master/conf/checksums.properties");
        InputStream in = url.openStream();
        Reader reader = new InputStreamReader(in, "UTF-8");
        md5properties.load(reader);
        reader.close();
    } catch (Exception e) {
        System.out.println("Error: Cannot connect to GitHub.com to check for updates");
        System.exit(-1);
    }

    System.out.println(AemDemoConstants.HR);

    int nbUpdateAvailable = 0;

    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String newMd5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]),
                        false);
                logger.debug("MD5 is: " + newMd5);
                String oldMd5 = md5properties.getProperty("demo.md5." + path[0]);
                if (oldMd5 == null || oldMd5.length() == 0) {
                    logger.error("Cannot find MD5 for " + path[0]);
                    System.out.println(path[2] + " : Cannot find M5 checksum");
                    continue;
                }
                if (newMd5.equals(oldMd5)) {
                    continue;
                } else {
                    System.out.println(path[2] + " : New update available"
                            + (path[0].equals("0") ? " (use 'git pull' to get the latest changes)" : ""));
                    nbUpdateAvailable++;
                }
            } else {
                System.out.println(path[2] + " : Not installed");
            }
        }
    }

    if (nbUpdateAvailable == 0) {
        System.out.println("Your AEM Demo Machine is up to date!");
    }

    System.out.println(AemDemoConstants.HR);

}

From source file:demo.learn.shiro.tool.PasswordEncryptionTool.java

/**
 * Main method.// w w w . j  a  v a 2s  . co  m
 * @param args Requires a plain text password.
 */
@SuppressWarnings("static-access")
public static void main(String[] args) {
    String plainTextPassword = "root";

    Option p = OptionBuilder.withArgName("password").hasArg().withDescription("plain text password")
            .isRequired(false).create('p');

    Options options = new Options();
    options.addOption(p);

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

        if (cmd.hasOption("p")) {
            plainTextPassword = cmd.getOptionValue("p");
        }
    } catch (ParseException pe) {
        String cmdLineSyntax = "java -cp %CLASSPATH% demo.learn.shiro.tool.PasswordEncryptionTool";
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(cmdLineSyntax, options, false);
        return;
    }

    final RandomNumberGenerator rng = new SecureRandomNumberGenerator();

    final ByteSource salt = rng.nextBytes();
    final String saltBase64 = Base64.encodeToString(salt.getBytes());
    final String hashedPasswordBase64 = new Sha256Hash(plainTextPassword, salt, S.HASH_ITER).toBase64();

    System.out.print("-p " + plainTextPassword);
    System.out.print(" -h " + hashedPasswordBase64);
    System.out.println(" -s " + saltBase64);
}