Example usage for org.apache.commons.cli CommandLine getOptionValues

List of usage examples for org.apache.commons.cli CommandLine getOptionValues

Introduction

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

Prototype

public String[] getOptionValues(char opt) 

Source Link

Document

Retrieves the array of values, if any, of an option.

Usage

From source file:com.example.dlp.RiskAnalysis.java

/**
 * Command line application to perform risk analysis using the Data Loss Prevention API.
 * Supported data format: BigQuery tables
 *//*from   w  ww. j a  va2 s .com*/
public static void main(String[] args) throws Exception {

    OptionGroup optionsGroup = new OptionGroup();
    optionsGroup.setRequired(true);

    Option numericalAnalysisOption = new Option("n", "numerical");
    optionsGroup.addOption(numericalAnalysisOption);

    Option categoricalAnalysisOption = new Option("c", "categorical");
    optionsGroup.addOption(categoricalAnalysisOption);

    Option kanonymityOption = new Option("k", "kAnonymity");
    optionsGroup.addOption(kanonymityOption);

    Option ldiversityOption = new Option("l", "lDiversity");
    optionsGroup.addOption(ldiversityOption);

    Options commandLineOptions = new Options();
    commandLineOptions.addOptionGroup(optionsGroup);

    Option datasetIdOption = Option.builder("datasetId").hasArg(true).required(false).build();
    commandLineOptions.addOption(datasetIdOption);

    Option tableIdOption = Option.builder("tableId").hasArg(true).required(false).build();
    commandLineOptions.addOption(tableIdOption);

    Option projectIdOption = Option.builder("projectId").hasArg(true).required(false).build();
    commandLineOptions.addOption(projectIdOption);

    Option columnNameOption = Option.builder("columnName").hasArg(true).required(false).build();
    commandLineOptions.addOption(columnNameOption);

    Option sensitiveAttributeOption = Option.builder("sensitiveAttribute").hasArg(true).required(false).build();
    commandLineOptions.addOption(sensitiveAttributeOption);

    Option quasiIdColumnNamesOption = Option.builder("quasiIdColumnNames").hasArg(true).required(false).build();
    commandLineOptions.addOption(quasiIdColumnNamesOption);

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

    try {
        cmd = parser.parse(commandLineOptions, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        formatter.printHelp(RiskAnalysis.class.getName(), commandLineOptions);
        System.exit(1);
        return;
    }

    String datasetId = cmd.getOptionValue(datasetIdOption.getOpt());
    String tableId = cmd.getOptionValue(tableIdOption.getOpt());
    // use default project id when project id is not specified
    String projectId = cmd.getOptionValue(projectIdOption.getOpt(), ServiceOptions.getDefaultProjectId());

    if (cmd.hasOption("n")) {
        // numerical stats analysis
        String columnName = cmd.getOptionValue(columnNameOption.getOpt());
        calculateNumericalStats(projectId, datasetId, tableId, columnName);
    } else if (cmd.hasOption("c")) {
        // categorical stats analysis
        String columnName = cmd.getOptionValue(columnNameOption.getOpt());
        calculateCategoricalStats(projectId, datasetId, tableId, columnName);
    } else if (cmd.hasOption("k")) {
        // k-anonymity analysis
        List<String> quasiIdColumnNames = Arrays.asList(cmd.getOptionValues(quasiIdColumnNamesOption.getOpt()));
        calculateKAnonymity(projectId, datasetId, tableId, quasiIdColumnNames);
    } else if (cmd.hasOption("l")) {
        // l-diversity analysis
        String sensitiveAttribute = cmd.getOptionValue(sensitiveAttributeOption.getOpt());
        List<String> quasiIdColumnNames = Arrays.asList(cmd.getOptionValues(quasiIdColumnNamesOption.getOpt()));
        calculateLDiversity(projectId, datasetId, tableId, sensitiveAttribute, quasiIdColumnNames);
    }
}

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

/**
 * Queries the command line options for an action to perform.
 * //from w w  w . j a  va 2 s.c o m
 * <pre>
 * {@code
 * > java -jar chordsharp.jar -help
 * usage: chordsharp
 *  -getsubscribers <topic>   get subscribers of a topic
 *  -help                     print this message
 *  -publish <params>         publish a new message for a topic: <topic> <message>
 *  -read <key>               read an item
 *  -subscribe <params>       subscribe to a topic: <topic> <url>
 *  -unsubscribe <params>     unsubscribe from a topic: <topic> <url>
 *  -write <params>           write an item: <key> <value>
 *  -minibench                run mini benchmark
 * }
 * </pre>
 * 
 * @param args command line arguments
 */
public static void main(String[] args) {
    CommandLineParser parser = new GnuParser();
    CommandLine line = null;
    try {
        line = parser.parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println("Parsing failed. Reason: " + e.getMessage());
        System.exit(0);
    }

    if (line.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("chordsharp", getOptions());
        System.exit(0);
    }

    if (line.hasOption("minibench")) {
        minibench();
        System.exit(0);
    }

    if (line.hasOption("read")) {
        try {
            System.out.println("read(" + line.getOptionValue("read") + ") == "
                    + ChordSharp.read(line.getOptionValue("read")));
        } catch (ConnectionException e) {
            System.err.println("read failed: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("read failed with timeout: " + e.getMessage());
        } catch (NotFoundException e) {
            System.err.println("read failed with not found: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("read failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("write")) {
        try {
            System.out.println("write(" + line.getOptionValues("write")[0] + ", "
                    + line.getOptionValues("write")[1] + ")");
            ChordSharp.write(line.getOptionValues("write")[0], line.getOptionValues("write")[1]);
        } catch (ConnectionException e) {
            System.err.println("write failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("write failed with timeout: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("write failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("publish")) {
        try {
            System.out.println("publish(" + line.getOptionValues("publish")[0] + ", "
                    + line.getOptionValues("publish")[1] + ")");
            ChordSharp.publish(line.getOptionValues("publish")[0], line.getOptionValues("publish")[1]);
        } catch (ConnectionException e) {
            System.err.println("publish failed with connection error: " + e.getMessage());
            //         } catch (TimeoutException e) {
            //            System.err.println("publish failed with timeout: "
            //                  + e.getMessage());
            //         } catch (UnknownException e) {
            //            System.err.println("publish failed with unknown: "
            //                  + e.getMessage());
        }
    }
    if (line.hasOption("subscribe")) {
        try {
            System.out.println("subscribe(" + line.getOptionValues("subscribe")[0] + ", "
                    + line.getOptionValues("subscribe")[1] + ")");
            ChordSharp.subscribe(line.getOptionValues("subscribe")[0], line.getOptionValues("subscribe")[1]);
        } catch (ConnectionException e) {
            System.err.println("subscribe failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("subscribe failed with timeout: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("subscribe failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("unsubscribe")) {
        try {
            System.out.println("unsubscribe(" + line.getOptionValues("unsubscribe")[0] + ", "
                    + line.getOptionValues("unsubscribe")[1] + ")");
            ChordSharp.unsubscribe(line.getOptionValues("unsubscribe")[0],
                    line.getOptionValues("unsubscribe")[1]);
        } catch (ConnectionException e) {
            System.err.println("unsubscribe failed with connection error: " + e.getMessage());
        } catch (TimeoutException e) {
            System.err.println("unsubscribe failed with timeout: " + e.getMessage());
        } catch (NotFoundException e) {
            System.err.println("unsubscribe failed with not found: " + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("unsubscribe failed with unknown: " + e.getMessage());
        }
    }
    if (line.hasOption("getsubscribers")) {
        try {
            System.out.println("getSubscribers(" + line.getOptionValues("getsubscribers")[0] + ") == "
                    + ChordSharp.getSubscribers(line.getOptionValues("getsubscribers")[0]));
        } catch (ConnectionException e) {
            System.err.println("getSubscribers failed with connection error: " + e.getMessage());
            //         } catch (TimeoutException e) {
            //            System.err.println("getSubscribers failed with timeout: "
            //                  + e.getMessage());
        } catch (UnknownException e) {
            System.err.println("getSubscribers failed with unknown error: " + e.getMessage());
        }
    }
}

From source file:com.akana.demo.freemarker.templatetester.App.java

public static void main(String[] args) {

    final Options options = new Options();

    @SuppressWarnings("static-access")
    Option optionContentType = OptionBuilder.withArgName("content-type").hasArg()
            .withDescription("content type of model").create("content");
    @SuppressWarnings("static-access")
    Option optionUrlPath = OptionBuilder.withArgName("httpRequestLine").hasArg()
            .withDescription("url path and parameters in HTTP Request Line format").create("url");
    @SuppressWarnings("static-access")
    Option optionRootMessageName = OptionBuilder.withArgName("messageName").hasArg()
            .withDescription("root data object name, defaults to 'message'").create("root");
    @SuppressWarnings("static-access")
    Option optionAdditionalMessages = OptionBuilder.withArgName("dataModelPaths")
            .hasArgs(Option.UNLIMITED_VALUES).withDescription("additional message object data sources")
            .create("messages");
    @SuppressWarnings("static-access")
    Option optionDebugMessages = OptionBuilder.hasArg(false)
            .withDescription("Shows debug information about template processing").create("debug");

    Option optionHelp = new Option("help", "print this message");

    options.addOption(optionHelp);/*www .  j  a va2s .c  o m*/
    options.addOption(optionContentType);
    options.addOption(optionUrlPath);
    options.addOption(optionRootMessageName);
    options.addOption(optionAdditionalMessages);
    options.addOption(optionDebugMessages);

    CommandLineParser parser = new DefaultParser();

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

        // Check for help flag
        if (cmd.hasOption("help")) {
            showHelp(options);
            return;
        }

        String[] remainingArguments = cmd.getArgs();
        if (remainingArguments.length < 2) {
            showHelp(options);
            return;
        }
        String ftlPath, dataPath = "none";

        ftlPath = remainingArguments[0];
        dataPath = remainingArguments[1];

        String contentType = "text/xml";
        // Discover content type from file extension
        String ext = FilenameUtils.getExtension(dataPath);
        if (ext.equals("json")) {
            contentType = "json";
        } else if (ext.equals("txt")) {
            contentType = "txt";
        }
        // Override discovered content type
        if (cmd.hasOption("content")) {
            contentType = cmd.getOptionValue("content");
        }
        // Root data model name
        String rootMessageName = "message";
        if (cmd.hasOption("root")) {
            rootMessageName = cmd.getOptionValue("root");
        }
        // Additional data models
        String[] additionalModels = new String[0];
        if (cmd.hasOption("messages")) {
            additionalModels = cmd.getOptionValues("messages");
        }
        // Debug Info
        if (cmd.hasOption("debug")) {
            System.out.println(" Processing ftl   : " + ftlPath);
            System.out.println("   with data model: " + dataPath);
            System.out.println(" with content-type: " + contentType);
            System.out.println(" data model object: " + rootMessageName);
            if (cmd.hasOption("messages")) {
                System.out.println("additional models: " + additionalModels.length);
            }
        }

        Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
        cfg.setDirectoryForTemplateLoading(new File("."));
        cfg.setDefaultEncoding("UTF-8");
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        /* Create the primary data-model */
        Map<String, Object> message = new HashMap<String, Object>();
        if (contentType.contains("json") || contentType.contains("txt")) {
            message.put("contentAsString",
                    FileUtils.readFileToString(new File(dataPath), StandardCharsets.UTF_8));
        } else {
            message.put("contentAsXml", freemarker.ext.dom.NodeModel.parse(new File(dataPath)));
        }

        if (cmd.hasOption("url")) {
            message.put("getProperty", new AkanaGetProperty(cmd.getOptionValue("url")));
        }

        Map<String, Object> root = new HashMap<String, Object>();
        root.put(rootMessageName, message);
        if (additionalModels.length > 0) {
            for (int i = 0; i < additionalModels.length; i++) {
                Map<String, Object> m = createMessageFromFile(additionalModels[i], contentType);
                root.put("message" + i, m);
            }
        }

        /* Get the template (uses cache internally) */
        Template temp = cfg.getTemplate(ftlPath);

        /* Merge data-model with template */
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);

    } catch (ParseException e) {
        showHelp(options);
        System.exit(1);
    } catch (IOException e) {
        System.out.println("Unable to parse ftl.");
        e.printStackTrace();
    } catch (SAXException e) {
        System.out.println("XML parsing issue.");
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        System.out.println("Unable to configure parser.");
        e.printStackTrace();
    } catch (TemplateException e) {
        System.out.println("Unable to parse template.");
        e.printStackTrace();
    }

}

From source file:com.msd.gin.halyard.tools.HalyardExport.java

/**
 * Main of the HalyardExport//  w ww .  j  av a2  s.co  m
 * @param args String command line arguments
 * @throws Exception throws Exception in case of any problem
 */
public static void main(final String args[]) throws Exception {
    if (conf == null)
        conf = new Configuration();
    Options options = new Options();
    options.addOption(newOption("h", null, "Prints this help"));
    options.addOption(newOption("v", null, "Prints version"));
    options.addOption(newOption("s", "source_htable", "Source HBase table with Halyard RDF store"));
    options.addOption(
            newOption("q", "sparql_query", "SPARQL tuple or graph query executed to export the data"));
    options.addOption(newOption("t", "target_url",
            "file://<path>/<file_name>.<ext> or hdfs://<path>/<file_name>.<ext> or jdbc:<jdbc_connection>/<table_name>"));
    options.addOption(newOption("p", "property=value", "JDBC connection properties"));
    options.addOption(newOption("l", "driver_classpath", "JDBC driver classpath delimited by ':'"));
    options.addOption(newOption("c", "driver_class", "JDBC driver class name"));
    options.addOption(newOption("r", null, "Trim target table before export (apply for JDBC only)"));
    try {
        CommandLine cmd = new PosixParser().parse(options, args);
        if (args.length == 0 || cmd.hasOption('h')) {
            printHelp(options);
            return;
        }
        if (cmd.hasOption('v')) {
            Properties p = new Properties();
            try (InputStream in = HalyardExport.class
                    .getResourceAsStream("/META-INF/maven/com.msd.gin.halyard/hbasesail/pom.properties")) {
                if (in != null)
                    p.load(in);
            }
            System.out.println("Halyard Export version " + p.getProperty("version", "unknown"));
            return;
        }
        if (!cmd.getArgList().isEmpty())
            throw new ExportException("Unknown arguments: " + cmd.getArgList().toString());
        for (char c : "sqt".toCharArray()) {
            if (!cmd.hasOption(c))
                throw new ExportException("Missing mandatory option: " + c);
        }
        for (char c : "sqtlc".toCharArray()) {
            String s[] = cmd.getOptionValues(c);
            if (s != null && s.length > 1)
                throw new ExportException("Multiple values for option: " + c);
        }
        StatusLog log = new StatusLog() {
            private final Logger l = Logger.getLogger(HalyardExport.class.getName());

            @Override
            public void tick() {
            }

            @Override
            public void logStatus(String status) {
                l.info(status);
            }
        };
        String driverClasspath = cmd.getOptionValue('l');
        URL driverCP[] = null;
        if (driverClasspath != null) {
            String jars[] = driverClasspath.split(":");
            driverCP = new URL[jars.length];
            for (int j = 0; j < jars.length; j++) {
                File f = new File(jars[j]);
                if (!f.isFile())
                    throw new ExportException("Invalid JDBC driver classpath element: " + jars[j]);
                driverCP[j] = f.toURI().toURL();
            }
        }
        export(conf, log, cmd.getOptionValue('s'), cmd.getOptionValue('q'), cmd.getOptionValue('t'),
                cmd.getOptionValue('c'), driverCP, cmd.getOptionValues('p'), cmd.hasOption('r'));
    } catch (RuntimeException exp) {
        System.out.println(exp.getMessage());
        printHelp(options);
        throw exp;
    }
}

From source file:dk.statsbiblioteket.netark.dvenabler.Command.java

@SuppressWarnings("CallToPrintStackTrace")
public static void main(String[] args) throws IOException {
    CommandLine cli;
    try {//from w w w  .j a v a  2  s .  com
        cli = new GnuParser().parse(getOptions(), args);
    } catch (ParseException e) {
        System.err.println("Exception parsing arguments");
        e.printStackTrace();
        usage();
        return;
    }

    if (cli.hasOption(HELP)) {
        usage();
        return;
    }

    if (!cli.hasOption(INPUT)) {
        System.err.println("input index must be specified");
        usage();
        return;
    }

    final File in = new File(cli.getOptionValue(INPUT));
    if (!in.exists() || !in.isDirectory()) {
        System.err.println("Unable to access index folder '" + in + "'");
        usage();
        return;
    }

    final boolean verbose = cli.hasOption(VERBOSE);
    if (cli.hasOption(LIST)) {
        list(in, verbose);
        return;
    }

    if (cli.hasOption(CONVERT)) {
        if (!cli.hasOption(OUTPUT)) {
            System.err.println("convert is specified but output is missing");
            usage();
            return;
        }
        final File out = new File(cli.getOptionValue(OUTPUT));
        if (!cli.hasOption(FIELDS)) {
            System.err.println("convert is specified but no fields are defined.\n"
                    + "Use '.' to signal that no fields should be changed");
            usage();
            return;
        }
        final String[] rawFields = cli.getOptionValues(FIELDS);
        List<DVConfig> dvFields = getTweakedFields(in, rawFields);
        if (dvFields == null) {
            System.err.println("Invalid field specification");
            usage();
            return;
        }
        convert(in, out, dvFields, verbose);
        return;
    }

    System.out.println("Nothing to do");
    usage();
}

From source file:com.continuent.tungsten.common.security.PasswordManagerCtrl.java

/**
 * Password Manager entry point/*from   ww  w  .  j ava2 s  .  co  m*/
 * 
 * @param argv
 * @throws Exception
 */
public static void main(String argv[]) throws Exception {
    pwd = new PasswordManagerCtrl();

    // --- Options ---
    ClientApplicationType clientApplicationType = null;
    String securityPropertiesFileLocation = null;
    String username = null;
    String password = null;
    CommandLine line = null;

    try {
        CommandLineParser parser = new GnuParser();
        // --- Parse the command line arguments ---

        // --- Help
        line = parser.parse(pwd.helpOptions, argv, true);
        if (line.hasOption(_HELP)) {
            DisplayHelpAndExit(EXIT_CODE.EXIT_OK);
        }

        // --- Program command line options
        line = parser.parse(pwd.options, argv);

        // --- Handle options ---

        // --- Optional arguments : Get options ---
        if (line.hasOption(_HELP)) {
            DisplayHelpAndExit(EXIT_CODE.EXIT_OK);
        }
        if (line.hasOption(_TARGET_APPLICATION)) // Target Application
        {
            String target = line.getOptionValue(TARGET_APPLICATION);
            clientApplicationType = PasswordManagerCtrl.getClientApplicationType(target);
        }
        if (line.hasOption(_FILE)) // security.properties file location
        {
            securityPropertiesFileLocation = line.getOptionValue(_FILE);
        }
        if (line.hasOption(_AUTHENTICATE)) { // Make sure username + password are provided
            String[] authenticateArgs = line.getOptionValues(_AUTHENTICATE);
            if (authenticateArgs.length < 2)
                throw new MissingArgumentException(authenticate);

            username = authenticateArgs[0];
            password = authenticateArgs[1];
        }
        if (line.hasOption(_CREATE)) { // Make sure username + password are provided
            String[] createArgs = line.getOptionValues(_CREATE);
            if (createArgs.length < 2)
                throw new MissingArgumentException(create);

            username = createArgs[0];
            password = createArgs[1];
        }
        // --- Options to replace values in security.properties file ---
        if (line.hasOption(_ENCRYPTED_PASSWORD))
            pwd.useEncryptedPassword = true;
        if (line.hasOption(_TRUSTSTORE_LOCATION))
            pwd.truststoreLocation = line.getOptionValue(_TRUSTSTORE_LOCATION);
        if (line.hasOption(_TRUSTSTORE_PASSWORD))
            pwd.truststorePassword = line.getOptionValue(_TRUSTSTORE_PASSWORD);
        if (line.hasOption(_KEYSTORE_LOCATION))
            pwd.keystoreLocation = line.getOptionValue(_KEYSTORE_LOCATION);
        if (line.hasOption(_KEYSTORE_PASSWORD))
            pwd.keystorePassword = line.getOptionValue(_KEYSTORE_PASSWORD);
        if (line.hasOption(_PASSWORD_FILE_LOCATION))
            pwd.passwordFileLocation = (String) line.getOptionValue(_PASSWORD_FILE_LOCATION);

        try {
            pwd.passwordManager = new PasswordManager(securityPropertiesFileLocation, clientApplicationType);

            AuthenticationInfo authenticationInfo = pwd.passwordManager.getAuthenticationInfo();
            // --- Substitute with user provided options
            if (pwd.useEncryptedPassword != null)
                authenticationInfo.setUseEncryptedPasswords(pwd.useEncryptedPassword);
            if (pwd.truststoreLocation != null)
                authenticationInfo.setTruststoreLocation(pwd.truststoreLocation);
            if (pwd.truststorePassword != null)
                authenticationInfo.setTruststorePassword(pwd.truststorePassword);
            if (pwd.keystoreLocation != null)
                authenticationInfo.setKeystoreLocation(pwd.keystoreLocation);
            if (pwd.keystorePassword != null)
                authenticationInfo.setKeystorePassword(pwd.keystorePassword);
            if (pwd.passwordFileLocation != null)
                authenticationInfo.setPasswordFileLocation(pwd.passwordFileLocation);

            // --- Display summary of used parameters ---
            logger.info("Using parameters: ");
            logger.info("-----------------");
            if (authenticationInfo.getParentPropertiesFileLocation() != null)
                logger.info(MessageFormat.format("security.properties \t = {0}",
                        authenticationInfo.getParentPropertiesFileLocation()));
            logger.info(MessageFormat.format("password_file.location \t = {0}",
                    authenticationInfo.getPasswordFileLocation()));
            logger.info(MessageFormat.format("encrypted.password \t = {0}",
                    authenticationInfo.isUseEncryptedPasswords()));

            // --- Keystore
            if (line.hasOption(_AUTHENTICATE)) {
                logger.info(MessageFormat.format("keystore.location \t = {0}",
                        authenticationInfo.getKeystoreLocation()));
                logger.info(MessageFormat.format("keystore.password \t = {0}",
                        authenticationInfo.getKeystorePassword()));
            }

            // --- Truststore
            if (authenticationInfo.isUseEncryptedPasswords()) {
                logger.info(MessageFormat.format("truststore.location \t = {0}",
                        authenticationInfo.getTruststoreLocation()));
                logger.info(MessageFormat.format("truststore.password \t = {0}",
                        authenticationInfo.getTruststorePassword()));
            }
            logger.info("-----------------");

            // --- AuthenticationInfo consistency check
            // Try to create files if possible
            pwd.passwordManager.try_createAuthenticationInfoFiles();
            authenticationInfo.checkAndCleanAuthenticationInfo();

        } catch (ConfigurationException ce) {
            logger.error(MessageFormat.format(
                    "Could not retrieve configuration information: {0}\nTry to specify a security.properties file location, provide options on the command line, or have the cluster.home variable set.",
                    ce.getMessage()));
            System.exit(EXIT_CODE.EXIT_ERROR.value);
        } catch (ServerRuntimeException sre) {
            logger.error(sre.getLocalizedMessage());
            // AuthenticationInfo consistency check : failed
            DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR);
        }

        // --- Perform commands ---

        // ######### Authenticate ##########
        if (line.hasOption(_AUTHENTICATE)) {
            try {
                boolean authOK = pwd.passwordManager.authenticateUser(username, password);
                String msgAuthOK = (authOK) ? "SUCCESS" : "FAILED";
                logger.info(
                        MessageFormat.format("Authenticating  {0}:{1} = {2}", username, password, msgAuthOK));
            } catch (Exception e) {
                logger.error(MessageFormat.format("Error while authenticating user: {0}", e.getMessage()));
            }
        }
        // ######### Create ##########
        if (line.hasOption(_CREATE)) {
            try {
                pwd.passwordManager.setPasswordForUser(username, password);
                logger.info(MessageFormat.format("User created successfuly: {0}", username));
            } catch (Exception e) {
                logger.error(MessageFormat.format("Error while creating user: {0}", e.getMessage()));
            }
        }

        // ########## DELETE ##########
        else if (line.hasOption(_DELETE)) {
            username = line.getOptionValue(_DELETE);

            try {
                pwd.passwordManager.deleteUser(username);
                logger.info(MessageFormat.format("User deleted successfuly: {0}", username));
            } catch (Exception e) {
                logger.error(MessageFormat.format("Error while deleting user: {0}", e.getMessage()));
            }
        }

    } catch (ParseException exp) {
        logger.error(exp.getMessage());

        DisplayHelpAndExit(EXIT_CODE.EXIT_ERROR);
    }
}

From source file:boa.compiler.BoaCompiler.java

public static void main(final String[] args) throws IOException {
    CommandLine cl = processCommandLineOptions(args);
    if (cl == null)
        return;/*from  ww w . ja v a  2s  .  co m*/
    final ArrayList<File> inputFiles = BoaCompiler.inputFiles;

    // get the name of the generated class
    final String className = getGeneratedClass(cl);

    // get the filename of the jar we will be writing
    final String jarName;
    if (cl.hasOption('o'))
        jarName = cl.getOptionValue('o');
    else
        jarName = className + ".jar";

    // make the output directory
    File outputRoot = null;
    if (cl.hasOption("cd")) {
        outputRoot = new File(cl.getOptionValue("cd"));
    } else {
        outputRoot = new File(new File(System.getProperty("java.io.tmpdir")), UUID.randomUUID().toString());
    }
    final File outputSrcDir = new File(outputRoot, "boa");
    if (!outputSrcDir.mkdirs())
        throw new IOException("unable to mkdir " + outputSrcDir);

    // find custom libs to load
    final List<URL> libs = new ArrayList<URL>();
    if (cl.hasOption('l'))
        for (final String lib : cl.getOptionValues('l'))
            libs.add(new File(lib).toURI().toURL());

    final File outputFile = new File(outputSrcDir, className + ".java");
    final BufferedOutputStream o = new BufferedOutputStream(new FileOutputStream(outputFile));
    try {
        final List<String> jobnames = new ArrayList<String>();
        final List<String> jobs = new ArrayList<String>();
        boolean isSimple = true;

        final List<Program> visitorPrograms = new ArrayList<Program>();

        SymbolTable.initialize(libs);

        final int maxVisitors;
        if (cl.hasOption('v'))
            maxVisitors = Integer.parseInt(cl.getOptionValue('v'));
        else
            maxVisitors = Integer.MAX_VALUE;

        for (int i = 0; i < inputFiles.size(); i++) {
            final File f = inputFiles.get(i);
            try {
                final BoaLexer lexer = new BoaLexer(new ANTLRFileStream(f.getAbsolutePath()));
                lexer.removeErrorListeners();
                lexer.addErrorListener(new LexerErrorListener());

                final CommonTokenStream tokens = new CommonTokenStream(lexer);
                final BoaParser parser = new BoaParser(tokens);
                parser.removeErrorListeners();
                parser.addErrorListener(new BaseErrorListener() {
                    @Override
                    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
                            int charPositionInLine, String msg, RecognitionException e)
                            throws ParseCancellationException {
                        throw new ParseCancellationException(e);
                    }
                });

                final BoaErrorListener parserErrorListener = new ParserErrorListener();
                final Start p = parse(tokens, parser, parserErrorListener);
                if (cl.hasOption("ast"))
                    new ASTPrintingVisitor().start(p);

                final String jobName = "" + i;

                try {
                    if (!parserErrorListener.hasError) {
                        new TypeCheckingVisitor().start(p, new SymbolTable());

                        final TaskClassifyingVisitor simpleVisitor = new TaskClassifyingVisitor();
                        simpleVisitor.start(p);

                        LOG.info(f.getName() + ": task complexity: "
                                + (!simpleVisitor.isComplex() ? "simple" : "complex"));
                        isSimple &= !simpleVisitor.isComplex();

                        new ShadowTypeEraser().start(p);
                        new InheritedAttributeTransformer().start(p);

                        new LocalAggregationTransformer().start(p);

                        // if a job has no visitor, let it have its own method
                        // also let jobs have own methods if visitor merging is disabled
                        if (!simpleVisitor.isComplex() || maxVisitors < 2 || inputFiles.size() == 1) {
                            new VisitorOptimizingTransformer().start(p);

                            if (cl.hasOption("pp"))
                                new PrettyPrintVisitor().start(p);
                            if (cl.hasOption("ast2"))
                                new ASTPrintingVisitor().start(p);
                            final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(jobName);
                            cg.start(p);
                            jobs.add(cg.getCode());

                            jobnames.add(jobName);
                        }
                        // if a job has visitors, fuse them all together into a single program
                        else {
                            p.getProgram().jobName = jobName;
                            visitorPrograms.add(p.getProgram());
                        }
                    }
                } catch (final TypeCheckException e) {
                    parserErrorListener.error("typecheck", lexer, null, e.n.beginLine, e.n.beginColumn,
                            e.n2.endColumn - e.n.beginColumn + 1, e.getMessage(), e);
                }
            } catch (final Exception e) {
                System.err.print(f.getName() + ": compilation failed: ");
                e.printStackTrace();
            }
        }

        if (!visitorPrograms.isEmpty())
            try {
                for (final Program p : new VisitorMergingTransformer().mergePrograms(visitorPrograms,
                        maxVisitors)) {
                    new VisitorOptimizingTransformer().start(p);

                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());

                    jobnames.add(p.jobName);
                }
            } catch (final Exception e) {
                System.err.println("error fusing visitors - falling back: " + e);
                e.printStackTrace();

                for (final Program p : visitorPrograms) {
                    new VisitorOptimizingTransformer().start(p);

                    if (cl.hasOption("pp"))
                        new PrettyPrintVisitor().start(p);
                    if (cl.hasOption("ast2"))
                        new ASTPrintingVisitor().start(p);
                    final CodeGeneratingVisitor cg = new CodeGeneratingVisitor(p.jobName);
                    cg.start(p);
                    jobs.add(cg.getCode());

                    jobnames.add(p.jobName);
                }
            }

        if (jobs.size() == 0)
            throw new RuntimeException("no files compiled without error");

        final ST st = AbstractCodeGeneratingVisitor.stg.getInstanceOf("Program");

        st.add("name", className);
        st.add("numreducers", inputFiles.size());
        st.add("jobs", jobs);
        st.add("jobnames", jobnames);
        st.add("combineTables", CodeGeneratingVisitor.combineAggregatorStrings);
        st.add("reduceTables", CodeGeneratingVisitor.reduceAggregatorStrings);
        st.add("splitsize", isSimple ? 64 * 1024 * 1024 : 10 * 1024 * 1024);
        if (DefaultProperties.localDataPath != null) {
            st.add("isLocal", true);
        }

        o.write(st.render().getBytes());
    } finally {
        o.close();
    }

    compileGeneratedSrc(cl, jarName, outputRoot, outputFile);
}

From source file:com.tvh.gmaildrafter.Drafter.java

/**
 * @param args the command line arguments
 *//*from   www .  j a  va2  s .co  m*/
public static void main(String[] args) {
    Options options = getCMDLineOptions();
    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        if (cmd.hasOption("help")) {
            printHelpMessage(options);
            System.exit(0);
        }

        String emailBody = null;
        String emailSubject = null;

        if (cmd.hasOption("body")) {
            String bodyFile = cmd.getOptionValue("body");
            File body = new File(bodyFile);
            emailBody = FileUtils.readFileToString(body);
            if (cmd.hasOption("deletebody")) {
                body.delete();
            }
        } else if (cmd.hasOption("stdin")) {
            emailBody = Util.readEntireStdin();
        }

        if (cmd.hasOption("subject"))
            emailSubject = cmd.getOptionValue("subject");
        else if (cmd.hasOption("subjectfile")) {
            String subjectFile = cmd.getOptionValue("subjectfile");
            File subject = new File(subjectFile);
            emailSubject = FileUtils.readFileToString(subject);
            if (cmd.hasOption("deletesubjectfile"))
                subject.delete();
        }

        String username = null;
        if (cmd.hasOption("username"))
            username = cmd.getOptionValue("username");

        String password = null;
        if (cmd.hasOption("password"))
            password = cmd.getOptionValue("password");

        String[] bcc = cmd.getOptionValues("bcc");
        String[] cc = cmd.getOptionValues("cc");

        Boolean sendImmediately = cmd.hasOption("immediate");

        String[] attachments = cmd.getOptionValues("attachments");
        String[] attachmentnames = cmd.getOptionValues("attachmentnames");
        String[] destinations = cmd.getOptionValues("to");

        Credentials credentials = Authenticater.getValidCredentials(username, password);

        if (credentials != null) {
            boolean success = false;
            while (!success) {
                try {
                    composeMail(credentials, emailSubject, emailBody, attachments, attachmentnames,
                            destinations, cc, bcc, sendImmediately);
                    success = true;
                } catch (AuthenticationFailedException e) {
                    JOptionPane.showMessageDialog(null, "Invalid login, please try again!");
                    credentials = Authenticater.getValidCredentials(username, null);
                    success = false;
                }

            }
        }

    } catch (ParseException ex) {
        javax.swing.JOptionPane.showMessageDialog(null, ex.getMessage());
        printHelpMessage(options);
        System.exit(7);
    } catch (IOException ex) {
        System.out.println("IO Exception " + ex.getLocalizedMessage());
        printHelpMessage(options);
        System.exit(2);
    } catch (LoginException ex) {
        System.out.println(ex.getMessage());
        System.exit(3);
    }

    System.exit(0);

}

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

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

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

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

From source file:com.zimbra.perf.chart.ChartUtil.java

public static void main(String[] args) throws Exception {
    CommandLineParser clParser = new GnuParser();
    Options opts = getOptions();//from w w w .j  ava2s.c o  m
    try {
        CommandLine cl = clParser.parse(opts, args);

        if (cl.hasOption('h'))
            usage(opts);
        if (!cl.hasOption('s') && !cl.hasOption('d'))
            usage(opts, "-s and -d options are required");
        if (!cl.hasOption('s'))
            usage(opts, "Missing required -s option");

        if (!cl.hasOption('d'))
            usage(opts, "Missing required -d option");

        String[] confs = cl.getOptionValues(OPT_CONF);
        if (confs == null || confs.length == 0)
            usage(opts, "Missing --" + OPT_CONF + " option");
        File[] confFiles = new File[confs.length];
        for (int i = 0; i < confs.length; i++) {
            File conf = new File(confs[i]);
            if (!conf.exists()) {
                System.err.printf("Configuration file %s does not exist\n", conf.getAbsolutePath());
                System.exit(1);
            }
            confFiles[i] = conf;
        }

        String[] srcDirStrs = cl.getOptionValues(OPT_SRCDIR);
        if (srcDirStrs == null || srcDirStrs.length == 0)
            usage(opts, "Missing --" + OPT_SRCDIR + " option");
        List<File> srcDirsList = new ArrayList<File>(srcDirStrs.length);
        for (int i = 0; i < srcDirStrs.length; i++) {
            File srcDir = new File(srcDirStrs[i]);
            if (srcDir.exists())
                srcDirsList.add(srcDir);
            else
                System.err.printf("Source directory %s does not exist\n", srcDir.getAbsolutePath());
        }
        if (srcDirsList.size() < 1)
            usage(opts, "No valid source directory found");
        File[] srcDirs = new File[srcDirsList.size()];
        srcDirsList.toArray(srcDirs);

        String destDirStr = cl.getOptionValue(OPT_DESTDIR);
        if (destDirStr == null)
            usage(opts, "Missing --" + OPT_DESTDIR + " option");
        File destDir = new File(destDirStr);
        if (!destDir.exists()) {
            boolean created = destDir.mkdirs();
            if (!created) {
                System.err.printf("Unable to create destination directory %s\n", destDir.getAbsolutePath());
                System.exit(1);
            }
        }
        if (!destDir.canWrite()) {
            System.err.printf("Destination directory %s is not writable\n", destDir.getAbsolutePath());
            System.exit(1);
        }

        String title = cl.getOptionValue(OPT_TITLE);
        if (title == null)
            title = srcDirs[0].getAbsoluteFile().getName();

        Date startAt = parseTimestampOption(cl, opts, OPT_START_AT);
        Date endAt = parseTimestampOption(cl, opts, OPT_END_AT);
        Date aggStartAt = parseTimestampOption(cl, opts, OPT_AGGREGATE_START_AT);
        Date aggEndAt = parseTimestampOption(cl, opts, OPT_AGGREGATE_END_AT);

        boolean noSummary = cl.hasOption('n');
        ChartUtil app = new ChartUtil(confFiles, srcDirs, destDir, title, startAt, endAt, aggStartAt, aggEndAt,
                noSummary);
        app.doit();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println();
        usage(opts);
    }
}