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

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

Introduction

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

Prototype

public MissingArgumentException(Option option) 

Source Link

Document

Construct a new MissingArgumentException with the specified detail message.

Usage

From source file:com.falcon.orca.helpers.CommandHelper.java

public static RunDetails createRunDetails(final CommandLine commandLine)
        throws MissingArgumentException, MalformedURLException {
    RunDetails runDetails = new RunDetails();
    if (commandLine.hasOption("url") && !StringUtils.isBlank(commandLine.getOptionValue("url"))) {
        runDetails.setUrl(commandLine.getOptionValue("url"));
    } else {/*from  w  ww  . j av a2s .c o  m*/
        throw new MissingArgumentException("--url Please provide URL to hit.");
    }
    if (commandLine.hasOption("dataFile") && commandLine.hasOption("template")) {
        runDetails.setBodyDynamic(true);
    }
    if ((commandLine.getOptionValue("url").contains("{{") && commandLine.hasOption("dataFile"))
            || (commandLine.getOptionValue("url").contains("@@") && commandLine.hasOption("dataFile"))) {
        runDetails.setUrlDynamic(true);
    }
    if (commandLine.hasOption("durationMode")) {
        runDetails.setDurationMode(Boolean.valueOf(commandLine.getOptionValue("durationMode")));
    } else {
        runDetails.setDurationMode(false);
    }
    if (runDetails.isDurationMode()) {
        if (commandLine.hasOption("duration")) {
            runDetails.setDuration(Long.valueOf(commandLine.getOptionValue("duration")));
        } else {
            throw new MissingArgumentException(
                    "--duration duration of run in  " + "seconds is required in duration mode");
        }
    } else {
        if (commandLine.hasOption("repeats")) {
            runDetails.setRepeats(Integer.valueOf(commandLine.getOptionValue("repeats")));
        } else {
            throw new MissingArgumentException("--repeats please provide number " + "of repeats to make");
        }
    }
    if (commandLine.hasOption("template")) {
        runDetails.setTemplateFilePath(commandLine.getOptionValue("template"));
    }
    if (commandLine.hasOption("dataFile")) {
        runDetails.setDataFilePath(commandLine.getOptionValue("dataFile"));
    }
    if (commandLine.hasOption("method")) {
        runDetails.setHttpMethod(commandLine.getOptionValue("method"));
    } else {
        runDetails.setHttpMethod("GET");
    }
    if (commandLine.hasOption("header")) {
        runDetails.setHeaders(Arrays.asList(commandLine.getOptionValues("header")));
    }
    if (commandLine.hasOption("cookie")) {
        runDetails.setCookies(Arrays.asList(commandLine.getOptionValues("cookie")));
    }
    if (commandLine.hasOption("data")) {
        runDetails.setData(Joiner.on(' ').join(commandLine.getOptionValues("data")));
    }
    if (commandLine.hasOption("concurrency")) {
        runDetails.setConcurrency(Integer.valueOf(commandLine.getOptionValue("concurrency")));
    } else {
        throw new MissingArgumentException("--concurrency Provide number of " + "users to simulate.");
    }
    return runDetails;
}

From source file:com.springrts.springls.CmdLineArgs.java

/**
 * Processes all command line arguments in 'args'.
 * Raises an exception in case of errors.
 * @return whether to exit the application after this method
 *///from  www.  java 2s.c  o  m
private static boolean apply(Configuration configuration, CommandLineParser parser, Options options,
        String[] args) throws ParseException {
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Server.getApplicationName(), options);
        return true;
    }

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue("port");
        int port = Integer.parseInt(portStr);
        if ((port < 1) || (port > 65535)) {
            throw new ParseException("Invalid port specified: " + portStr);
        }
        configuration.setProperty(ServerConfiguration.PORT, port);
    }
    if (cmd.hasOption("database")) {
        configuration.setProperty(ServerConfiguration.USE_DATABASE, true);
    } else if (cmd.hasOption("file-storage")) {
        configuration.setProperty(ServerConfiguration.USE_DATABASE, false);
    } else {
        configuration.setProperty(ServerConfiguration.LAN_MODE, true);
    }
    if (cmd.hasOption("statistics")) {
        configuration.setProperty(ServerConfiguration.STATISTICS_STORE, true);
    }
    if (cmd.hasOption("nat-port")) {
        String portStr = cmd.getOptionValue("port");
        int port = Integer.parseInt(portStr);
        if ((port < 1) || (port > 65535)) {
            throw new ParseException("Invalid NAT traversal port" + " specified: " + portStr);
        }
        configuration.setProperty(ServerConfiguration.NAT_PORT, port);
    }
    if (cmd.hasOption("log-main")) {
        configuration.setProperty(ServerConfiguration.CHANNELS_LOG_REGEX, "^main$");
    }
    if (cmd.hasOption("lan-admin")) {
        String[] usernamePassword = cmd.getOptionValues("lan-admin");

        if (usernamePassword.length < 1) {
            throw new MissingArgumentException("LAN admin user name is missing");
        }
        String username = usernamePassword[0];
        String password = (usernamePassword.length > 1) ? usernamePassword[0]
                : ServerConfiguration.getDefaults().getString(ServerConfiguration.LAN_ADMIN_PASSWORD);

        String error = Account.isOldUsernameValid(username);
        if (error != null) {
            throw new ParseException("LAN admin user name is not valid: " + error);
        }
        error = Account.isPasswordValid(password);
        if (error != null) {
            throw new ParseException("LAN admin password is not valid: " + error);
        }
        configuration.setProperty(ServerConfiguration.LAN_ADMIN_USERNAME, username);
        configuration.setProperty(ServerConfiguration.LAN_ADMIN_PASSWORD, password);
    }
    if (cmd.hasOption("load-args")) {
        File argsFile = new File(cmd.getOptionValue("load-args"));
        Reader inF = null;
        BufferedReader in = null;
        try {
            try {
                inF = new FileReader(argsFile);
                in = new BufferedReader(inF);
                String line;
                List<String> argsList = new LinkedList<String>();
                while ((line = in.readLine()) != null) {
                    String[] argsLine = line.split("[ \t]+");
                    argsList.addAll(Arrays.asList(argsLine));
                }
                String[] args2 = argsList.toArray(new String[argsList.size()]);
                apply(configuration, parser, options, args2);
            } finally {
                if (in != null) {
                    in.close();
                } else if (inF != null) {
                    inF.close();
                }
            }
        } catch (Exception ex) {
            throw new ParseException("invalid load-args argument: " + ex.getMessage());
        }
    }
    if (cmd.hasOption("spring-version")) {
        String version = cmd.getOptionValue("spring-version");
        configuration.setProperty(ServerConfiguration.ENGINE_VERSION, version);
    }

    return false;
}

From source file:mitm.common.tools.SendMail.java

private void sendMessage(Address[] recipients, MimeMessage message)
        throws MissingArgumentException, MessagingException, InterruptedException {
    Properties properties = System.getProperties();

    if (StringUtils.isBlank(smtpHost)) {
        throw new MissingArgumentException("<smtp host> is missing");
    }//from   ww  w.  ja  va 2 s . c  om

    MailTransport mailSender = new MailTransportImpl(smtpHost, smtpPort, sender, properties, username,
            password);

    prepareMessage(message, from, subject);

    sendMultiThreaded(mailSender, message, recipients);
}

From source file:br.ufpb.dicomflow.integrationAPI.tools.ReadService.java

private static void readService(CommandLine cl) throws ParseException, JAXBException, IOException {

    Logger.v(rb.getString("start-receive-service"));

    MailAuthenticatorIF mailAuthenticator = new SMTPAuthenticator(
            properties.getProperty(DicomMessageProperties.AUTHENTICATION_LOGIN),
            properties.getProperty(DicomMessageProperties.AUTHENTICATION_PASSWORD));
    MailServiceExtractorIF mailServiceExtractor = new SMTPServiceExtractor();
    MailMessageReaderIF mailMessageReader = new SMTPMessageReader(
            properties.getProperty(DicomMessageProperties.PROVIDER_HOST),
            properties.getProperty(DicomMessageProperties.PROVIDER_FOLDER));

    SMTPReceiver receiver = new SMTPReceiver();
    receiver.setProperties(properties);/* www . ja  v a2  s  . com*/
    receiver.setAuthenticatorBuilder(mailAuthenticator);
    receiver.setMessageReader(mailMessageReader);
    receiver.setServiceExtractor(mailServiceExtractor);

    if (!cl.hasOption(DEST_DIR_OPTION)) {

        throw new MissingArgumentException(rb.getString("missing-content-opt"));

    } else {

        File destDir = new File(cl.getOptionValue(DEST_DIR_OPTION));
        if (!destDir.exists()) {
            throw new FileNotFoundException(
                    rb.getString("invalid-dest-dir") + cl.getOptionValue(DEST_DIR_OPTION));
        }

        List<MessageIF> messages = new ArrayList<MessageIF>();
        if (cl.hasOption(CLIUtils.ENCRYPT_OPTION)) {
            messages = receiver.receiveCipherMessages(filter, signer, cipher, privateKey);
        } else {
            messages = receiver.receiveMessages(filter);
        }

        saveMessages(messages, destDir);

    }

    Logger.v(rb.getString("finish-receive-service"));

}

From source file:mitm.application.djigzo.tools.CertManager.java

private void syncKeyAndCertStore() throws Exception {
    SyncMode syncMode = SyncMode.fromName(syncOption.getValue());

    if (syncMode == null) {
        StrBuilder sb = new StrBuilder();

        for (SyncMode mode : SyncMode.values()) {
            sb.appendSeparator(',');
            sb.append(mode.getName());//from  w ww .j  av a2 s .  c om
        }

        throw new MissingArgumentException(
                "Syncmode is not a valid syncmode. Supported syncmodes: " + sb.toString());
    }

    createKeyAndCertStoreWS().sync(syncMode);
}

From source file:eu.sonata.nfv.nec.validate.cli.Main.java

/**
 * Parses the command line arguments./*from   w w  w  . ja v  a  2s.c  o m*/
 *
 * @param args The command line arguments.
 */
private static void parseCliOptions(String[] args) {
    // Command line options.
    Options options = createCliOptions();
    // Command line parser.
    CommandLineParser parser = new DefaultParser();

    try {
        // Parse the command line arguments
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("h")) {
            printHelp(options);
            System.exit(EXIT_CODE_SUCCESS);
        }
        if (line.hasOption("s")) {
            schemaFile = normalizePath(line.getOptionValue('s'));
            if (schemaFile == null)
                checkSchema = false;
        }
        if (line.hasOption("v")) {
            setLogLevel(2);
        }
        if (line.hasOption("d")) {
            checkSchema = false;
        }
        if (line.hasOption("c")) {
            coloredOutput = true;
        }
        if (line.hasOption("k")) {
            schemaKey = line.getOptionValue('k');
        } else {
            schemaKey = DEFAULT_SCHEMA_KEY;
        }
        // Get whatever ist left, after the options have been processed.
        if (line.getArgList() == null || line.getArgList().isEmpty()) {
            throw new MissingArgumentException("JSON/YAML file to validate is missing.");
        } else {
            jsonFile = normalizePath(line.getArgList().get(0));
        }
    } catch (MissingOptionException | MissingArgumentException e) {
        System.err.println("ERROR: " + e.getMessage() + "\n");
        printHelp(options);
        System.exit(EXIT_CODE_ERROR);
    } catch (ParseException e) {
        // Oops, something went wrong
        System.err.println("ERROR: Parsing failed. Reason: " + e.getMessage());
    }
}

From source file:mitm.common.tools.SMIME.java

/**
 * @param args// w  w  w  .j  a v  a2  s . c o  m
 * @throws CryptoMessageSyntaxException
 */
public static void main(String[] args) {
    try {
        PropertyConfigurator.configure("conf/tools.log4j.properties");

        InitializeBouncycastle.initialize();

        securityFactory = SecurityFactoryFactory.getSecurityFactory();

        CommandLineParser parser = new BasicParser();

        Options options = createCommandLineOptions();

        HelpFormatter formatter = new HelpFormatter();

        CommandLine commandLine;

        try {
            commandLine = parser.parse(options, args);
        } catch (ParseException e) {
            formatter.printHelp("SMIME", options, true);

            throw e;
        }

        String inFile = commandLine.getOptionValue("in");
        String keyFile = commandLine.getOptionValue("p12");
        String password = commandLine.getOptionValue("password");
        boolean binary = commandLine.hasOption("binary");
        String p7mOut = commandLine.getOptionValue("p7mOut");
        String cerOut = commandLine.getOptionValue("cerOut");
        String alias = commandLine.getOptionValue("alias");
        String digest = commandLine.getOptionValue("digest");
        String outFile = commandLine.getOptionValue("out");

        if (commandLine.hasOption("help") || args == null || args.length == 0) {
            formatter.printHelp("SMIME", options, true);

            return;
        }

        if (commandLine.hasOption("pwd")) {
            System.err.println("Please enter your password: ");

            /*
             * We will redirect the output to err so we do not get any * chars on the output.
             */
            ConsoleReader consoleReader = new ConsoleReader(new FileInputStream(FileDescriptor.in),
                    new PrintWriter(System.err));

            password = consoleReader.readLine(new Character('*'));
        }

        KeyStore keyStore = null;

        if (keyFile != null) {
            keyStore = loadKeyStore(keyFile, password);
        }

        if (commandLine.hasOption("printAliases")) {
            if (keyStore == null) {
                throw new MissingArgumentException("p12 file is missing.");
            }

            printKeystoreAliases(keyStore);
        }

        MimeMessage message;

        if (commandLine.hasOption("r")) {
            if (commandLine.hasOption("p7m")) {
                message = loadp7m(inFile, binary);

                if (commandLine.hasOption("p7mOut")) {
                    MailUtils.writeMessage(message, new File(p7mOut));
                }
            } else {
                message = loadMessage(inFile);
            }

            KeyStoreKeyProvider basicKeyStore = null;

            if (keyStore != null) {
                basicKeyStore = new KeyStoreKeyProvider(keyStore, "test");

                basicKeyStore.setUseOL2010Workaround(true);
            }

            if (message == null) {
                throw new MissingArgumentException("in file is not specified");
            }

            inspectMessage(message, basicKeyStore, cerOut);
        } else if (commandLine.hasOption("sign")) {
            message = loadMessage(inFile);

            if (message == null) {
                throw new MissingArgumentException("in file is not specified");
            }

            if (StringUtils.isEmpty(outFile)) {
                throw new MissingArgumentException("out file is not specified");
            }

            sign(message, keyStore, alias, password, digest, outFile);
        }
    } catch (MissingArgumentException e) {
        System.err.println("Not all required parameters are specified. " + e);
    } catch (ParseException e) {
        System.err.println("Command line parsing error. " + e);
    } catch (Exception e) {
        logger.error("Some error ocurred", e);
    }
}

From source file:mitm.application.djigzo.tools.CLITool.java

private void setProperty(String email, String domain, boolean global, String property, String value,
        boolean encrypt) throws Exception {
    if (email == null && domain == null && !global) {
        throw new MissingArgumentException("Email, domain or global must be specified");
    }/*  w  w  w. j  a  va  2 s  .c o  m*/

    if (value == null) {
        throw new MissingArgumentException("Value is missing");
    }

    UserPreferencesDTO userPreferences;

    if (email != null) {
        UsersWS usersWS = getUsersWS();

        if (!usersWS.isUser(email)) {
            usersWS.addUser(email);
        }

        userPreferences = getUserWS().getUserPreferences(email);
    } else if (domain != null) {
        DomainsWS domainsWS = getDomainsWS();

        if (!domainsWS.isDomain(domain)) {
            domainsWS.addDomain(domain);
        }

        userPreferences = getDomainWS().getDomainPreferences(domain);
    } else {
        userPreferences = getGlobalPreferencesManagerWS().getGlobalUserPreferences();
    }

    if (StringUtils.isBlank(value)) {
        value = null;
    }

    getHierarchicalPropertiesWS().setProperty(userPreferences, property, value, encrypt);
}

From source file:mitm.application.djigzo.tools.CLITool.java

private void getProperty() throws Exception {
    if (email == null && domain == null && !global) {
        throw new MissingArgumentException("Email, domain or global must be specified");
    }//from  w w w  .  j ava 2s. c om

    UserPreferencesDTO userPreferences;

    if (email != null) {
        if (!EmailAddressUtils.isValid(email)) {
            throw new CLIRuntimeException(email + " is not a valid email address");
        }

        userPreferences = getUserWS().getUserPreferences(email);
    } else if (domain != null) {
        userPreferences = getDomainWS().getDomainPreferences(domain);
    } else {
        userPreferences = getGlobalPreferencesManagerWS().getGlobalUserPreferences();
    }

    if (userPreferences == null) {
        throw new CLIRuntimeException("User or domain does not exist");
    }

    System.out.println(
            getHierarchicalPropertiesWS().getProperty(userPreferences, getPropertyOption.getValue(), encrypt));
}

From source file:mitm.common.tools.SMIME.java

private static void sign(MimeMessage source, KeyStore keyStore, String alias, String password,
        String digestAlgo, String outFile) throws Exception {
    if (StringUtils.isEmpty(alias)) {
        throw new MissingArgumentException("alias is missing.");
    }//from www  .  j a v a  2  s . c  o  m

    KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(password.toCharArray()));

    if (!(entry instanceof KeyStore.PrivateKeyEntry)) {
        throw new KeyStoreException("Key is not a PrivateKeyEntry.");
    }

    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) entry;

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    PrivateKey key = privateKeyEntry.getPrivateKey();

    if (certificate == null) {
        throw new KeyStoreException("Entry does not have a certificate.");
    }

    if (key == null) {
        throw new KeyStoreException("Entry does not have a private key.");
    }

    SMIMESigningAlgorithm signingAlgorithm;

    if (StringUtils.isNotEmpty(digestAlgo)) {
        signingAlgorithm = SMIMESigningAlgorithm.fromName(digestAlgo);

        if (signingAlgorithm == null) {
            throw new IllegalArgumentException(digestAlgo + " is not a valid digest.");
        }
    } else {
        signingAlgorithm = SMIMESigningAlgorithm.SHA1WITHRSA;
    }

    SMIMEBuilder builder = new SMIMEBuilderImpl(source);

    builder.addCertificates(certificate);
    builder.addSigner(key, certificate, signingAlgorithm);

    builder.sign(SMIMESignMode.CLEAR);

    MimeMessage signed = builder.buildMessage();

    if (signed == null) {
        throw new SMIMEException("Message could not be signed");
    }

    MailUtils.writeMessage(signed, new File(outFile));
}