Search in sources :

Example 1 with Argument

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

the class LDAPDebugger 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 {
    this.parser = parser;
    String description = "The address on which to listen for client " + "connections.  If this is not provided, then it will listen on " + "all interfaces.";
    listenAddress = new StringArgument('a', "listenAddress", false, 1, "{address}", description);
    listenAddress.addLongIdentifier("listen-address", true);
    parser.addArgument(listenAddress);
    description = "The port on which to listen for client connections.  If " + "no value is provided, then a free port will be automatically " + "selected.";
    listenPort = new IntegerArgument('L', "listenPort", true, 1, "{port}", description, 0, 65_535, 0);
    listenPort.addLongIdentifier("listen-port", true);
    parser.addArgument(listenPort);
    description = "Use SSL when accepting client connections.  This is " + "independent of the '--useSSL' option, which applies only to " + "communication between the LDAP debugger and the backend server.  " + "If this argument is provided, then either the --keyStorePath or " + "the --generateSelfSignedCertificate argument must also be provided.";
    listenUsingSSL = new BooleanArgument('S', "listenUsingSSL", 1, description);
    listenUsingSSL.addLongIdentifier("listen-using-ssl", true);
    parser.addArgument(listenUsingSSL);
    description = "Generate a self-signed certificate to present to clients " + "when the --listenUsingSSL argument is provided.  This argument " + "cannot be used in conjunction with the --keyStorePath argument.";
    generateSelfSignedCertificate = new BooleanArgument(null, "generateSelfSignedCertificate", 1, description);
    generateSelfSignedCertificate.addLongIdentifier("generate-self-signed-certificate", true);
    parser.addArgument(generateSelfSignedCertificate);
    description = "The path to the output file to be written.  If no value " + "is provided, then the output will be written to standard output.";
    outputFile = new FileArgument('f', "outputFile", false, 1, "{path}", description, false, true, true, false);
    outputFile.addLongIdentifier("output-file", true);
    parser.addArgument(outputFile);
    description = "The path to the a code log file to be written.  If a " + "value is provided, then the tool will generate sample code that " + "corresponds to the requests received from clients.  If no value is " + "provided, then no code log will be generated.";
    codeLogFile = new FileArgument('c', "codeLogFile", false, 1, "{path}", description, false, true, true, false);
    codeLogFile.addLongIdentifier("code-log-file", true);
    parser.addArgument(codeLogFile);
    // If --listenUsingSSL is provided, then either the --keyStorePath argument
    // or the --generateSelfSignedCertificate argument must also be provided.
    final Argument keyStorePathArgument = parser.getNamedArgument("keyStorePath");
    parser.addDependentArgumentSet(listenUsingSSL, keyStorePathArgument, generateSelfSignedCertificate);
    // The --generateSelfSignedCertificate argument cannot be used with any of
    // the arguments pertaining to a key store path.
    final Argument keyStorePasswordArgument = parser.getNamedArgument("keyStorePassword");
    final Argument keyStorePasswordFileArgument = parser.getNamedArgument("keyStorePasswordFile");
    final Argument promptForKeyStorePasswordArgument = parser.getNamedArgument("promptForKeyStorePassword");
    parser.addExclusiveArgumentSet(generateSelfSignedCertificate, keyStorePathArgument);
    parser.addExclusiveArgumentSet(generateSelfSignedCertificate, keyStorePasswordArgument);
    parser.addExclusiveArgumentSet(generateSelfSignedCertificate, keyStorePasswordFileArgument);
    parser.addExclusiveArgumentSet(generateSelfSignedCertificate, promptForKeyStorePasswordArgument);
}
Also used : IntegerArgument(com.unboundid.util.args.IntegerArgument) FileArgument(com.unboundid.util.args.FileArgument) Argument(com.unboundid.util.args.Argument) StringArgument(com.unboundid.util.args.StringArgument) BooleanArgument(com.unboundid.util.args.BooleanArgument) IntegerArgument(com.unboundid.util.args.IntegerArgument) BooleanArgument(com.unboundid.util.args.BooleanArgument) FileArgument(com.unboundid.util.args.FileArgument) StringArgument(com.unboundid.util.args.StringArgument)

Example 2 with Argument

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

the class CommandLineTool method getToolInvocationProvidedArguments.

/**
 * Updates the provided argument list with object pairs that comprise the
 * set of arguments actually provided to this tool on the command line.
 *
 * @param  parser                          The argument parser for this tool.
 *                                         It must not be {@code null}.
 * @param  argumentsSetFromPropertiesFile  A set that includes all arguments
 *                                         set from the properties file.
 * @param  argList                         The list to which the argument
 *                                         information should be added.  It
 *                                         must not be {@code null}.  The
 *                                         first element of each object pair
 *                                         that is added must be
 *                                         non-{@code null}.  The second
 *                                         element in any given pair may be
 *                                         {@code null} if the first element
 *                                         represents the name of an argument
 *                                         that doesn't take any values, the
 *                                         name of the selected subcommand, or
 *                                         an unnamed trailing argument.
 */
private static void getToolInvocationProvidedArguments(@NotNull final ArgumentParser parser, @NotNull final Set<Argument> argumentsSetFromPropertiesFile, @NotNull final List<ObjectPair<String, String>> argList) {
    final String noValue = null;
    final SubCommand subCommand = parser.getSelectedSubCommand();
    if (subCommand != null) {
        argList.add(new ObjectPair<>(subCommand.getPrimaryName(), noValue));
    }
    for (final Argument arg : parser.getNamedArguments()) {
        // Exclude arguments that weren't provided.
        if (!arg.isPresent()) {
            continue;
        }
        // Exclude arguments that were set from the properties file.
        if (argumentsSetFromPropertiesFile.contains(arg)) {
            continue;
        }
        if (arg.takesValue()) {
            for (final String value : arg.getValueStringRepresentations(false)) {
                if (arg.isSensitive()) {
                    argList.add(new ObjectPair<>(arg.getIdentifierString(), "*****REDACTED*****"));
                } else {
                    argList.add(new ObjectPair<>(arg.getIdentifierString(), value));
                }
            }
        } else {
            argList.add(new ObjectPair<>(arg.getIdentifierString(), noValue));
        }
    }
    if (subCommand != null) {
        getToolInvocationProvidedArguments(subCommand.getArgumentParser(), argumentsSetFromPropertiesFile, argList);
    }
    for (final String trailingArgument : parser.getTrailingArguments()) {
        argList.add(new ObjectPair<>(trailingArgument, noValue));
    }
}
Also used : SubCommand(com.unboundid.util.args.SubCommand) FileArgument(com.unboundid.util.args.FileArgument) Argument(com.unboundid.util.args.Argument) BooleanArgument(com.unboundid.util.args.BooleanArgument)

Example 3 with Argument

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

the class CommandLineToolInteractiveModeProcessor method displayInteractiveMenu.

/**
 * Displays a menu that allows the user to supply values for the command-line
 * arguments.  Note that this will not include arguments automatically added
 * by the {@link LDAPCommandLineTool} API.
 *
 * @param  ldapArgs  A list of the arguments used to connect and authenticate
 *                   to the LDAP server(s) in non-interactive mode.  The
 *                   contents of this list may be altered if the user opts to
 *                   change the LDAP connection settings.
 *
 * @return  The tool-specific arguments configured by the user.
 *
 * @throws  LDAPException  If a problem is encountered while interacting with
 *                         the user, or if the user wants to quit.
 */
@NotNull()
private List<String> displayInteractiveMenu(@NotNull final List<String> ldapArgs) throws LDAPException {
    final ArrayList<Argument> args = new ArrayList<>(parser.getNamedArguments());
    if (parser.getSelectedSubCommand() != null) {
        args.addAll(parser.getSelectedSubCommand().getArgumentParser().getNamedArguments());
    }
    final Set<String> usageArguments = CommandLineTool.getUsageArgumentIdentifiers(tool);
    final Set<String> ldapArguments;
    if (tool instanceof LDAPCommandLineTool) {
        ldapArguments = LDAPCommandLineTool.getLongLDAPArgumentIdentifiers(((LDAPCommandLineTool) tool));
    } else {
        ldapArguments = Collections.emptySet();
    }
    int maxIdentifierLength = 0;
    final String trailingArgsIdentifier = INFO_INTERACTIVE_MENU_TRAILING_ARGS_IDENTIFIER.get();
    if (parser.allowsTrailingArguments()) {
        maxIdentifierLength = trailingArgsIdentifier.length();
    }
    final Iterator<Argument> argIterator = args.iterator();
    while (argIterator.hasNext()) {
        final Argument a = argIterator.next();
        final String longID = a.getLongIdentifier();
        if (usageArguments.contains(longID) || ldapArguments.contains(longID)) {
            argIterator.remove();
        } else {
            maxIdentifierLength = Math.max(maxIdentifierLength, a.getIdentifierString().length());
        }
    }
    if (args.isEmpty() && (!parser.allowsTrailingArguments())) {
        return Collections.emptyList();
    } else {
        // value.
        for (final Argument arg : args) {
            if (!arg.isRequired()) {
                continue;
            }
            final List<String> valueStrings = arg.getValueStringRepresentations(true);
            if (!valueStrings.isEmpty()) {
                continue;
            }
            promptForArgument(arg);
        }
        // If the tool requires trailing arguments, then prompt for them.
        if (parser.requiresTrailingArguments()) {
            promptForTrailingArguments();
        }
        argsLoop: while (true) {
            final int maxNumberLength = String.valueOf(args.size()).length();
            final int subsequentIndent = maxNumberLength + maxIdentifierLength + 4;
            tool.out();
            tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_ARG_MENU_PROMPT.get());
            int optionNumber = 1;
            for (final Argument arg : args) {
                List<String> valueStrings = arg.getValueStringRepresentations(true);
                if (arg.isSensitive()) {
                    final int size = valueStrings.size();
                    switch(size) {
                        case 0:
                            // No need to do any thing.
                            break;
                        case 1:
                            valueStrings = Collections.singletonList("***REDACTED***");
                            break;
                        default:
                            valueStrings = new ArrayList<>(size);
                            for (int i = 0; i <= size; i++) {
                                valueStrings.add("***REDACTED" + i + "***");
                            }
                            break;
                    }
                }
                switch(valueStrings.size()) {
                    case 0:
                        tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign(String.valueOf(optionNumber), maxNumberLength), ' ', leftAlign(arg.getIdentifierString(), maxIdentifierLength), " -");
                        break;
                    case 1:
                        tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign(String.valueOf(optionNumber), maxNumberLength), ' ', leftAlign(arg.getIdentifierString(), maxIdentifierLength), " - ", valueStrings.get(0));
                        break;
                    default:
                        tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign(String.valueOf(optionNumber), maxNumberLength), ' ', leftAlign(arg.getIdentifierString(), maxIdentifierLength), " - ", valueStrings.get(0));
                        for (int i = 1; i < valueStrings.size(); i++) {
                            tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("", maxNumberLength), ' ', leftAlign("", maxIdentifierLength), " - ", valueStrings.get(i));
                        }
                        break;
                }
                optionNumber++;
            }
            if (parser.allowsTrailingArguments()) {
                final List<String> trailingArgs = parser.getTrailingArguments();
                switch(trailingArgs.size()) {
                    case 0:
                        tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("t", maxNumberLength), ' ', leftAlign(trailingArgsIdentifier, maxIdentifierLength), " -");
                        break;
                    case 1:
                        tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("t", maxNumberLength), ' ', leftAlign(trailingArgsIdentifier, maxIdentifierLength), " - ", trailingArgs.get(0));
                        break;
                    default:
                        tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("t", maxNumberLength), ' ', leftAlign(trailingArgsIdentifier, maxIdentifierLength), " - ", trailingArgs.get(0));
                        for (int i = 1; i < trailingArgs.size(); i++) {
                            tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("", maxNumberLength), ' ', leftAlign("", maxIdentifierLength), " - ", trailingArgs.get(i));
                        }
                        break;
                }
            }
            tool.out();
            if (tool instanceof LDAPCommandLineTool) {
                final LDAPCommandLineTool ldapTool = (LDAPCommandLineTool) tool;
                if (ldapTool.supportsAuthentication()) {
                    tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "l - ", INFO_INTERACTIVE_MENU_OPTION_REPROMPT_FOR_CONN_AUTH_ARGS.get());
                } else {
                    tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "l - ", INFO_INTERACTIVE_MENU_OPTION_REPROMPT_FOR_CONN_ARGS.get());
                }
            } else if (tool instanceof MultiServerLDAPCommandLineTool) {
                tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "l - ", INFO_INTERACTIVE_MENU_OPTION_REPROMPT_FOR_CONN_AUTH_ARGS.get());
            }
            tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "d - ", INFO_INTERACTIVE_MENU_OPTION_DISPLAY_ARGS.get(tool.getToolName()));
            tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "r - ", INFO_INTERACTIVE_MENU_OPTION_RUN.get(tool.getToolName()));
            tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "q - ", INFO_INTERACTIVE_MENU_OPTION_QUIT.get());
            tool.out();
            tool.getOut().print(INFO_INTERACTIVE_MENU_ENTER_CHOICE_WITHOUT_DEFAULT.get() + ' ');
            final Argument selectedArg;
            try {
                while (true) {
                    final String line = systemInReader.readLine().trim();
                    if (line.equalsIgnoreCase("t") && (tool.getMaxTrailingArguments() != 0)) {
                        promptForTrailingArguments();
                        continue argsLoop;
                    } else if (line.equalsIgnoreCase("l")) {
                        if (tool instanceof LDAPCommandLineTool) {
                            promptForLDAPArguments(ldapArgs, true);
                        } else if (tool instanceof MultiServerLDAPCommandLineTool) {
                            promptForMultiServerLDAPArguments(ldapArgs, true);
                        } else {
                            tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_ARG_MENU_INVALID_CHOICE.get());
                            tool.getOut().print(INFO_INTERACTIVE_MENU_ENTER_CHOICE_WITHOUT_DEFAULT.get() + ' ');
                        }
                        continue argsLoop;
                    } else if (line.equalsIgnoreCase("d")) {
                        try {
                            validateRequiredExclusiveAndDependentArgumentSets();
                            tool.doExtendedArgumentValidation();
                            final ArrayList<String> argStrings = new ArrayList<>(2 * args.size());
                            final SubCommand subcommand = parser.getSelectedSubCommand();
                            if (subcommand != null) {
                                argStrings.add(subcommand.getPrimaryName());
                            }
                            argStrings.addAll(ldapArgs);
                            for (final Argument a : args) {
                                ArgumentHelper.addToCommandLine(a, argStrings);
                            }
                            argStrings.addAll(parser.getTrailingArguments());
                            if (argStrings.isEmpty()) {
                                tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_MENU_NO_CURRENT_ARGS.get(tool.getToolName()));
                            } else {
                                tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_MENU_CURRENT_ARGS_HEADER.get(tool.getToolName()));
                                printArgs(argStrings);
                            }
                            tool.out();
                            promptForString(INFO_INTERACTIVE_MENU_PROMPT_PRESS_ENTER_TO_CONTINUE.get(), null, false);
                            continue argsLoop;
                        } catch (final ArgumentException ae) {
                            Debug.debugException(ae);
                            tool.err();
                            tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_MENU_EXTENDED_VALIDATION_ERRORS.get(ae.getMessage()));
                            tool.err();
                            tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_MENU_CORRECT_VALIDATION_ERRORS.get());
                            tool.err();
                            promptForString(INFO_INTERACTIVE_MENU_PROMPT_PRESS_ENTER_TO_CONTINUE.get(), null, false);
                            continue argsLoop;
                        }
                    } else if (line.equalsIgnoreCase("r")) {
                        try {
                            validateRequiredExclusiveAndDependentArgumentSets();
                            tool.doExtendedArgumentValidation();
                            break argsLoop;
                        } catch (final ArgumentException ae) {
                            Debug.debugException(ae);
                            tool.err();
                            tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_MENU_EXTENDED_VALIDATION_ERRORS.get(ae.getMessage()));
                            tool.err();
                            tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_MENU_CORRECT_VALIDATION_ERRORS.get());
                            tool.err();
                            promptForString(INFO_INTERACTIVE_MENU_PROMPT_PRESS_ENTER_TO_CONTINUE.get(), null, false);
                            continue argsLoop;
                        }
                    } else if (line.equalsIgnoreCase("q")) {
                        throw new LDAPException(ResultCode.SUCCESS, "");
                    }
                    int selectedValue = -1;
                    try {
                        selectedValue = Integer.parseInt(line);
                    } catch (final Exception e) {
                        Debug.debugException(e);
                    }
                    if ((selectedValue < 1) || (selectedValue > args.size())) {
                        tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_ARG_MENU_INVALID_CHOICE.get());
                        tool.getOut().print(INFO_INTERACTIVE_MENU_ENTER_CHOICE_WITHOUT_DEFAULT.get() + ' ');
                    } else {
                        selectedArg = args.get(selectedValue - 1);
                        break;
                    }
                }
            } catch (final LDAPException le) {
                Debug.debugException(le);
                throw le;
            } catch (final Exception e) {
                Debug.debugException(e);
                throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_INTERACTIVE_MENU_CANNOT_READ_CHOICE.get(StaticUtils.getExceptionMessage(e)), e);
            }
            promptForArgument(selectedArg);
        }
        final ArrayList<String> argStrings = new ArrayList<>(2 * args.size());
        for (final Argument a : args) {
            ArgumentHelper.addToCommandLine(a, argStrings);
        }
        argStrings.addAll(parser.getTrailingArguments());
        return argStrings;
    }
}
Also used : SubCommand(com.unboundid.util.args.SubCommand) ControlArgument(com.unboundid.util.args.ControlArgument) IntegerArgument(com.unboundid.util.args.IntegerArgument) ScopeArgument(com.unboundid.util.args.ScopeArgument) BooleanValueArgument(com.unboundid.util.args.BooleanValueArgument) DurationArgument(com.unboundid.util.args.DurationArgument) Argument(com.unboundid.util.args.Argument) DNArgument(com.unboundid.util.args.DNArgument) BooleanArgument(com.unboundid.util.args.BooleanArgument) TimestampArgument(com.unboundid.util.args.TimestampArgument) ArgumentListArgument(com.unboundid.util.args.ArgumentListArgument) FileArgument(com.unboundid.util.args.FileArgument) StringArgument(com.unboundid.util.args.StringArgument) FilterArgument(com.unboundid.util.args.FilterArgument) ArrayList(java.util.ArrayList) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) LDAPException(com.unboundid.ldap.sdk.LDAPException) List(java.util.List) ArrayList(java.util.ArrayList) ArgumentException(com.unboundid.util.args.ArgumentException)

Example 4 with Argument

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

the class LDAPDelete method doExtendedNonLDAPArgumentValidation.

/**
 * {@inheritDoc}
 */
@Override()
public void doExtendedNonLDAPArgumentValidation() throws ArgumentException {
    // to identify entries to delete are provided.
    if (!parser.getTrailingArguments().isEmpty()) {
        for (final Argument a : Arrays.asList(entryDN, dnFile, deleteEntriesMatchingFilter, deleteEntriesMatchingFiltersFromFile)) {
            if (a.isPresent()) {
                throw new ArgumentException(ERR_LDAPDELETE_TRAILING_ARG_CONFLICT.get(a.getIdentifierString()));
            }
        }
    }
    // and pre-create those controls.
    if (routeToBackendSet.isPresent()) {
        final List<String> values = routeToBackendSet.getValues();
        final Map<String, List<String>> idsByRP = new LinkedHashMap<>(StaticUtils.computeMapCapacity(values.size()));
        for (final String value : values) {
            final int colonPos = value.indexOf(':');
            if (colonPos <= 0) {
                throw new ArgumentException(ERR_LDAPDELETE_ROUTE_TO_BACKEND_SET_INVALID_FORMAT.get(value, routeToBackendSet.getIdentifierString()));
            }
            final String rpID = value.substring(0, colonPos);
            final String bsID = value.substring(colonPos + 1);
            List<String> idsForRP = idsByRP.get(rpID);
            if (idsForRP == null) {
                idsForRP = new ArrayList<>(values.size());
                idsByRP.put(rpID, idsForRP);
            }
            idsForRP.add(bsID);
        }
        for (final Map.Entry<String, List<String>> e : idsByRP.entrySet()) {
            final String rpID = e.getKey();
            final List<String> bsIDs = e.getValue();
            routeToBackendSetRequestControls.add(RouteToBackendSetRequestControl.createAbsoluteRoutingRequest(true, rpID, bsIDs));
        }
    }
}
Also used : ControlArgument(com.unboundid.util.args.ControlArgument) IntegerArgument(com.unboundid.util.args.IntegerArgument) DurationArgument(com.unboundid.util.args.DurationArgument) Argument(com.unboundid.util.args.Argument) DNArgument(com.unboundid.util.args.DNArgument) BooleanArgument(com.unboundid.util.args.BooleanArgument) FileArgument(com.unboundid.util.args.FileArgument) StringArgument(com.unboundid.util.args.StringArgument) FilterArgument(com.unboundid.util.args.FilterArgument) List(java.util.List) ArrayList(java.util.ArrayList) ArgumentException(com.unboundid.util.args.ArgumentException) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 5 with Argument

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

the class CommandLineTool method runTool.

/**
 * Performs all processing for this command-line tool.  This includes:
 * <UL>
 *   <LI>Creating the argument parser and populating it using the
 *       {@link #addToolArguments} method.</LI>
 *   <LI>Parsing the provided set of command line arguments, including any
 *       additional validation using the {@link #doExtendedArgumentValidation}
 *       method.</LI>
 *   <LI>Invoking the {@link #doToolProcessing} method to do the appropriate
 *       work for this tool.</LI>
 * </UL>
 *
 * @param  args  The command-line arguments provided to this program.
 *
 * @return  The result of processing this tool.  It should be
 *          {@link ResultCode#SUCCESS} if the tool completed its work
 *          successfully, or some other result if a problem occurred.
 */
@NotNull()
public final ResultCode runTool(@Nullable final String... args) {
    final ArgumentParser parser;
    try {
        parser = createArgumentParser();
        boolean exceptionFromParsingWithNoArgumentsExplicitlyProvided = false;
        if (supportsInteractiveMode() && defaultsToInteractiveMode() && ((args == null) || (args.length == 0))) {
            // arguments when run non-interactively.
            try {
                parser.parse(StaticUtils.NO_STRINGS);
            } catch (final Exception e) {
                Debug.debugException(e);
                exceptionFromParsingWithNoArgumentsExplicitlyProvided = true;
            }
        } else if (args == null) {
            parser.parse(StaticUtils.NO_STRINGS);
        } else {
            parser.parse(args);
        }
        final File generatedPropertiesFile = parser.getGeneratedPropertiesFile();
        if (supportsPropertiesFile() && (generatedPropertiesFile != null)) {
            wrapOut(0, StaticUtils.TERMINAL_WIDTH_COLUMNS - 1, INFO_CL_TOOL_WROTE_PROPERTIES_FILE.get(generatedPropertiesFile.getAbsolutePath()));
            return ResultCode.SUCCESS;
        }
        if (helpArgument.isPresent()) {
            out(parser.getUsageString(StaticUtils.TERMINAL_WIDTH_COLUMNS - 1));
            displayExampleUsages(parser);
            return ResultCode.SUCCESS;
        }
        if ((helpSASLArgument != null) && helpSASLArgument.isPresent()) {
            String mechanism = null;
            final Argument saslOptionArgument = parser.getNamedArgument("saslOption");
            if ((saslOptionArgument != null) && saslOptionArgument.isPresent()) {
                for (final String value : saslOptionArgument.getValueStringRepresentations(false)) {
                    final String lowerValue = StaticUtils.toLowerCase(value);
                    if (lowerValue.startsWith("mech=")) {
                        final String mech = value.substring(5).trim();
                        if (!mech.isEmpty()) {
                            mechanism = mech;
                            break;
                        }
                    }
                }
            }
            out(SASLUtils.getUsageString(mechanism, StaticUtils.TERMINAL_WIDTH_COLUMNS - 1));
            return ResultCode.SUCCESS;
        }
        if ((helpSubcommandsArgument != null) && helpSubcommandsArgument.isPresent()) {
            final TreeMap<String, SubCommand> subCommands = getSortedSubCommands(parser);
            for (final SubCommand sc : subCommands.values()) {
                final StringBuilder nameBuffer = new StringBuilder();
                final Iterator<String> nameIterator = sc.getNames(false).iterator();
                while (nameIterator.hasNext()) {
                    nameBuffer.append(nameIterator.next());
                    if (nameIterator.hasNext()) {
                        nameBuffer.append(", ");
                    }
                }
                out(nameBuffer.toString());
                for (final String descriptionLine : StaticUtils.wrapLine(sc.getDescription(), (StaticUtils.TERMINAL_WIDTH_COLUMNS - 3))) {
                    out("  " + descriptionLine);
                }
                out();
            }
            wrapOut(0, (StaticUtils.TERMINAL_WIDTH_COLUMNS - 1), INFO_CL_TOOL_USE_SUBCOMMAND_HELP.get(getToolName()));
            return ResultCode.SUCCESS;
        }
        if ((versionArgument != null) && versionArgument.isPresent()) {
            out(getToolVersion());
            return ResultCode.SUCCESS;
        }
        // connection attempt is made.
        for (final BooleanArgument a : enableSSLDebuggingArguments) {
            if (a.isPresent()) {
                StaticUtils.setSystemProperty("javax.net.debug", "all");
            }
        }
        boolean extendedValidationDone = false;
        if (interactiveArgument != null) {
            if (interactiveArgument.isPresent() || (defaultsToInteractiveMode() && ((args == null) || (args.length == 0)) && (parser.getArgumentsSetFromPropertiesFile().isEmpty() || exceptionFromParsingWithNoArgumentsExplicitlyProvided))) {
                try {
                    final List<String> interactiveArgs = requestToolArgumentsInteractively(parser);
                    if (interactiveArgs == null) {
                        final CommandLineToolInteractiveModeProcessor processor = new CommandLineToolInteractiveModeProcessor(this, parser);
                        processor.doInteractiveModeProcessing();
                        extendedValidationDone = true;
                    } else {
                        ArgumentHelper.reset(parser);
                        parser.parse(StaticUtils.toArray(interactiveArgs, String.class));
                    }
                } catch (final LDAPException le) {
                    Debug.debugException(le);
                    final String message = le.getMessage();
                    if ((message != null) && (!message.isEmpty())) {
                        err(message);
                    }
                    return le.getResultCode();
                }
            }
        }
        if (!extendedValidationDone) {
            doExtendedArgumentValidation();
        }
    } catch (final ArgumentException ae) {
        Debug.debugException(ae);
        err(ae.getMessage());
        return ResultCode.PARAM_ERROR;
    }
    PrintStream outputFileStream = null;
    if ((outputFileArgument != null) && outputFileArgument.isPresent()) {
        final File outputFile = outputFileArgument.getValue();
        final boolean append = ((appendToOutputFileArgument != null) && appendToOutputFileArgument.isPresent());
        try {
            final FileOutputStream fos = new FileOutputStream(outputFile, append);
            outputFileStream = new PrintStream(fos, true, "UTF-8");
        } catch (final Exception e) {
            Debug.debugException(e);
            err(ERR_CL_TOOL_ERROR_CREATING_OUTPUT_FILE.get(outputFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
            return ResultCode.LOCAL_ERROR;
        }
        if ((teeOutputArgument != null) && teeOutputArgument.isPresent()) {
            out = new PrintStream(new TeeOutputStream(out, outputFileStream));
            err = new PrintStream(new TeeOutputStream(err, outputFileStream));
        } else {
            out = outputFileStream;
            err = outputFileStream;
        }
    }
    try {
        // If any values were selected using a properties file, then display
        // information about them.
        final List<String> argsSetFromPropertiesFiles = parser.getArgumentsSetFromPropertiesFile();
        if ((!argsSetFromPropertiesFiles.isEmpty()) && (!parser.suppressPropertiesFileComment())) {
            for (final String line : StaticUtils.wrapLine(INFO_CL_TOOL_ARGS_FROM_PROPERTIES_FILE.get(parser.getPropertiesFileUsed().getPath()), (StaticUtils.TERMINAL_WIDTH_COLUMNS - 3))) {
                out("# ", line);
            }
            final StringBuilder buffer = new StringBuilder();
            for (final String s : argsSetFromPropertiesFiles) {
                if (s.startsWith("-")) {
                    if (buffer.length() > 0) {
                        out(buffer);
                        buffer.setLength(0);
                    }
                    buffer.append("#      ");
                    buffer.append(s);
                } else {
                    if (buffer.length() == 0) {
                        // This should never happen.
                        buffer.append("#      ");
                    } else {
                        buffer.append(' ');
                    }
                    buffer.append(StaticUtils.cleanExampleCommandLineArgument(s));
                }
            }
            if (buffer.length() > 0) {
                out(buffer);
            }
            out();
        }
        CommandLineToolShutdownHook shutdownHook = null;
        final AtomicReference<ResultCode> exitCode = new AtomicReference<>();
        if (registerShutdownHook()) {
            shutdownHook = new CommandLineToolShutdownHook(this, exitCode);
            Runtime.getRuntime().addShutdownHook(shutdownHook);
        }
        final ToolInvocationLogDetails logDetails = ToolInvocationLogger.getLogMessageDetails(getToolName(), logToolInvocationByDefault(), getErr());
        ToolInvocationLogShutdownHook logShutdownHook = null;
        if (logDetails.logInvocation()) {
            final HashSet<Argument> argumentsSetFromPropertiesFile = new HashSet<>(StaticUtils.computeMapCapacity(10));
            final ArrayList<ObjectPair<String, String>> propertiesFileArgList = new ArrayList<>(10);
            getToolInvocationPropertiesFileArguments(parser, argumentsSetFromPropertiesFile, propertiesFileArgList);
            final ArrayList<ObjectPair<String, String>> providedArgList = new ArrayList<>(10);
            getToolInvocationProvidedArguments(parser, argumentsSetFromPropertiesFile, providedArgList);
            logShutdownHook = new ToolInvocationLogShutdownHook(logDetails);
            Runtime.getRuntime().addShutdownHook(logShutdownHook);
            final String propertiesFilePath;
            if (propertiesFileArgList.isEmpty()) {
                propertiesFilePath = "";
            } else {
                final File propertiesFile = parser.getPropertiesFileUsed();
                if (propertiesFile == null) {
                    propertiesFilePath = "";
                } else {
                    propertiesFilePath = propertiesFile.getAbsolutePath();
                }
            }
            ToolInvocationLogger.logLaunchMessage(logDetails, providedArgList, propertiesFileArgList, propertiesFilePath);
        }
        try {
            exitCode.set(doToolProcessing());
        } catch (final Exception e) {
            Debug.debugException(e);
            err(StaticUtils.getExceptionMessage(e));
            exitCode.set(ResultCode.LOCAL_ERROR);
        } finally {
            if (logShutdownHook != null) {
                Runtime.getRuntime().removeShutdownHook(logShutdownHook);
                String completionMessage = getToolCompletionMessage();
                if (completionMessage == null) {
                    completionMessage = exitCode.get().getName();
                }
                ToolInvocationLogger.logCompletionMessage(logDetails, exitCode.get().intValue(), completionMessage);
            }
            if (shutdownHook != null) {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
            }
        }
        return exitCode.get();
    } finally {
        if (outputFileStream != null) {
            outputFileStream.close();
        }
    }
}
Also used : ToolInvocationLogShutdownHook(com.unboundid.ldap.sdk.unboundidds.tools.ToolInvocationLogShutdownHook) FileArgument(com.unboundid.util.args.FileArgument) Argument(com.unboundid.util.args.Argument) BooleanArgument(com.unboundid.util.args.BooleanArgument) ArrayList(java.util.ArrayList) ArgumentParser(com.unboundid.util.args.ArgumentParser) ArgumentException(com.unboundid.util.args.ArgumentException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PrintStream(java.io.PrintStream) SubCommand(com.unboundid.util.args.SubCommand) ToolInvocationLogDetails(com.unboundid.ldap.sdk.unboundidds.tools.ToolInvocationLogDetails) BooleanArgument(com.unboundid.util.args.BooleanArgument) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) LDAPException(com.unboundid.ldap.sdk.LDAPException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) ResultCode(com.unboundid.ldap.sdk.ResultCode)

Aggregations

Argument (com.unboundid.util.args.Argument)11 BooleanArgument (com.unboundid.util.args.BooleanArgument)9 FileArgument (com.unboundid.util.args.FileArgument)9 StringArgument (com.unboundid.util.args.StringArgument)7 IntegerArgument (com.unboundid.util.args.IntegerArgument)6 ArrayList (java.util.ArrayList)6 SubCommand (com.unboundid.util.args.SubCommand)5 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)4 LDAPException (com.unboundid.ldap.sdk.LDAPException)4 ArgumentException (com.unboundid.util.args.ArgumentException)4 DurationArgument (com.unboundid.util.args.DurationArgument)4 TimestampArgument (com.unboundid.util.args.TimestampArgument)4 ArgumentParser (com.unboundid.util.args.ArgumentParser)3 DNArgument (com.unboundid.util.args.DNArgument)3 FilterArgument (com.unboundid.util.args.FilterArgument)3 BooleanValueArgument (com.unboundid.util.args.BooleanValueArgument)2 ControlArgument (com.unboundid.util.args.ControlArgument)2 ScopeArgument (com.unboundid.util.args.ScopeArgument)2 Method (java.lang.reflect.Method)2 List (java.util.List)2