Search in sources :

Example 81 with ParseException

use of org.apache.commons.cli.ParseException in project herd by FINRAOS.

the class DataBridgeApp method parseCommandLineArguments.

/**
 * Parses the command line arguments using the specified argument parser. Common data bridge options will be initialized and added to the argument parser in
 * this method, but any application specific arguments should be added to the argument parser prior to calling this method. Ensure the argParser was set in
 * this class prior to calling this method.
 *
 * @param args the command line arguments.
 * @param applicationContext the Spring application context.
 *
 * @return the return value if the application should exit or null if the application can continue.
 */
// Using System.out to inform user of usage or version information is okay.
@SuppressWarnings("PMD.SystemPrintln")
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE", justification = "We will use the standard carriage return character.")
protected ReturnValue parseCommandLineArguments(String[] args, ApplicationContext applicationContext) {
    // Get the application argument parser.
    ArgumentParser argParser = getArgumentParser();
    try {
        s3AccessKeyOpt = argParser.addArgument("a", "s3AccessKey", true, "S3 access key.", false);
        s3SecretKeyOpt = argParser.addArgument("p", "s3SecretKey", true, "S3 secret key.", false);
        s3EndpointOpt = argParser.addArgument("e", "s3Endpoint", true, "S3 endpoint.", false);
        localPathOpt = argParser.addArgument("l", "localPath", true, "The path to files on your local file system.", true);
        manifestPathOpt = argParser.addArgument("m", "manifestPath", true, "Local path to the manifest file.", true);
        regServerHostOpt = argParser.addArgument("H", "regServerHost", true, "Registration Service hostname.", false);
        regServerPortOpt = argParser.addArgument("P", "regServerPort", true, "Registration Service port.", false);
        dmRegServerHostOpt = argParser.addArgument("Y", "dmRegServerHost", true, "Registration Service hostname (deprecated - use regServerHost).", false);
        dmRegServerPortOpt = argParser.addArgument("Z", "dmRegServerPort", true, "Registration Service port (deprecated - use regServerPort.", false);
        sslOpt = argParser.addArgument("s", "ssl", true, "Enable or disable SSL (HTTPS).", false);
        usernameOpt = argParser.addArgument("u", "username", true, "The username for HTTPS client authentication.", false);
        passwordOpt = argParser.addArgument("w", "password", true, "The password used for HTTPS client authentication.", false);
        helpOpt = argParser.addArgument("h", "help", false, "Display usage information and exit.", false);
        versionOpt = argParser.addArgument("v", "version", false, "Display version information and exit.", false);
        httpProxyHostOpt = argParser.addArgument("n", "httpProxyHost", true, "HTTP proxy host.", false);
        httpProxyPortOpt = argParser.addArgument("o", "httpProxyPort", true, "HTTP proxy port.", false);
        maxThreadsOpt = argParser.addArgument("t", "maxThreads", true, "Maximum number of threads.", false);
        socketTimeoutOpt = argParser.addArgument("c", "socketTimeout", true, "The socket timeout in milliseconds. 0 indicates no timeout. Default 50000.", false);
        // Parse command line arguments without failing on any missing required arguments by passing "false" as the second argument.
        argParser.parseArguments(args, false);
        // If help option was specified, then display usage information and return success.
        if (argParser.getBooleanValue(helpOpt)) {
            System.out.println(argParser.getUsageInformation());
            return ReturnValue.SUCCESS;
        }
        // If version option was specified, then display version information and return success.
        if (argParser.getBooleanValue(versionOpt)) {
            BuildInformation buildInformation = applicationContext.getBean(BuildInformation.class);
            System.out.println(String.format(BUILD_INFO_STRING_FORMAT, buildInformation.getBuildDate(), buildInformation.getBuildNumber(), buildInformation.getBuildOs(), buildInformation.getBuildUser()));
            return ReturnValue.SUCCESS;
        }
        // Parse command line arguments for the second time, enforcing the required arguments by passing "true" as the second argument.
        argParser.parseArguments(args, true);
        // Extract a boolean option value passing "false" as a default value.
        useSsl = argParser.getStringValueAsBoolean(sslOpt, false);
        // Username and password are required when useSsl is enabled.
        if (useSsl && (StringUtils.isBlank(argParser.getStringValue(usernameOpt)) || StringUtils.isBlank(argParser.getStringValue(passwordOpt)))) {
            throw new ParseException("Username and password are required when SSL is enabled.");
        }
        // Ensure that both the S3 secret and access keys were specified or both not specified.
        if (StringUtils.isNotBlank(argParser.getStringValue(s3SecretKeyOpt)) && StringUtils.isBlank(argParser.getStringValue(s3AccessKeyOpt))) {
            throw new ParseException("S3 access key must be specified when S3 secret key is present.");
        }
        if (StringUtils.isNotBlank(argParser.getStringValue(s3AccessKeyOpt)) && StringUtils.isBlank(argParser.getStringValue(s3SecretKeyOpt))) {
            throw new ParseException("S3 secret key must be specified when S3 access key is present.");
        }
        // Get the registration server host
        regServerHost = argParser.getStringValue(regServerHostOpt);
        if (StringUtils.isBlank(regServerHost)) {
            regServerHost = argParser.getStringValue(dmRegServerHostOpt);
            if (StringUtils.isBlank(regServerHost)) {
                throw new ParseException("A registration host must be specified.");
            }
        } else {
            if (StringUtils.isNotBlank(argParser.getStringValue(dmRegServerHostOpt))) {
                throw new ParseException("The regServerHost and the dmRegServerHost options can't both be specified.");
            }
        }
        // Get the registration server port
        regServerPort = argParser.getIntegerValue(regServerPortOpt);
        if (regServerPort == null) {
            regServerPort = argParser.getIntegerValue(dmRegServerPortOpt);
            if (regServerPort == null) {
                throw new ParseException("A registration port must be specified.");
            }
        } else {
            if (argParser.getIntegerValue(dmRegServerPortOpt) != null) {
                throw new ParseException("The regServerPort and the dmRegServerPort options can't both be specified.");
            }
        }
        // Extract all Integer option values here to catch any NumberFormatException exceptions.
        httpProxyPort = argParser.getIntegerValue(httpProxyPortOpt);
        maxThreads = argParser.getIntegerValue(maxThreadsOpt, ToolsCommonConstants.DEFAULT_THREADS);
    } catch (ParseException ex) {
        // Log a friendly error and return a failure which will cause the application to exit.
        LOGGER.error("Error parsing command line arguments: " + ex.getMessage() + "\n" + argParser.getUsageInformation());
        return ReturnValue.FAILURE;
    }
    // The command line arguments were all parsed successfully so return null to continue processing.
    return null;
}
Also used : BuildInformation(org.finra.herd.model.api.xml.BuildInformation) ParseException(org.apache.commons.cli.ParseException) ArgumentParser(org.finra.herd.core.ArgumentParser) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 82 with ParseException

use of org.apache.commons.cli.ParseException in project oozie by apache.

the class TestCLIParser method testCommandParser.

@Test
public void testCommandParser() throws Exception {
    try {
        CLIParser parser = new CLIParser("oozie", new String[] {});
        parser.addCommand("a", "<A>", "AAAAA", new Options(), false);
        CLIParser.Command c = parser.parse(new String[] { "a", "b" });
        assertEquals("a", c.getName());
        assertEquals("b", c.getCommandLine().getArgs()[0]);
    } catch (ParseException ex) {
        fail();
    }
}
Also used : Options(org.apache.commons.cli.Options) ParseException(org.apache.commons.cli.ParseException) Test(org.junit.Test)

Example 83 with ParseException

use of org.apache.commons.cli.ParseException in project oozie by apache.

the class CLIParser method parse.

/**
 * Parse a array of arguments into a command.
 *
 * @param args array of arguments.
 * @return the parsed Command.
 * @throws ParseException thrown if the arguments could not be parsed.
 */
public Command parse(String[] args) throws ParseException {
    if (args.length == 0) {
        throw new ParseException("missing sub-command");
    } else {
        if (commands.containsKey(args[0])) {
            GnuParser parser;
            String[] minusCommand = new String[args.length - 1];
            System.arraycopy(args, 1, minusCommand, 0, minusCommand.length);
            if (args[0].equals(OozieCLI.JOB_CMD)) {
                validdateArgs(args, minusCommand);
                parser = new OozieGnuParser(true);
            } else {
                parser = new OozieGnuParser(false);
            }
            return new Command(args[0], parser.parse(commands.get(args[0]), minusCommand, commandWithArgs.get(args[0])));
        } else {
            throw new ParseException(MessageFormat.format("invalid sub-command [{0}]", args[0]));
        }
    }
}
Also used : GnuParser(org.apache.commons.cli.GnuParser) ParseException(org.apache.commons.cli.ParseException)

Example 84 with ParseException

use of org.apache.commons.cli.ParseException in project atlasdb by palantir.

the class AtlasConsoleMain method run.

public void run(String[] args) {
    try {
        CommandLineParser parser = new GnuParser();
        CommandLine cli = parser.parse(OPTIONS, args);
        if (cli.hasOption(HELP_FLAG_SHORT)) {
            usage();
            new HelpFormatter().printHelp("atlasDBConsole", OPTIONS, true);
            // (authorized)
            System.exit(0);
        }
        System.exit(execute(cli));
    } catch (ParseException e) {
        // (authorized)
        System.out.println("Invalid command line - " + e.getMessage());
        new HelpFormatter().printHelp("atlasDBConsole", OPTIONS, true);
        // (authorized)
        System.exit(1);
    } catch (IOException e) {
        // (authorized)
        System.out.println("Invalid script file input - " + e.getMessage());
        // (authorized)
        System.exit(1);
    }
}
Also used : HelpFormatter(org.apache.commons.cli.HelpFormatter) CommandLine(org.apache.commons.cli.CommandLine) GnuParser(org.apache.commons.cli.GnuParser) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException) IOException(java.io.IOException)

Example 85 with ParseException

use of org.apache.commons.cli.ParseException in project cdap by caskdata.

the class TransactionManagerDebuggerMain method parseArgsAndExecMode.

/**
 * Parse the arguments from the command line and execute the different modes.
 * @param args command line arguments
 * @param conf default configuration
 * @return true if the arguments were parsed successfully and comply with the expected usage
 */
private boolean parseArgsAndExecMode(String[] args, Configuration conf) {
    CommandLineParser parser = new GnuParser();
    // Check all the options of the command line
    try {
        CommandLine line = parser.parse(options, args);
        if (line.hasOption(HELP_OPTION)) {
            printUsage(false);
            return true;
        }
        hostname = line.getOptionValue(HOST_OPTION);
        existingFilename = line.getOptionValue(FILENAME_OPTION);
        persistingFilename = line.hasOption(SAVE_OPTION) ? line.getOptionValue(SAVE_OPTION) : null;
        showTxids = line.hasOption(IDS_OPTION);
        txId = line.hasOption(TRANSACTION_OPTION) ? Long.valueOf(line.getOptionValue(TRANSACTION_OPTION)) : null;
        accessToken = line.hasOption(TOKEN_OPTION) ? line.getOptionValue(TOKEN_OPTION).replaceAll("(\r|\n)", "") : null;
        tokenFile = line.hasOption(TOKEN_FILE_OPTION) ? line.getOptionValue(TOKEN_FILE_OPTION).replaceAll("(\r|\n)", "") : null;
        portNumber = line.hasOption(PORT_OPTION) ? Integer.valueOf(line.getOptionValue(PORT_OPTION)) : conf.getInt(Constants.Router.ROUTER_PORT, Integer.parseInt(Constants.Router.DEFAULT_ROUTER_PORT));
        // if both tokenfile and accessToken are given, just use the access token
        if (tokenFile != null) {
            if (accessToken != null) {
                tokenFile = null;
            } else {
                readTokenFile();
            }
        }
        switch(this.mode) {
            case VIEW:
                if (!line.hasOption(HOST_OPTION) && !line.hasOption(FILENAME_OPTION)) {
                    usage("Either specify a hostname to download a new snapshot, " + "or a filename of an existing snapshot.");
                    return false;
                }
                // Execute mode
                executeViewMode();
                break;
            case INVALIDATE:
                if (!line.hasOption(HOST_OPTION) || !line.hasOption(TRANSACTION_OPTION)) {
                    usage("Specify a host name and a transaction id.");
                    return false;
                }
                // Execute mode
                executeInvalidateMode();
                break;
            case RESET:
                if (!line.hasOption(HOST_OPTION)) {
                    usage("Specify a host name.");
                    return false;
                }
                // Execute mode
                executeResetMode();
                break;
            default:
                printUsage(true);
                return false;
        }
    } catch (ParseException e) {
        printUsage(true);
        return false;
    }
    return true;
}
Also used : CommandLine(org.apache.commons.cli.CommandLine) GnuParser(org.apache.commons.cli.GnuParser) CommandLineParser(org.apache.commons.cli.CommandLineParser) ParseException(org.apache.commons.cli.ParseException)

Aggregations

ParseException (org.apache.commons.cli.ParseException)586 CommandLine (org.apache.commons.cli.CommandLine)488 CommandLineParser (org.apache.commons.cli.CommandLineParser)380 Options (org.apache.commons.cli.Options)370 DefaultParser (org.apache.commons.cli.DefaultParser)220 HelpFormatter (org.apache.commons.cli.HelpFormatter)204 GnuParser (org.apache.commons.cli.GnuParser)173 IOException (java.io.IOException)124 Option (org.apache.commons.cli.Option)109 File (java.io.File)90 PosixParser (org.apache.commons.cli.PosixParser)65 Path (org.apache.hadoop.fs.Path)50 ArrayList (java.util.ArrayList)42 Properties (java.util.Properties)35 BasicParser (org.apache.commons.cli.BasicParser)31 FileInputStream (java.io.FileInputStream)29 Job (org.apache.hadoop.mapreduce.Job)27 Configuration (org.apache.hadoop.conf.Configuration)26 List (java.util.List)25 URI (java.net.URI)21