Search in sources :

Example 11 with BooleanArgument

use of com.unboundid.util.args.BooleanArgument in project ldapsdk by pingidentity.

the class AuthRate method addNonLDAPArguments.

/**
 * Adds the arguments used by this program that aren't already provided by the
 * generic {@code LDAPCommandLineTool} framework.
 *
 * @param  parser  The argument parser to which the arguments should be added.
 *
 * @throws  ArgumentException  If a problem occurs while adding the arguments.
 */
@Override()
public void addNonLDAPArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
    String description = "The base DN to use for the searches.  It may be a " + "simple DN or a value pattern to specify a range of DNs (e.g., " + "\"uid=user.[1-1000],ou=People,dc=example,dc=com\").  See " + ValuePattern.PUBLIC_JAVADOC_URL + " for complete details about the " + "value pattern syntax.  This must be provided.";
    baseDN = new StringArgument('b', "baseDN", true, 1, "{dn}", description);
    baseDN.setArgumentGroupName("Search and Authentication Arguments");
    baseDN.addLongIdentifier("base-dn", true);
    parser.addArgument(baseDN);
    description = "The scope to use for the searches.  It should be 'base', " + "'one', 'sub', or 'subord'.  If this is not provided, a " + "default scope of 'sub' will be used.";
    scopeArg = new ScopeArgument('s', "scope", false, "{scope}", description, SearchScope.SUB);
    scopeArg.setArgumentGroupName("Search and Authentication Arguments");
    parser.addArgument(scopeArg);
    description = "The filter to use for the searches.  It may be a simple " + "filter or a value pattern to specify a range of filters " + "(e.g., \"(uid=user.[1-1000])\").  See " + ValuePattern.PUBLIC_JAVADOC_URL + " for complete details " + "about the value pattern syntax.  This must be provided.";
    filter = new StringArgument('f', "filter", false, 1, "{filter}", description);
    filter.setArgumentGroupName("Search and Authentication Arguments");
    parser.addArgument(filter);
    description = "The name of an attribute to include in entries returned " + "from the searches.  Multiple attributes may be requested " + "by providing this argument multiple times.  If no return " + "attributes are specified, then entries will be returned " + "with all user attributes.";
    attributes = new StringArgument('A', "attribute", false, 0, "{name}", description);
    attributes.setArgumentGroupName("Search and Authentication Arguments");
    parser.addArgument(attributes);
    description = "The password to use when binding as the users returned " + "from the searches.  This must be provided.";
    userPassword = new StringArgument('C', "credentials", true, 1, "{password}", description);
    userPassword.setSensitive(true);
    userPassword.setArgumentGroupName("Search and Authentication Arguments");
    parser.addArgument(userPassword);
    description = "Indicates that the tool should only perform bind " + "operations without the initial search.  If this argument " + "is provided, then the base DN pattern will be used to " + "obtain the bind DNs.";
    bindOnly = new BooleanArgument('B', "bindOnly", 1, description);
    bindOnly.setArgumentGroupName("Search and Authentication Arguments");
    bindOnly.addLongIdentifier("bind-only", true);
    parser.addArgument(bindOnly);
    parser.addRequiredArgumentSet(filter, bindOnly);
    description = "The type of authentication to perform.  Allowed values " + "are:  SIMPLE, CRAM-MD5, DIGEST-MD5, and PLAIN.  If no " + "value is provided, then SIMPLE authentication will be " + "performed.";
    final Set<String> allowedAuthTypes = StaticUtils.setOf("simple", "cram-md5", "digest-md5", "plain");
    authType = new StringArgument('a', "authType", true, 1, "{authType}", description, allowedAuthTypes, "simple");
    authType.setArgumentGroupName("Search and Authentication Arguments");
    authType.addLongIdentifier("auth-type", true);
    parser.addArgument(authType);
    description = "Indicates that bind requests should include the " + "authorization identity request control as described in " + "RFC 3829.";
    authorizationIdentityRequestControl = new BooleanArgument(null, "authorizationIdentityRequestControl", 1, description);
    authorizationIdentityRequestControl.setArgumentGroupName("Request Control Arguments");
    authorizationIdentityRequestControl.addLongIdentifier("authorization-identity-request-control", true);
    parser.addArgument(authorizationIdentityRequestControl);
    description = "Indicates that bind requests should include the " + "password policy request control as described in " + "draft-behera-ldap-password-policy-10.";
    passwordPolicyRequestControl = new BooleanArgument(null, "passwordPolicyRequestControl", 1, description);
    passwordPolicyRequestControl.setArgumentGroupName("Request Control Arguments");
    passwordPolicyRequestControl.addLongIdentifier("password-policy-request-control", true);
    parser.addArgument(passwordPolicyRequestControl);
    description = "Indicates that search requests should include the " + "specified request control.  This may be provided multiple " + "times to include multiple search request controls.";
    searchControl = new ControlArgument(null, "searchControl", false, 0, null, description);
    searchControl.setArgumentGroupName("Request Control Arguments");
    searchControl.addLongIdentifier("search-control", true);
    parser.addArgument(searchControl);
    description = "Indicates that bind requests should include the " + "specified request control.  This may be provided multiple " + "times to include multiple modify request controls.";
    bindControl = new ControlArgument(null, "bindControl", false, 0, null, description);
    bindControl.setArgumentGroupName("Request Control Arguments");
    bindControl.addLongIdentifier("bind-control", true);
    parser.addArgument(bindControl);
    description = "The number of threads to use to perform the " + "authentication processing.  If this is not provided, then " + "a default of one thread will be used.";
    numThreads = new IntegerArgument('t', "numThreads", true, 1, "{num}", description, 1, Integer.MAX_VALUE, 1);
    numThreads.setArgumentGroupName("Rate Management Arguments");
    numThreads.addLongIdentifier("num-threads", true);
    parser.addArgument(numThreads);
    description = "The length of time in seconds between output lines.  If " + "this is not provided, then a default interval of five " + "seconds will be used.";
    collectionInterval = new IntegerArgument('i', "intervalDuration", true, 1, "{num}", description, 1, Integer.MAX_VALUE, 5);
    collectionInterval.setArgumentGroupName("Rate Management Arguments");
    collectionInterval.addLongIdentifier("interval-duration", true);
    parser.addArgument(collectionInterval);
    description = "The maximum number of intervals for which to run.  If " + "this is not provided, then the tool will run until it is " + "interrupted.";
    numIntervals = new IntegerArgument('I', "numIntervals", true, 1, "{num}", description, 1, Integer.MAX_VALUE, Integer.MAX_VALUE);
    numIntervals.setArgumentGroupName("Rate Management Arguments");
    numIntervals.addLongIdentifier("num-intervals", true);
    parser.addArgument(numIntervals);
    description = "The target number of authorizations to perform per " + "second.  It is still necessary to specify a sufficient " + "number of threads for achieving this rate.  If neither " + "this option nor --variableRateData is provided, then the " + "tool will run at the maximum rate for the specified " + "number of threads.";
    ratePerSecond = new IntegerArgument('r', "ratePerSecond", false, 1, "{auths-per-second}", description, 1, Integer.MAX_VALUE);
    ratePerSecond.setArgumentGroupName("Rate Management Arguments");
    ratePerSecond.addLongIdentifier("rate-per-second", true);
    parser.addArgument(ratePerSecond);
    final String variableRateDataArgName = "variableRateData";
    final String generateSampleRateFileArgName = "generateSampleRateFile";
    description = RateAdjustor.getVariableRateDataArgumentDescription(generateSampleRateFileArgName);
    variableRateData = new FileArgument(null, variableRateDataArgName, false, 1, "{path}", description, true, true, true, false);
    variableRateData.setArgumentGroupName("Rate Management Arguments");
    variableRateData.addLongIdentifier("variable-rate-data", true);
    parser.addArgument(variableRateData);
    description = RateAdjustor.getGenerateSampleVariableRateFileDescription(variableRateDataArgName);
    sampleRateFile = new FileArgument(null, generateSampleRateFileArgName, false, 1, "{path}", description, false, true, true, false);
    sampleRateFile.setArgumentGroupName("Rate Management Arguments");
    sampleRateFile.addLongIdentifier("generate-sample-rate-file", true);
    sampleRateFile.setUsageArgument(true);
    parser.addArgument(sampleRateFile);
    parser.addExclusiveArgumentSet(variableRateData, sampleRateFile);
    description = "The number of intervals to complete before beginning " + "overall statistics collection.  Specifying a nonzero " + "number of warm-up intervals gives the client and server " + "a chance to warm up without skewing performance results.";
    warmUpIntervals = new IntegerArgument(null, "warmUpIntervals", true, 1, "{num}", description, 0, Integer.MAX_VALUE, 0);
    warmUpIntervals.setArgumentGroupName("Rate Management Arguments");
    warmUpIntervals.addLongIdentifier("warm-up-intervals", true);
    parser.addArgument(warmUpIntervals);
    description = "Indicates the format to use for timestamps included in " + "the output.  A value of 'none' indicates that no " + "timestamps should be included.  A value of 'with-date' " + "indicates that both the date and the time should be " + "included.  A value of 'without-date' indicates that only " + "the time should be included.";
    final Set<String> allowedFormats = StaticUtils.setOf("none", "with-date", "without-date");
    timestampFormat = new StringArgument(null, "timestampFormat", true, 1, "{format}", description, allowedFormats, "none");
    timestampFormat.addLongIdentifier("timestamp-format", true);
    parser.addArgument(timestampFormat);
    description = "Indicates that information about the result codes for " + "failed operations should not be displayed.";
    suppressErrorsArgument = new BooleanArgument(null, "suppressErrorResultCodes", 1, description);
    suppressErrorsArgument.addLongIdentifier("suppress-error-result-codes", true);
    parser.addArgument(suppressErrorsArgument);
    description = "Generate output in CSV format rather than a " + "display-friendly format";
    csvFormat = new BooleanArgument('c', "csv", 1, description);
    parser.addArgument(csvFormat);
    description = "Specifies the seed to use for the random number generator.";
    randomSeed = new IntegerArgument('R', "randomSeed", false, 1, "{value}", description);
    randomSeed.addLongIdentifier("random-seed", true);
    parser.addArgument(randomSeed);
}
Also used : ControlArgument(com.unboundid.util.args.ControlArgument) ScopeArgument(com.unboundid.util.args.ScopeArgument) BooleanArgument(com.unboundid.util.args.BooleanArgument) IntegerArgument(com.unboundid.util.args.IntegerArgument) FileArgument(com.unboundid.util.args.FileArgument) StringArgument(com.unboundid.util.args.StringArgument)

Example 12 with BooleanArgument

use of com.unboundid.util.args.BooleanArgument in project ldapsdk by pingidentity.

the class Base64Tool method doEncode.

/**
 * Performs the necessary work for base64 encoding.
 *
 * @param  p  The argument parser for the encode subcommand.
 *
 * @return  A result code that indicates whether the processing completed
 *          successfully.
 */
@NotNull()
private ResultCode doEncode(@NotNull final ArgumentParser p) {
    // Get the data to encode.
    final ByteStringBuffer rawDataBuffer = new ByteStringBuffer();
    final StringArgument dataArg = p.getStringArgument(ARG_NAME_DATA);
    if ((dataArg != null) && dataArg.isPresent()) {
        rawDataBuffer.append(dataArg.getValue());
    } else {
        try {
            final InputStream inputStream;
            final FileArgument inputFileArg = p.getFileArgument(ARG_NAME_INPUT_FILE);
            if ((inputFileArg != null) && inputFileArg.isPresent()) {
                inputStream = new FileInputStream(inputFileArg.getValue());
            } else {
                inputStream = in;
            }
            final byte[] buffer = new byte[8192];
            while (true) {
                final int bytesRead = inputStream.read(buffer);
                if (bytesRead <= 0) {
                    break;
                }
                rawDataBuffer.append(buffer, 0, bytesRead);
            }
            inputStream.close();
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, "An error occurred while attempting to read the data to encode:  ", StaticUtils.getExceptionMessage(e));
            return ResultCode.LOCAL_ERROR;
        }
    }
    // If we should ignore any trailing end-of-line markers, then do that now.
    final BooleanArgument ignoreEOLArg = p.getBooleanArgument(ARG_NAME_IGNORE_TRAILING_LINE_BREAK);
    if ((ignoreEOLArg != null) && ignoreEOLArg.isPresent()) {
        stripEOLLoop: while (rawDataBuffer.length() > 0) {
            switch(rawDataBuffer.getBackingArray()[rawDataBuffer.length() - 1]) {
                case '\n':
                case '\r':
                    rawDataBuffer.delete(rawDataBuffer.length() - 1, 1);
                    break;
                default:
                    break stripEOLLoop;
            }
        }
    }
    // Base64-encode the data.
    final byte[] rawDataArray = rawDataBuffer.toByteArray();
    final ByteStringBuffer encodedDataBuffer = new ByteStringBuffer(4 * rawDataBuffer.length() / 3 + 3);
    final BooleanArgument urlArg = p.getBooleanArgument(ARG_NAME_URL);
    if ((urlArg != null) && urlArg.isPresent()) {
        Base64.urlEncode(rawDataArray, 0, rawDataArray.length, encodedDataBuffer, false);
    } else {
        Base64.encode(rawDataArray, encodedDataBuffer);
    }
    // Write the encoded data.
    final FileArgument outputFileArg = p.getFileArgument(ARG_NAME_OUTPUT_FILE);
    if ((outputFileArg != null) && outputFileArg.isPresent()) {
        try {
            final FileOutputStream outputStream = new FileOutputStream(outputFileArg.getValue(), false);
            encodedDataBuffer.write(outputStream);
            outputStream.write(StaticUtils.EOL_BYTES);
            outputStream.flush();
            outputStream.close();
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, "An error occurred while attempting to write the base64-encoded " + "data to output file ", outputFileArg.getValue().getAbsolutePath(), ":  ", StaticUtils.getExceptionMessage(e));
            err("Base64-encoded data:");
            err(encodedDataBuffer.toString());
            return ResultCode.LOCAL_ERROR;
        }
    } else {
        out(encodedDataBuffer.toString());
    }
    return ResultCode.SUCCESS;
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) BooleanArgument(com.unboundid.util.args.BooleanArgument) FileArgument(com.unboundid.util.args.FileArgument) ByteStringBuffer(com.unboundid.util.ByteStringBuffer) FileInputStream(java.io.FileInputStream) ArgumentException(com.unboundid.util.args.ArgumentException) StringArgument(com.unboundid.util.args.StringArgument) NotNull(com.unboundid.util.NotNull)

Example 13 with BooleanArgument

use of com.unboundid.util.args.BooleanArgument in project ldapsdk by pingidentity.

the class Base64Tool method addToolArguments.

/**
 * Adds the command-line arguments supported for use with this tool to the
 * provided argument parser.  The tool may need to retain references to the
 * arguments (and/or the argument parser, if trailing arguments are allowed)
 * to it in order to obtain their values for use in later processing.
 *
 * @param  parser  The argument parser to which the arguments are to be added.
 *
 * @throws  ArgumentException  If a problem occurs while adding any of the
 *                             tool-specific arguments to the provided
 *                             argument parser.
 */
@Override()
public void addToolArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
    this.parser = parser;
    // Create the subcommand for encoding data.
    final ArgumentParser encodeParser = new ArgumentParser("encode", "Base64-encodes raw data.");
    final StringArgument encodeDataArgument = new StringArgument('d', ARG_NAME_DATA, false, 1, "{data}", "The raw data to be encoded.  If neither the --" + ARG_NAME_DATA + " nor the --" + ARG_NAME_INPUT_FILE + " argument is provided, " + "then the data will be read from standard input.");
    encodeDataArgument.addLongIdentifier("rawData", true);
    encodeDataArgument.addLongIdentifier("raw-data", true);
    encodeParser.addArgument(encodeDataArgument);
    final FileArgument encodeDataFileArgument = new FileArgument('f', ARG_NAME_INPUT_FILE, false, 1, null, "The path to a file containing the raw data to be encoded.  If " + "neither the --" + ARG_NAME_DATA + " nor the --" + ARG_NAME_INPUT_FILE + " argument is provided, then the data " + "will be read from standard input.", true, true, true, false);
    encodeDataFileArgument.addLongIdentifier("rawDataFile", true);
    encodeDataFileArgument.addLongIdentifier("input-file", true);
    encodeDataFileArgument.addLongIdentifier("raw-data-file", true);
    encodeParser.addArgument(encodeDataFileArgument);
    final FileArgument encodeOutputFileArgument = new FileArgument('o', ARG_NAME_OUTPUT_FILE, false, 1, null, "The path to a file to which the encoded data should be written.  " + "If this is not provided, the encoded data will be written to " + "standard output.", false, true, true, false);
    encodeOutputFileArgument.addLongIdentifier("toEncodedFile", true);
    encodeOutputFileArgument.addLongIdentifier("output-file", true);
    encodeOutputFileArgument.addLongIdentifier("to-encoded-file", true);
    encodeParser.addArgument(encodeOutputFileArgument);
    final BooleanArgument encodeURLArgument = new BooleanArgument(null, ARG_NAME_URL, "Encode the data with the base64url mechanism rather than the " + "standard base64 mechanism.");
    encodeParser.addArgument(encodeURLArgument);
    final BooleanArgument encodeIgnoreTrailingEOLArgument = new BooleanArgument(null, ARG_NAME_IGNORE_TRAILING_LINE_BREAK, "Ignore any end-of-line marker that may be present at the end of " + "the data to encode.");
    encodeIgnoreTrailingEOLArgument.addLongIdentifier("ignore-trailing-line-break", true);
    encodeParser.addArgument(encodeIgnoreTrailingEOLArgument);
    encodeParser.addExclusiveArgumentSet(encodeDataArgument, encodeDataFileArgument);
    final LinkedHashMap<String[], String> encodeExamples = new LinkedHashMap<>(StaticUtils.computeMapCapacity(3));
    encodeExamples.put(new String[] { "encode", "--data", "Hello" }, "Base64-encodes the string 'Hello' and writes the result to " + "standard output.");
    encodeExamples.put(new String[] { "encode", "--inputFile", "raw-data.txt", "--outputFile", "encoded-data.txt" }, "Base64-encodes the data contained in the 'raw-data.txt' file and " + "writes the result to the 'encoded-data.txt' file.");
    encodeExamples.put(new String[] { "encode" }, "Base64-encodes data read from standard input and writes the result " + "to standard output.");
    final SubCommand encodeSubCommand = new SubCommand(SUBCOMMAND_NAME_ENCODE, "Base64-encodes raw data.", encodeParser, encodeExamples);
    parser.addSubCommand(encodeSubCommand);
    // Create the subcommand for decoding data.
    final ArgumentParser decodeParser = new ArgumentParser("decode", "Decodes base64-encoded data.");
    final StringArgument decodeDataArgument = new StringArgument('d', ARG_NAME_DATA, false, 1, "{data}", "The base64-encoded data to be decoded.  If neither the --" + ARG_NAME_DATA + " nor the --" + ARG_NAME_INPUT_FILE + " argument is provided, then the data will be read from " + "standard input.");
    decodeDataArgument.addLongIdentifier("encodedData", true);
    decodeDataArgument.addLongIdentifier("encoded-data", true);
    decodeParser.addArgument(decodeDataArgument);
    final FileArgument decodeDataFileArgument = new FileArgument('f', ARG_NAME_INPUT_FILE, false, 1, null, "The path to a file containing the base64-encoded data to be " + "decoded.  If neither the --" + ARG_NAME_DATA + " nor the --" + ARG_NAME_INPUT_FILE + " argument is provided, then the data " + "will be read from standard input.", true, true, true, false);
    decodeDataFileArgument.addLongIdentifier("encodedDataFile", true);
    decodeDataFileArgument.addLongIdentifier("input-file", true);
    decodeDataFileArgument.addLongIdentifier("encoded-data-file", true);
    decodeParser.addArgument(decodeDataFileArgument);
    final FileArgument decodeOutputFileArgument = new FileArgument('o', ARG_NAME_OUTPUT_FILE, false, 1, null, "The path to a file to which the decoded data should be written.  " + "If this is not provided, the decoded data will be written to " + "standard output.", false, true, true, false);
    decodeOutputFileArgument.addLongIdentifier("toRawFile", true);
    decodeOutputFileArgument.addLongIdentifier("output-file", true);
    decodeOutputFileArgument.addLongIdentifier("to-raw-file", true);
    decodeParser.addArgument(decodeOutputFileArgument);
    final BooleanArgument decodeURLArgument = new BooleanArgument(null, ARG_NAME_URL, "Decode the data with the base64url mechanism rather than the " + "standard base64 mechanism.");
    decodeParser.addArgument(decodeURLArgument);
    final BooleanArgument decodeAddTrailingLineBreak = new BooleanArgument(null, ARG_NAME_ADD_TRAILING_LINE_BREAK, "Add a line break to the end of the decoded data.");
    decodeAddTrailingLineBreak.addLongIdentifier("add-trailing-line-break", true);
    decodeParser.addArgument(decodeAddTrailingLineBreak);
    decodeParser.addExclusiveArgumentSet(decodeDataArgument, decodeDataFileArgument);
    final LinkedHashMap<String[], String> decodeExamples = new LinkedHashMap<>(StaticUtils.computeMapCapacity(3));
    decodeExamples.put(new String[] { "decode", "--data", "SGVsbG8=" }, "Base64-decodes the string 'SGVsbG8=' and writes the result to " + "standard output.");
    decodeExamples.put(new String[] { "decode", "--inputFile", "encoded-data.txt", "--outputFile", "decoded-data.txt" }, "Base64-decodes the data contained in the 'encoded-data.txt' file " + "and writes the result to the 'raw-data.txt' file.");
    decodeExamples.put(new String[] { "decode" }, "Base64-decodes data read from standard input and writes the result " + "to standard output.");
    final SubCommand decodeSubCommand = new SubCommand(SUBCOMMAND_NAME_DECODE, "Decodes base64-encoded data.", decodeParser, decodeExamples);
    parser.addSubCommand(decodeSubCommand);
}
Also used : SubCommand(com.unboundid.util.args.SubCommand) BooleanArgument(com.unboundid.util.args.BooleanArgument) FileArgument(com.unboundid.util.args.FileArgument) ArgumentParser(com.unboundid.util.args.ArgumentParser) StringArgument(com.unboundid.util.args.StringArgument) LinkedHashMap(java.util.LinkedHashMap)

Example 14 with BooleanArgument

use of com.unboundid.util.args.BooleanArgument in project ldapsdk by pingidentity.

the class IndentLDAPFilter method addToolArguments.

/**
 * Adds the command-line arguments supported for use with this tool to the
 * provided argument parser.  The tool may need to retain references to the
 * arguments (and/or the argument parser, if trailing arguments are allowed)
 * to it in order to obtain their values for use in later processing.
 *
 * @param  parser  The argument parser to which the arguments are to be added.
 *
 * @throws  ArgumentException  If a problem occurs while adding any of the
 *                             tool-specific arguments to the provided
 *                             argument parser.
 */
@Override()
public void addToolArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
    this.parser = parser;
    final IntegerArgument indentColumnsArg = new IntegerArgument(null, ARG_INDENT_SPACES, false, 1, "{numSpaces}", "Specifies the number of spaces that should be used to indent each " + "additional level of filter hierarchy.  A value of zero " + "indicates that the hierarchy should be displayed without any " + "additional indenting.  If this argument is not provided, a " + "default indent of two spaces will be used.", 0, Integer.MAX_VALUE, 2);
    indentColumnsArg.addLongIdentifier("indentSpaces", true);
    indentColumnsArg.addLongIdentifier("indent-columns", true);
    indentColumnsArg.addLongIdentifier("indentColumns", true);
    indentColumnsArg.addLongIdentifier("indent", true);
    parser.addArgument(indentColumnsArg);
    final BooleanArgument doNotSimplifyArg = new BooleanArgument(null, ARG_DO_NOT_SIMPLIFY, 1, "Indicates that the tool should not make any attempt to simplify " + "the provided filter.  If this argument is not provided, then " + "the tool will try to simplify the provided filter (for " + "example, by removing unnecessary levels of hierarchy, like an " + "AND embedded in an AND).");
    doNotSimplifyArg.addLongIdentifier("doNotSimplify", true);
    doNotSimplifyArg.addLongIdentifier("do-not-simplify-filter", true);
    doNotSimplifyArg.addLongIdentifier("doNotSimplifyFilter", true);
    doNotSimplifyArg.addLongIdentifier("dont-simplify", true);
    doNotSimplifyArg.addLongIdentifier("dontSimplify", true);
    doNotSimplifyArg.addLongIdentifier("dont-simplify-filter", true);
    doNotSimplifyArg.addLongIdentifier("dontSimplifyFilter", true);
    parser.addArgument(doNotSimplifyArg);
}
Also used : IntegerArgument(com.unboundid.util.args.IntegerArgument) BooleanArgument(com.unboundid.util.args.BooleanArgument)

Example 15 with BooleanArgument

use of com.unboundid.util.args.BooleanArgument in project ldapsdk by pingidentity.

the class CommandLineToolInteractiveModeProcessor method promptForLDAPArguments.

/**
 * Interactively prompts for the arguments used to connect and optionally
 * authenticate to the directory server.
 *
 * @param  argList  The list to which the string representations of all LDAP
 *                  arguments should be added.
 * @param  test     Indicates whether to attempt to use the arguments to
 *                  establish an LDAP connection.
 *
 * @throws  LDAPException  If a problem is encountered while interacting with
 *                         the user, or if the user wants to quit.
 */
private void promptForLDAPArguments(@NotNull final List<String> argList, final boolean test) throws LDAPException {
    final LDAPCommandLineTool ldapTool = (LDAPCommandLineTool) tool;
    argList.clear();
    // Get the address of the directory server.
    final String defaultHostname;
    final StringArgument hostnameArgument = parser.getStringArgument("hostname");
    if (hostnameArgument.isPresent()) {
        defaultHostname = hostnameArgument.getValue();
    } else {
        defaultHostname = "localhost";
    }
    ArgumentHelper.reset(hostnameArgument);
    final String hostname = promptForString(INFO_INTERACTIVE_LDAP_PROMPT_HOST.get(), defaultHostname, true);
    ArgumentHelper.addValueSuppressException(hostnameArgument, hostname);
    argList.add("--hostname");
    argList.add(hostname);
    // If this tool is running with access to Directory Server data, and if the
    // selected hostname is "localhost" or a loopback address, then try to load
    // information about the server's connection handlers.
    List<LDAPConnectionHandlerConfiguration> serverListenerConfigs = null;
    final File dsInstanceRoot = InternalSDKHelper.getPingIdentityServerRoot();
    if (dsInstanceRoot != null) {
        final File configFile = StaticUtils.constructPath(dsInstanceRoot, "config", "config.ldif");
        if (configFile.exists() && configFile.isFile()) {
            try {
                serverListenerConfigs = LDAPConnectionHandlerConfiguration.readConfiguration(configFile, true);
            } catch (final Exception e) {
                Debug.debugException(e);
            }
        }
    }
    // Determine the type of connection security to use.
    final BooleanArgument useSSLArgument = parser.getBooleanArgument("useSSL");
    final BooleanArgument useStartTLSArgument = parser.getBooleanArgument("useStartTLS");
    final String defaultSecurityChoice;
    if (useSSLArgument.isPresent()) {
        defaultSecurityChoice = "1";
    } else if (useStartTLSArgument.isPresent()) {
        defaultSecurityChoice = "3";
    } else if ((serverListenerConfigs != null) && (!serverListenerConfigs.isEmpty())) {
        final LDAPConnectionHandlerConfiguration cfg = serverListenerConfigs.get(0);
        if (cfg.usesSSL()) {
            defaultSecurityChoice = "1";
        } else if (cfg.supportsStartTLS()) {
            defaultSecurityChoice = "3";
        } else {
            defaultSecurityChoice = "5";
        }
    } else {
        defaultSecurityChoice = "1";
    }
    ArgumentHelper.reset(useSSLArgument);
    ArgumentHelper.reset(useStartTLSArgument);
    final boolean useSSL;
    final boolean useStartTLS;
    final boolean defaultTrust;
    final int securityType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_SECURITY_PROMPT.get(), false, defaultSecurityChoice, INFO_INTERACTIVE_LDAP_SECURITY_OPTION_SSL_DEFAULT.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_SSL_MANUAL.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_START_TLS_DEFAULT.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_START_TLS_MANUAL.get(), INFO_INTERACTIVE_LDAP_SECURITY_OPTION_NONE.get());
    switch(securityType) {
        case 0:
            useSSL = true;
            useStartTLS = false;
            defaultTrust = true;
            argList.add("--useSSL");
            ArgumentHelper.incrementOccurrencesSuppressException(useSSLArgument);
            break;
        case 1:
            useSSL = true;
            useStartTLS = false;
            defaultTrust = false;
            argList.add("--useSSL");
            ArgumentHelper.incrementOccurrencesSuppressException(useSSLArgument);
            break;
        case 2:
            useSSL = false;
            useStartTLS = true;
            defaultTrust = true;
            argList.add("--useStartTLS");
            ArgumentHelper.incrementOccurrencesSuppressException(useStartTLSArgument);
            break;
        case 3:
            useSSL = false;
            useStartTLS = true;
            defaultTrust = false;
            argList.add("--useStartTLS");
            ArgumentHelper.incrementOccurrencesSuppressException(useStartTLSArgument);
            break;
        case 4:
        default:
            useSSL = false;
            useStartTLS = false;
            defaultTrust = false;
            break;
    }
    // If we are to use security without default trust configuration, then
    // prompt for the appropriate settings.
    BindRequest bindRequest = null;
    boolean trustAll = false;
    byte[] keyStorePIN = null;
    byte[] trustStorePIN = null;
    File keyStorePath = null;
    File trustStorePath = null;
    String certificateNickname = null;
    String keyStoreFormat = null;
    String trustStoreFormat = null;
    final StringArgument keyStorePasswordArgument = parser.getStringArgument("keyStorePassword");
    final StringArgument trustStorePasswordArgument = parser.getStringArgument("trustStorePassword");
    final StringArgument saslOptionArgument = parser.getStringArgument("saslOption");
    if (!defaultTrust) {
        // If the user wants to connect securely, then get the appropriate set of
        // arguments pertaining to key and trust managers.
        ArgumentHelper.reset(keyStorePasswordArgument);
        ArgumentHelper.reset(trustStorePasswordArgument);
        ArgumentHelper.reset(parser.getNamedArgument("keyStorePasswordFile"));
        ArgumentHelper.reset(parser.getNamedArgument("promptForKeyStorePassword"));
        ArgumentHelper.reset(parser.getNamedArgument("trustStorePasswordFile"));
        ArgumentHelper.reset(parser.getNamedArgument("promptForTrustStorePassword"));
        if (useSSL || useStartTLS) {
            final StringArgument keyStorePathArgument = parser.getStringArgument("keyStorePath");
            final StringArgument keyStoreFormatArgument = parser.getStringArgument("keyStoreFormat");
            // Determine if a client certificate should be presented.
            final String defaultStoreTypeChoice;
            if (keyStoreFormatArgument.isPresent()) {
                final String format = keyStoreFormatArgument.getValue();
                if (format.equalsIgnoreCase(CryptoHelper.KEY_STORE_TYPE_PKCS_12)) {
                    defaultStoreTypeChoice = "3";
                } else {
                    defaultStoreTypeChoice = "2";
                }
            } else if (keyStorePathArgument.isPresent()) {
                defaultStoreTypeChoice = "2";
            } else {
                defaultStoreTypeChoice = "1";
            }
            final String defaultKeyStorePath;
            if (keyStorePathArgument.isPresent()) {
                defaultKeyStorePath = keyStorePathArgument.getValue();
            } else {
                defaultKeyStorePath = null;
            }
            final String defaultCertNickname;
            final StringArgument certNicknameArgument = parser.getStringArgument("certNickname");
            if (certNicknameArgument.isPresent()) {
                defaultCertNickname = certNicknameArgument.getValue();
            } else {
                defaultCertNickname = null;
            }
            ArgumentHelper.reset(keyStorePathArgument);
            ArgumentHelper.reset(keyStoreFormatArgument);
            ArgumentHelper.reset(certNicknameArgument);
            final int keystoreType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_CLIENT_CERT_PROMPT.get(), false, defaultStoreTypeChoice, INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_NO.get(), INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_JKS.get(), INFO_INTERACTIVE_LDAP_CLIENT_CERT_OPTION_PKCS12.get());
            ArgumentHelper.reset(keyStoreFormatArgument);
            switch(keystoreType) {
                case 1:
                    keyStoreFormat = CryptoHelper.KEY_STORE_TYPE_JKS;
                    break;
                case 2:
                    keyStoreFormat = CryptoHelper.KEY_STORE_TYPE_PKCS_12;
                    break;
                case 0:
                default:
                    break;
            }
            if (keyStoreFormat != null) {
                ArgumentHelper.addValueSuppressException(keyStoreFormatArgument, keyStoreFormat);
                // Get the path to the keystore file.
                keyStorePath = promptForPath(INFO_INTERACTIVE_LDAP_KEYSTORE_PATH_PROMPT.get(), defaultKeyStorePath, true, true, true, true, false);
                argList.add("--keyStorePath");
                argList.add(keyStorePath.getAbsolutePath());
                ArgumentHelper.addValueSuppressException(keyStorePathArgument, keyStorePath.getAbsolutePath());
                // Get the PIN needed to access the keystore.
                keyStorePIN = promptForPassword(INFO_INTERACTIVE_LDAP_KEYSTORE_PIN_PROMPT.get(), null, false);
                if (keyStorePIN != null) {
                    argList.add("--keyStorePassword");
                    argList.add("***REDACTED***");
                    ArgumentHelper.addValueSuppressException(keyStorePasswordArgument, StaticUtils.toUTF8String(keyStorePIN));
                }
                argList.add("--keyStoreFormat");
                argList.add(keyStoreFormat);
                certificateNickname = promptForString(INFO_INTERACTIVE_LDAP_CERT_NICKNAME_PROMPT.get(), defaultCertNickname, false);
                if (certificateNickname != null) {
                    argList.add("--certNickname");
                    argList.add(certificateNickname);
                    ArgumentHelper.addValueSuppressException(certNicknameArgument, certificateNickname);
                }
                if (ldapTool.supportsAuthentication() && promptForYesNo(INFO_INTERACTIVE_LDAP_CERT_AUTH_PROMPT.get(), false, true)) {
                    bindRequest = new EXTERNALBindRequest();
                    argList.add("--saslOption");
                    argList.add("mech=EXTERNAL");
                    ArgumentHelper.reset(saslOptionArgument);
                    ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=EXTERNAL");
                }
            }
            // Determine how to trust the server certificate.
            final BooleanArgument trustAllArgument = parser.getBooleanArgument("trustAll");
            final StringArgument trustStorePathArgument = parser.getStringArgument("trustStorePath");
            final StringArgument trustStoreFormatArgument = parser.getStringArgument("trustStoreFormat");
            final String defaultTrustTypeChoice;
            if (trustAllArgument.isPresent()) {
                defaultTrustTypeChoice = "4";
            } else if (trustStoreFormatArgument.isPresent()) {
                final String format = trustStoreFormatArgument.getValue();
                if (format.equalsIgnoreCase(CryptoHelper.KEY_STORE_TYPE_PKCS_12)) {
                    defaultTrustTypeChoice = "3";
                } else {
                    defaultTrustTypeChoice = "2";
                }
            } else if (trustStorePathArgument.isPresent()) {
                defaultTrustTypeChoice = "2";
            } else {
                defaultTrustTypeChoice = "1";
            }
            final String defaultTrustStorePath;
            if (trustStorePathArgument.isPresent()) {
                defaultTrustStorePath = trustStorePathArgument.getValue();
            } else {
                defaultTrustStorePath = null;
            }
            ArgumentHelper.reset(trustAllArgument);
            ArgumentHelper.reset(trustStorePathArgument);
            ArgumentHelper.reset(trustStoreFormatArgument);
            final int trustType = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_TRUST_PROMPT.get(), false, defaultTrustTypeChoice, INFO_INTERACTIVE_LDAP_TRUST_OPTION_PROMPT.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_JKS.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_PKCS12.get(), INFO_INTERACTIVE_LDAP_TRUST_OPTION_BLIND.get());
            switch(trustType) {
                case 1:
                    trustStoreFormat = CryptoHelper.KEY_STORE_TYPE_JKS;
                    break;
                case 2:
                    trustStoreFormat = CryptoHelper.KEY_STORE_TYPE_PKCS_12;
                    break;
                case 3:
                    trustAll = true;
                    argList.add("--trustAll");
                    ArgumentHelper.incrementOccurrencesSuppressException(trustAllArgument);
                    break;
                case 0:
                default:
                    // We will interactively prompt the user about whether to trust the
                    // certificate in the test section below.  However, to avoid
                    // prompting the user twice, we will configure the tool behind the
                    // scenes to trust all certificates.
                    ArgumentHelper.incrementOccurrencesSuppressException(trustAllArgument);
                    break;
            }
            if (trustStoreFormat != null) {
                ArgumentHelper.addValueSuppressException(trustStoreFormatArgument, trustStoreFormat);
                // Get the path to the truststore file.
                trustStorePath = promptForPath(INFO_INTERACTIVE_LDAP_TRUSTSTORE_PATH_PROMPT.get(), defaultTrustStorePath, true, true, true, true, false);
                argList.add("--trustStorePath");
                argList.add(trustStorePath.getAbsolutePath());
                ArgumentHelper.addValueSuppressException(trustStorePathArgument, trustStorePath.getAbsolutePath());
                // Get the PIN needed to access the truststore.
                trustStorePIN = promptForPassword(INFO_INTERACTIVE_LDAP_TRUSTSTORE_PIN_PROMPT.get(), null, false);
                if (trustStorePIN != null) {
                    argList.add("--trustStorePassword");
                    argList.add("***REDACTED***");
                    ArgumentHelper.addValueSuppressException(trustStorePasswordArgument, StaticUtils.toUTF8String(trustStorePIN));
                }
                argList.add("--trustStoreFormat");
                argList.add(trustStoreFormat);
            }
        } else {
            ArgumentHelper.reset(parser.getNamedArgument("keyStorePath"));
            ArgumentHelper.reset(parser.getNamedArgument("keyStoreFormat"));
            ArgumentHelper.reset(parser.getNamedArgument("trustStorePath"));
            ArgumentHelper.reset(parser.getNamedArgument("trustStoreFormat"));
            ArgumentHelper.reset(parser.getNamedArgument("certNickname"));
        }
    }
    // Get the port of the directory server.
    int defaultPort;
    final IntegerArgument portArgument = parser.getIntegerArgument("port");
    if (portArgument.getNumOccurrences() > 0) {
        // Note -- We're using getNumOccurrences here because isPresent also
        // returns true if there is a default value, and that could be wrong in
        // this case because the default value doesn't know about SSL.
        defaultPort = portArgument.getValue();
    } else if (useSSL) {
        defaultPort = 636;
        if (serverListenerConfigs != null) {
            for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
                if (cfg.usesSSL()) {
                    defaultPort = cfg.getPort();
                    break;
                }
            }
        }
    } else if (useStartTLS) {
        defaultPort = 389;
        if (serverListenerConfigs != null) {
            for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
                if (cfg.supportsStartTLS()) {
                    defaultPort = cfg.getPort();
                    break;
                }
            }
        }
    } else {
        defaultPort = 389;
        if (serverListenerConfigs != null) {
            for (final LDAPConnectionHandlerConfiguration cfg : serverListenerConfigs) {
                if (!cfg.usesSSL()) {
                    defaultPort = cfg.getPort();
                    break;
                }
            }
        }
    }
    ArgumentHelper.reset(portArgument);
    final int port = promptForInteger(INFO_INTERACTIVE_LDAP_PROMPT_PORT.get(), defaultPort, 1, 65_535, true);
    argList.add("--port");
    argList.add(String.valueOf(port));
    ArgumentHelper.addValueSuppressException(portArgument, String.valueOf(port));
    // Determine how to authenticate to the directory server.
    if (ldapTool.supportsAuthentication()) {
        final DNArgument bindDNArgument = parser.getDNArgument("bindDN");
        final StringArgument bindPasswordArgument = parser.getStringArgument("bindPassword");
        ArgumentHelper.reset(bindPasswordArgument);
        ArgumentHelper.reset(parser.getNamedArgument("bindPasswordFile"));
        ArgumentHelper.reset(parser.getNamedArgument("promptForBindPassword"));
        if (bindRequest == null) {
            final String defaultAuthTypeChoice;
            final String defaultBindDN;
            if (saslOptionArgument.isPresent()) {
                defaultAuthTypeChoice = "2";
                defaultBindDN = null;
            } else {
                defaultAuthTypeChoice = "1";
                if (bindDNArgument.isPresent()) {
                    defaultBindDN = bindDNArgument.getStringValue();
                } else {
                    defaultBindDN = null;
                }
            }
            ArgumentHelper.reset(bindDNArgument);
            boolean useSimpleAuth = false;
            boolean useSASLAuth = false;
            final int authMethod = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_AUTH_PROMPT.get(), false, defaultAuthTypeChoice, INFO_INTERACTIVE_LDAP_AUTH_OPTION_SIMPLE.get(), INFO_INTERACTIVE_LDAP_AUTH_OPTION_SASL.get(), INFO_INTERACTIVE_LDAP_AUTH_OPTION_NONE.get());
            switch(authMethod) {
                case 0:
                    useSimpleAuth = true;
                    break;
                case 1:
                    useSASLAuth = true;
                    break;
                case 2:
                default:
                    break;
            }
            if (useSimpleAuth) {
                ArgumentHelper.reset(saslOptionArgument);
                final DN bindDN = promptForDN(INFO_INTERACTIVE_LDAP_AUTH_BIND_DN_PROMPT.get(), defaultBindDN, true);
                if (bindDN.isNullDN()) {
                    bindRequest = new SimpleBindRequest();
                    argList.add("--bindDN");
                    argList.add("");
                    argList.add("--bindPassword");
                    argList.add("");
                    ArgumentHelper.addValueSuppressException(bindDNArgument, "");
                    ArgumentHelper.addValueSuppressException(bindPasswordArgument, "");
                } else {
                    final byte[] bindPassword = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
                    bindRequest = new SimpleBindRequest(bindDN, bindPassword);
                    argList.add("--bindDN");
                    argList.add(bindDN.toString());
                    argList.add("--bindPassword");
                    argList.add("***REDACTED***");
                    ArgumentHelper.addValueSuppressException(bindDNArgument, bindDN.toString());
                    ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(bindPassword));
                }
            } else if (useSASLAuth) {
                String defaultMechChoice = null;
                String defaultAuthID = null;
                String defaultAuthzID = null;
                String defaultRealm = null;
                if (saslOptionArgument.isPresent()) {
                    for (final String saslOption : saslOptionArgument.getValues()) {
                        final String lowerOption = StaticUtils.toLowerCase(saslOption);
                        if (lowerOption.equals("mech=cram-md5")) {
                            defaultMechChoice = "1";
                        } else if (lowerOption.equals("mech=digest-md5")) {
                            defaultMechChoice = "2";
                        } else if (lowerOption.equals("mech=plain")) {
                            defaultMechChoice = "3";
                        } else if (lowerOption.startsWith("authid=")) {
                            defaultAuthID = saslOption.substring(7);
                        } else if (lowerOption.startsWith("authzid=")) {
                            defaultAuthzID = saslOption.substring(8);
                        } else if (lowerOption.startsWith("realm=")) {
                            defaultRealm = saslOption.substring(6);
                        }
                    }
                }
                ArgumentHelper.reset(saslOptionArgument);
                final int mech = getNumberedMenuChoice(INFO_INTERACTIVE_LDAP_AUTH_SASL_PROMPT.get(), false, defaultMechChoice, INFO_INTERACTIVE_LDAP_SASL_OPTION_CRAM_MD5.get(), INFO_INTERACTIVE_LDAP_SASL_OPTION_DIGEST_MD5.get(), INFO_INTERACTIVE_LDAP_SASL_OPTION_PLAIN.get());
                switch(mech) {
                    case 0:
                        String authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
                        byte[] pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
                        bindRequest = new CRAMMD5BindRequest(authID, pw);
                        argList.add("--saslOption");
                        argList.add("mech=CRAM-MD5");
                        argList.add("--saslOption");
                        argList.add("authID=" + authID);
                        argList.add("--bindPassword");
                        argList.add("***REDACTED***");
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=CRAM-MD5");
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
                        ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
                        break;
                    case 1:
                        authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
                        String authzID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHZID_PROMPT.get(), defaultAuthzID, false);
                        final String realm = promptForString(INFO_INTERACTIVE_LDAP_AUTH_REALM_PROMPT.get(), defaultRealm, false);
                        pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
                        bindRequest = new DIGESTMD5BindRequest(authID, authzID, pw, realm);
                        argList.add("--saslOption");
                        argList.add("mech=DIGEST-MD5");
                        argList.add("--saslOption");
                        argList.add("authID=" + authID);
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=DIGEST-MD5");
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
                        if (authzID != null) {
                            argList.add("--saslOption");
                            argList.add("authzID=" + authzID);
                            ArgumentHelper.addValueSuppressException(saslOptionArgument, "authzID=" + authzID);
                        }
                        if (realm != null) {
                            argList.add("--saslOption");
                            argList.add("realm=" + realm);
                            ArgumentHelper.addValueSuppressException(saslOptionArgument, "realm=" + realm);
                        }
                        argList.add("--bindPassword");
                        argList.add("***REDACTED***");
                        ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
                        break;
                    case 2:
                        authID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHID_PROMPT.get(), defaultAuthID, true);
                        authzID = promptForString(INFO_INTERACTIVE_LDAP_AUTH_AUTHZID_PROMPT.get(), defaultAuthzID, false);
                        pw = promptForPassword(INFO_INTERACTIVE_LDAP_AUTH_PW_PROMPT.get(), null, true);
                        bindRequest = new PLAINBindRequest(authID, authzID, pw);
                        argList.add("--saslOption");
                        argList.add("mech=PLAIN");
                        argList.add("--saslOption");
                        argList.add("authID=" + authID);
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "mech=PLAIN");
                        ArgumentHelper.addValueSuppressException(saslOptionArgument, "authID=" + authID);
                        if (authzID != null) {
                            argList.add("--saslOption");
                            argList.add("authzID=" + authzID);
                            ArgumentHelper.addValueSuppressException(saslOptionArgument, "authzID=" + authzID);
                        }
                        argList.add("--bindPassword");
                        argList.add("***REDACTED***");
                        ArgumentHelper.addValueSuppressException(bindPasswordArgument, StaticUtils.toUTF8String(pw));
                        break;
                }
            }
        } else {
            ArgumentHelper.reset(bindDNArgument);
        }
    }
    if (test) {
        // Perform the necessary initialization for SSL/TLS communication.
        final SSLUtil sslUtil;
        if (useSSL || useStartTLS) {
            final KeyManager keyManager;
            if (keyStorePath == null) {
                keyManager = null;
            } else {
                final char[] pinChars;
                if (keyStorePIN == null) {
                    pinChars = null;
                } else {
                    final String pinString = StaticUtils.toUTF8String(keyStorePIN);
                    pinChars = pinString.toCharArray();
                }
                try {
                    keyManager = new KeyStoreKeyManager(keyStorePath, pinChars, keyStoreFormat, certificateNickname, true);
                } catch (final Exception e) {
                    Debug.debugException(e);
                    tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_KEY_MANAGER.get(StaticUtils.getExceptionMessage(e)));
                    if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                        promptForLDAPArguments(argList, test);
                        return;
                    } else {
                        throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
                    }
                }
            }
            final TrustManager trustManager;
            if (trustAll) {
                trustManager = new TrustAllTrustManager();
            } else if (trustStorePath == null) {
                trustManager = InternalSDKHelper.getPreferredPromptTrustManagerChain(null);
            } else {
                final char[] pinChars;
                if (trustStorePIN == null) {
                    pinChars = null;
                } else {
                    final String pinString = StaticUtils.toUTF8String(trustStorePIN);
                    pinChars = pinString.toCharArray();
                }
                try {
                    trustManager = new TrustStoreTrustManager(trustStorePath, pinChars, trustStoreFormat, true);
                } catch (final Exception e) {
                    Debug.debugException(e);
                    tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_TRUST_MANAGER.get(StaticUtils.getExceptionMessage(e)));
                    if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                        promptForLDAPArguments(argList, test);
                        return;
                    } else {
                        throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
                    }
                }
            }
            sslUtil = new SSLUtil(keyManager, trustManager);
        } else {
            sslUtil = null;
        }
        // Create and establish the connection.
        final LDAPConnection conn;
        if (useSSL) {
            try {
                conn = new LDAPConnection(sslUtil.createSSLSocketFactory());
            } catch (final Exception e) {
                Debug.debugException(e);
                tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CREATE_SOCKET_FACTORY.get(StaticUtils.getExceptionMessage(e)), e);
                if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                    promptForLDAPArguments(argList, test);
                    return;
                } else {
                    throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
                }
            }
        } else {
            conn = new LDAPConnection();
        }
        try {
            try {
                conn.connect(hostname, port);
            } catch (final LDAPException le) {
                Debug.debugException(le);
                tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_CONNECT.get(hostname, port, le.getResultString()));
                if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                    promptForLDAPArguments(argList, test);
                    return;
                } else {
                    throw new LDAPException(le.getResultCode(), "", le);
                }
            }
            // If we should use StartTLS to secure the connection, then do so now.
            if (useStartTLS) {
                try {
                    final ExtendedResult startTLSResult = conn.processExtendedOperation(new StartTLSExtendedRequest(sslUtil.createSSLContext()));
                    if (startTLSResult.getResultCode() != ResultCode.SUCCESS) {
                        throw new LDAPException(startTLSResult);
                    }
                } catch (final Exception e) {
                    Debug.debugException(e);
                    final String msg;
                    if (e instanceof LDAPException) {
                        msg = ((LDAPException) e).getResultString();
                    } else {
                        msg = StaticUtils.getExceptionMessage(e);
                    }
                    tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_PERFORM_STARTTLS.get(msg));
                    if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                        promptForLDAPArguments(argList, test);
                        return;
                    } else {
                        throw new LDAPException(ResultCode.LOCAL_ERROR, "", e);
                    }
                }
            }
            // Authenticate the connection if appropriate.
            if (bindRequest != null) {
                try {
                    conn.bind(bindRequest);
                } catch (final LDAPException le) {
                    Debug.debugException(le);
                    tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_LDAP_CANNOT_AUTHENTICATE.get(le.getResultString()));
                    if (promptForYesNo(INFO_INTERACTIVE_LDAP_RETRY_PROMPT.get(), true, true)) {
                        promptForLDAPArguments(argList, test);
                        return;
                    } else {
                        throw new LDAPException(le.getResultCode(), "", le);
                    }
                }
            }
        } finally {
            conn.close();
        }
    }
}
Also used : TrustStoreTrustManager(com.unboundid.util.ssl.TrustStoreTrustManager) BindRequest(com.unboundid.ldap.sdk.BindRequest) EXTERNALBindRequest(com.unboundid.ldap.sdk.EXTERNALBindRequest) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest) SimpleBindRequest(com.unboundid.ldap.sdk.SimpleBindRequest) PLAINBindRequest(com.unboundid.ldap.sdk.PLAINBindRequest) CRAMMD5BindRequest(com.unboundid.ldap.sdk.CRAMMD5BindRequest) PLAINBindRequest(com.unboundid.ldap.sdk.PLAINBindRequest) DN(com.unboundid.ldap.sdk.DN) TrustAllTrustManager(com.unboundid.util.ssl.TrustAllTrustManager) SSLUtil(com.unboundid.util.ssl.SSLUtil) DNArgument(com.unboundid.util.args.DNArgument) SimpleBindRequest(com.unboundid.ldap.sdk.SimpleBindRequest) IntegerArgument(com.unboundid.util.args.IntegerArgument) DIGESTMD5BindRequest(com.unboundid.ldap.sdk.DIGESTMD5BindRequest) KeyStoreKeyManager(com.unboundid.util.ssl.KeyStoreKeyManager) KeyManager(javax.net.ssl.KeyManager) KeyStoreKeyManager(com.unboundid.util.ssl.KeyStoreKeyManager) LDAPConnectionHandlerConfiguration(com.unboundid.ldap.sdk.unboundidds.LDAPConnectionHandlerConfiguration) BooleanArgument(com.unboundid.util.args.BooleanArgument) CRAMMD5BindRequest(com.unboundid.ldap.sdk.CRAMMD5BindRequest) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) StringArgument(com.unboundid.util.args.StringArgument) TrustManager(javax.net.ssl.TrustManager) TrustAllTrustManager(com.unboundid.util.ssl.TrustAllTrustManager) TrustStoreTrustManager(com.unboundid.util.ssl.TrustStoreTrustManager) EXTERNALBindRequest(com.unboundid.ldap.sdk.EXTERNALBindRequest) LDAPException(com.unboundid.ldap.sdk.LDAPException) ExtendedResult(com.unboundid.ldap.sdk.ExtendedResult) File(java.io.File) StartTLSExtendedRequest(com.unboundid.ldap.sdk.extensions.StartTLSExtendedRequest)

Aggregations

BooleanArgument (com.unboundid.util.args.BooleanArgument)65 StringArgument (com.unboundid.util.args.StringArgument)53 FileArgument (com.unboundid.util.args.FileArgument)51 IntegerArgument (com.unboundid.util.args.IntegerArgument)35 DNArgument (com.unboundid.util.args.DNArgument)25 LDAPException (com.unboundid.ldap.sdk.LDAPException)19 File (java.io.File)19 ArgumentException (com.unboundid.util.args.ArgumentException)18 ASN1BitString (com.unboundid.asn1.ASN1BitString)16 NotNull (com.unboundid.util.NotNull)16 FilterArgument (com.unboundid.util.args.FilterArgument)14 ControlArgument (com.unboundid.util.args.ControlArgument)13 IOException (java.io.IOException)13 UnrecoverableKeyException (java.security.UnrecoverableKeyException)12 ArrayList (java.util.ArrayList)12 KeyStore (java.security.KeyStore)10 ScopeArgument (com.unboundid.util.args.ScopeArgument)9 Certificate (java.security.cert.Certificate)8 ArgumentParser (com.unboundid.util.args.ArgumentParser)7 DN (com.unboundid.ldap.sdk.DN)6