Search in sources :

Example 6 with Argument

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

the class ManageAccountTestCase method testAllSuccessResult.

/**
 * Tests the behavior when running the tool and expecting a success result.
 *
 * @throws  Exception  If an unexpected problem occurs.
 */
@Test()
public void testAllSuccessResult() throws Exception {
    // Get an instance of the manage-account tool that we will run to generate a
    // sample variable rate data file.  Not only can we use this file to get
    // test coverage later, but we can also use the tool instance to get the
    // argument parser available so that we can introspect it to get information
    // about what arguments we can use.
    final String variableRateDataFile = createTempFile().getAbsolutePath();
    final ManageAccount tool = new ManageAccount(null, null);
    assertEquals(tool.runTool("--generateSampleRateFile", variableRateDataFile), ResultCode.SUCCESS);
    final ArgumentParser parser = tool.getArgumentParser();
    assertNotNull(parser);
    // Create some other files that will be used for testing.
    final String rejectFile = createTempFile().getAbsolutePath();
    final String dnFile = createTempFile("# Comment at the top", "uid=user.1,ou=People,dc=example,dc=com", "# Comment in the middle. Also, blank line follows.", "", "uid=user.2,ou=People,dc=example,dc=com", "dn:uid=user.3,ou=People,dc=example,dc=com", "dn: uid=user.4,ou=People,dc=example,dc=com", "dn::" + Base64.encode("uid=user.5,ou=People,dc=example,dc=com"), "dn:: " + Base64.encode("uid=user.6,ou=People,dc=example,dc=com"), "", "# Comment at the end").getAbsolutePath();
    // Create an in-memory directory server instance with fake support for the
    // password policy state extended operation.
    final InMemoryDirectoryServerConfig cfg = new InMemoryDirectoryServerConfig("dc=example,dc=com");
    final String[] referralURLs = { "ldap://ds1.example.com:389/dc=example,dc=com", "ldap://ds2.example.com:389/dc=example,dc=com" };
    final PasswordPolicyStateOperation[] resultOperations = { new PasswordPolicyStateOperation(PasswordPolicyStateOperation.OP_TYPE_GET_ACCOUNT_DISABLED_STATE, new ASN1OctetString[] { new ASN1OctetString("false") }), new PasswordPolicyStateOperation(PasswordPolicyStateOperation.OP_TYPE_GET_FAILURE_LOCKOUT_TIME, null), new PasswordPolicyStateOperation(PasswordPolicyStateOperation.OP_TYPE_GET_ACCOUNT_USABILITY_NOTICES, new ASN1OctetString[] { new ASN1OctetString(new PasswordPolicyStateAccountUsabilityNotice(PasswordPolicyStateAccountUsabilityNotice.NOTICE_TYPE_IN_MINIMUM_PASSWORD_AGE, PasswordPolicyStateAccountUsabilityNotice.NOTICE_NAME_IN_MINIMUM_PASSWORD_AGE, "notice message").toString()), new ASN1OctetString("Notice 2") }), new PasswordPolicyStateOperation(PasswordPolicyStateOperation.OP_TYPE_GET_ACCOUNT_USABILITY_WARNINGS, new ASN1OctetString[] { new ASN1OctetString(new PasswordPolicyStateAccountUsabilityWarning(PasswordPolicyStateAccountUsabilityWarning.WARNING_TYPE_ACCOUNT_EXPIRING, PasswordPolicyStateAccountUsabilityWarning.WARNING_NAME_ACCOUNT_EXPIRING, "warning message").toString()), new ASN1OctetString("Warning 2") }), new PasswordPolicyStateOperation(PasswordPolicyStateOperation.OP_TYPE_GET_ACCOUNT_USABILITY_ERRORS, new ASN1OctetString[] { new ASN1OctetString(new PasswordPolicyStateAccountUsabilityError(PasswordPolicyStateAccountUsabilityError.ERROR_TYPE_ACCOUNT_EXPIRED, PasswordPolicyStateAccountUsabilityError.ERROR_NAME_ACCOUNT_EXPIRED, "error message").toString()), new ASN1OctetString("Error 2") }) };
    cfg.addExtendedOperationHandler(new CannedResponsePWPStateInMemoryExtendedOperationHandler(new PasswordPolicyStateExtendedResult(-1, ResultCode.SUCCESS, "Success", "ou=Matched DN,dc=example,dc=com", referralURLs, "uid=test.user,ou=People,dc=example,dc=com", resultOperations, null)));
    final InMemoryDirectoryServer ds = new InMemoryDirectoryServer(cfg);
    ds.startListening();
    try {
        final ArrayList<String> argList = new ArrayList<String>(20);
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        for (final ManageAccountSubCommandType t : ManageAccountSubCommandType.values()) {
            for (final String name : t.getAllNames()) {
                argList.clear();
                argList.add(name);
                argList.add("--hostname");
                argList.add("127.0.0.1");
                argList.add("--port");
                argList.add(String.valueOf(ds.getListenPort()));
                argList.add("--targetDN");
                argList.add("uid=test.user,ou=People,dc=example,dc=com");
                final SubCommand sc = parser.getSubCommand(name);
                assertNotNull(sc);
                final ArgumentParser subCommandParser = sc.getArgumentParser();
                final Argument a = subCommandParser.getNamedArgument('O');
                if (a == null) {
                    String[] args = argList.toArray(StaticUtils.NO_STRINGS);
                    assertEquals(ManageAccount.main(out, out, args), ResultCode.SUCCESS, "Failed with arguments " + argList + ":  " + StaticUtils.toUTF8String(out.toByteArray()));
                    out.reset();
                    args = argList.toArray(StaticUtils.NO_STRINGS);
                    assertEquals(ManageAccount.main(out, out, args), ResultCode.SUCCESS, "Failed with arguments " + argList + ":  " + StaticUtils.toUTF8String(out.toByteArray()));
                    continue;
                }
                if (!a.isRequired()) {
                    out.reset();
                    String[] args = argList.toArray(StaticUtils.NO_STRINGS);
                    assertEquals(ManageAccount.main(null, null, args), ResultCode.SUCCESS, "Failed with arguments " + argList + ":  " + StaticUtils.toUTF8String(out.toByteArray()));
                    argList.add("--suppressEmptyResultOperations");
                    args = argList.toArray(StaticUtils.NO_STRINGS);
                    out.reset();
                    assertEquals(ManageAccount.main(null, null, args), ResultCode.SUCCESS, "Failed with arguments " + argList + ":  " + StaticUtils.toUTF8String(out.toByteArray()));
                    argList.remove(argList.size() - 1);
                }
                final String value1;
                final String value2;
                if (a instanceof BooleanValueArgument) {
                    value1 = "true";
                    value2 = "false";
                } else if (a instanceof StringArgument) {
                    if (sc.hasName("set-last-login-ip-address")) {
                        value1 = "1.2.3.4";
                        value2 = "5.6.7.8";
                    } else {
                        value1 = "value 1";
                        value2 = "value 2";
                    }
                } else if (a instanceof TimestampArgument) {
                    final long now = System.currentTimeMillis();
                    value1 = StaticUtils.encodeGeneralizedTime(now - 1L);
                    value2 = StaticUtils.encodeGeneralizedTime(now);
                } else {
                    throw new AssertionError("Unexpected argument type for argument " + a.getIdentifierString() + " in subcommand " + name + ":  " + a.getClass().getName());
                }
                argList.add("--ratePerSecond");
                argList.add("100");
                argList.add("--variableRateData");
                argList.add(variableRateDataFile);
                argList.add("--rejectFile");
                argList.add(rejectFile);
                argList.add("--targetDNFile");
                argList.add(dnFile);
                argList.add("--numThreads");
                argList.add("10");
                argList.add("--numSearchThreads");
                argList.add("10");
                argList.add(a.getIdentifierString());
                argList.add(value1);
                out.reset();
                String[] args = argList.toArray(StaticUtils.NO_STRINGS);
                assertEquals(ManageAccount.main(null, null, args), ResultCode.SUCCESS, "Failed with arguments " + argList + ":  " + StaticUtils.toUTF8String(out.toByteArray()));
                out.reset();
                argList.add("--suppressEmptyResultOperations");
                args = argList.toArray(StaticUtils.NO_STRINGS);
                assertEquals(ManageAccount.main(null, null, args), ResultCode.SUCCESS, "Failed with arguments " + argList + ":  " + StaticUtils.toUTF8String(out.toByteArray()));
                argList.remove(argList.size() - 1);
                if (a.getMaxOccurrences() > 1) {
                    argList.add(a.getIdentifierString());
                    argList.add(value2);
                    out.reset();
                    args = argList.toArray(StaticUtils.NO_STRINGS);
                    assertEquals(ManageAccount.main(null, null, args), ResultCode.SUCCESS, "Failed with arguments " + argList + ":  " + StaticUtils.toUTF8String(out.toByteArray()));
                    out.reset();
                    argList.add("--suppressEmptyResultOperations");
                    args = argList.toArray(StaticUtils.NO_STRINGS);
                    assertEquals(ManageAccount.main(null, null, args), ResultCode.SUCCESS, "Failed with arguments " + argList + ":  " + StaticUtils.toUTF8String(out.toByteArray()));
                    argList.remove(argList.size() - 1);
                }
            }
        }
    } finally {
        ds.shutDown(true);
    }
}
Also used : ASN1OctetString(com.unboundid.asn1.ASN1OctetString) PasswordPolicyStateAccountUsabilityError(com.unboundid.ldap.sdk.unboundidds.extensions.PasswordPolicyStateAccountUsabilityError) BooleanValueArgument(com.unboundid.util.args.BooleanValueArgument) Argument(com.unboundid.util.args.Argument) StringArgument(com.unboundid.util.args.StringArgument) TimestampArgument(com.unboundid.util.args.TimestampArgument) InMemoryDirectoryServerConfig(com.unboundid.ldap.listener.InMemoryDirectoryServerConfig) ArrayList(java.util.ArrayList) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) PasswordPolicyStateExtendedResult(com.unboundid.ldap.sdk.unboundidds.extensions.PasswordPolicyStateExtendedResult) ArgumentParser(com.unboundid.util.args.ArgumentParser) BooleanValueArgument(com.unboundid.util.args.BooleanValueArgument) TimestampArgument(com.unboundid.util.args.TimestampArgument) SubCommand(com.unboundid.util.args.SubCommand) InMemoryDirectoryServer(com.unboundid.ldap.listener.InMemoryDirectoryServer) PasswordPolicyStateOperation(com.unboundid.ldap.sdk.unboundidds.extensions.PasswordPolicyStateOperation) ByteArrayOutputStream(java.io.ByteArrayOutputStream) StringArgument(com.unboundid.util.args.StringArgument) PasswordPolicyStateAccountUsabilityNotice(com.unboundid.ldap.sdk.unboundidds.extensions.PasswordPolicyStateAccountUsabilityNotice) PasswordPolicyStateAccountUsabilityWarning(com.unboundid.ldap.sdk.unboundidds.extensions.PasswordPolicyStateAccountUsabilityWarning) Test(org.testng.annotations.Test)

Example 7 with Argument

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

the class CommandLineTool method getToolInvocationPropertiesFileArguments.

/**
 * Updates the provided argument list with object pairs that comprise the
 * set of tool arguments set from a properties file.
 *
 * @param  parser                          The argument parser for this tool.
 *                                         It must not be {@code null}.
 * @param  argumentsSetFromPropertiesFile  A set that should be updated with
 *                                         each argument 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 getToolInvocationPropertiesFileArguments(@NotNull final ArgumentParser parser, @NotNull final Set<Argument> argumentsSetFromPropertiesFile, @NotNull final List<ObjectPair<String, String>> argList) {
    final ArgumentParser subCommandParser;
    final SubCommand subCommand = parser.getSelectedSubCommand();
    if (subCommand == null) {
        subCommandParser = null;
    } else {
        subCommandParser = subCommand.getArgumentParser();
    }
    final String noValue = null;
    final Iterator<String> iterator = parser.getArgumentsSetFromPropertiesFile().iterator();
    while (iterator.hasNext()) {
        final String arg = iterator.next();
        if (arg.startsWith("-")) {
            Argument a;
            if (arg.startsWith("--")) {
                final String longIdentifier = arg.substring(2);
                a = parser.getNamedArgument(longIdentifier);
                if ((a == null) && (subCommandParser != null)) {
                    a = subCommandParser.getNamedArgument(longIdentifier);
                }
            } else {
                final char shortIdentifier = arg.charAt(1);
                a = parser.getNamedArgument(shortIdentifier);
                if ((a == null) && (subCommandParser != null)) {
                    a = subCommandParser.getNamedArgument(shortIdentifier);
                }
            }
            if (a != null) {
                argumentsSetFromPropertiesFile.add(a);
                if (a.takesValue()) {
                    final String value = iterator.next();
                    if (a.isSensitive()) {
                        argList.add(new ObjectPair<>(a.getIdentifierString(), noValue));
                    } else {
                        argList.add(new ObjectPair<>(a.getIdentifierString(), value));
                    }
                } else {
                    argList.add(new ObjectPair<>(a.getIdentifierString(), noValue));
                }
            }
        } else {
            argList.add(new ObjectPair<>(arg, 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) ArgumentParser(com.unboundid.util.args.ArgumentParser)

Example 8 with Argument

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

the class GenerateToolUsage method printHTMLArgs.

/**
 * Writes HTML-formatted information about the arguments for the provided
 * argument parser to the given writer.
 *
 * @param  w  The writer to which the argument information should be
 *            printed.
 * @param  p  The argument parser whose arguments should be displayed.
 */
private void printHTMLArgs(final PrintWriter w, final ArgumentParser p) {
    final LinkedHashMap<String, List<Argument>> argsByCategory = new LinkedHashMap<>(20);
    for (final Argument a : p.getNamedArguments()) {
        List<Argument> argList;
        if (a.getArgumentGroupName() == null) {
            argList = argsByCategory.get("");
            if (argList == null) {
                argList = new ArrayList<>(10);
                argsByCategory.put("", argList);
            }
        } else {
            argList = argsByCategory.get(a.getArgumentGroupName());
            if (argList == null) {
                argList = new ArrayList<>(10);
                argsByCategory.put(a.getArgumentGroupName(), argList);
            }
        }
        argList.add(a);
    }
    final List<Argument> ungroupedArgs = argsByCategory.remove("");
    if (ungroupedArgs != null) {
        if (argsByCategory.isEmpty()) {
            if (p.hasSubCommands()) {
                argsByCategory.put("Global Arguments", ungroupedArgs);
            } else {
                argsByCategory.put("Arguments", ungroupedArgs);
            }
        } else {
            argsByCategory.put("Additional Arguments", ungroupedArgs);
        }
    }
    final StringBuilder buffer = new StringBuilder();
    for (final Map.Entry<String, List<Argument>> e : argsByCategory.entrySet()) {
        w.println("    <h3>" + htmlEscape(e.getKey()) + "</h3>");
        w.println("    <ul>");
        for (final Argument a : e.getValue()) {
            w.println("      <li>");
            buffer.setLength(0);
            for (final Character c : a.getShortIdentifiers(false)) {
                if (buffer.length() > 0) {
                    buffer.append(" / ");
                }
                buffer.append("<tt>-");
                buffer.append(c);
                if (a.takesValue() && (a.getValuePlaceholder() != null)) {
                    buffer.append(" <i>");
                    buffer.append(htmlEscape(a.getValuePlaceholder()));
                    buffer.append("</i>");
                }
                buffer.append("</tt>");
            }
            for (final String s : a.getLongIdentifiers(false)) {
                if (buffer.length() > 0) {
                    buffer.append(" / ");
                }
                buffer.append("<tt>--");
                buffer.append(s);
                if (a.takesValue() && (a.getValuePlaceholder() != null)) {
                    buffer.append(" <i>");
                    buffer.append(htmlEscape(a.getValuePlaceholder()));
                    buffer.append("</i>");
                }
                buffer.append("</tt>");
            }
            buffer.append(" &mdash; ");
            buffer.append(htmlEscape(a.getDescription()));
            w.println("        " + buffer);
            if (a.getValueConstraints() != null) {
                w.println("        <br>");
                w.println("        " + htmlEscape(a.getValueConstraints()));
            }
            w.println("        <br><br>");
            w.println("      </li>");
        }
        w.println("    </ul>");
    }
    final List<Set<Argument>> requiredargumentSets = p.getRequiredArgumentSets();
    if (!requiredargumentSets.isEmpty()) {
        w.println("    <h3>Required Argument Sets</h3>");
        w.println("    <ul>");
        for (final Set<Argument> requiredArgumentSet : requiredargumentSets) {
            buffer.setLength(0);
            for (final Argument a : requiredArgumentSet) {
                if (buffer.length() > 0) {
                    buffer.append(", ");
                }
                buffer.append("<tt>");
                buffer.append(a.getIdentifierString());
                buffer.append("</tt>");
            }
            w.println("      <li>");
            w.println("        At least one of the following arguments must " + "be provided:  " + buffer);
            w.println("      </li>");
        }
        w.println("    </ul>");
    }
    final List<ObjectPair<Argument, Set<Argument>>> dependentArgumentSets = p.getDependentArgumentSets();
    if (!dependentArgumentSets.isEmpty()) {
        w.println("    <h3>Dependent Argument Sets</h3>");
        w.println("    <ul>");
        for (final ObjectPair<Argument, Set<Argument>> dependentArgumentSet : dependentArgumentSets) {
            w.println("      <li>");
            final Set<Argument> argSet = dependentArgumentSet.getSecond();
            if (argSet.size() == 1) {
                w.println("        If the <tt>" + dependentArgumentSet.getFirst().getIdentifierString() + "</tt> argument is provided, then the <tt>" + argSet.iterator().next().getIdentifierString() + "</tt> argument must also be provided.");
            } else {
                buffer.setLength(0);
                for (final Argument a : argSet) {
                    if (buffer.length() > 0) {
                        buffer.append(", ");
                    }
                    buffer.append("<tt>");
                    buffer.append(a.getIdentifierString());
                    buffer.append("</tt>");
                }
                w.println("        If the <tt>" + dependentArgumentSet.getFirst().getIdentifierString() + "</tt> argument is provided, then at least one of the " + "following arguments must also be provided:  " + buffer);
            }
            w.println("      </li>");
        }
        w.println("    </ul>");
    }
    final List<Set<Argument>> exclusiveArgumentSets = p.getExclusiveArgumentSets();
    if (!exclusiveArgumentSets.isEmpty()) {
        w.println("    <h3>Exclusive Argument Sets</h3>");
        w.println("    <ul>");
        for (final Set<Argument> exclusiveArgumentSet : exclusiveArgumentSets) {
            buffer.setLength(0);
            for (final Argument a : exclusiveArgumentSet) {
                if (buffer.length() > 0) {
                    buffer.append(", ");
                }
                buffer.append("<tt>");
                buffer.append(a.getIdentifierString());
                buffer.append("</tt>");
            }
            w.println("      <li>");
            w.println("        The following arguments cannot be used " + "together:  " + buffer);
            w.println("      </li>");
        }
        w.println("    </ul>");
    }
}
Also used : Set(java.util.Set) Argument(com.unboundid.util.args.Argument) ExampleCommandLineArgument(com.unboundid.util.ExampleCommandLineArgument) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) Map(java.util.Map) ObjectPair(com.unboundid.util.ObjectPair)

Example 9 with Argument

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

the class CollectSupportData method addNonLDAPArguments.

/**
 * {@inheritDoc}
 */
@Override()
public void addNonLDAPArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
    this.parser = parser;
    // Output-related arguments.
    outputPathArg = new FileArgument(null, "outputPath", false, 1, null, INFO_CSD_ARG_DESC_OUTPUT_PATH.get(), false, true, false, false);
    outputPathArg.addLongIdentifier("output-path", true);
    outputPathArg.addLongIdentifier("outputFile", true);
    outputPathArg.addLongIdentifier("output-file", true);
    outputPathArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_OUTPUT.get());
    parser.addArgument(outputPathArg);
    encryptArg = new BooleanArgument(null, "encrypt", 1, INFO_CSD_ARG_DESC_ENCRYPT.get());
    encryptArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_OUTPUT.get());
    parser.addArgument(encryptArg);
    passphraseFileArg = new FileArgument(null, "passphraseFile", false, 1, null, INFO_CSD_ARG_DESC_PASSPHRASE_FILE.get(), false, true, true, false);
    passphraseFileArg.addLongIdentifier("passphrase-file", true);
    passphraseFileArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_OUTPUT.get());
    parser.addArgument(passphraseFileArg);
    generatePassphraseArg = new BooleanArgument(null, "generatePassphrase", 1, INFO_CSD_ARG_DESC_GENERATE_PASSPHRASE.get());
    generatePassphraseArg.addLongIdentifier("generate-passphrase", true);
    generatePassphraseArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_OUTPUT.get());
    parser.addArgument(generatePassphraseArg);
    decryptArg = new FileArgument(null, "decrypt", false, 1, null, INFO_CSD_ARG_DESC_DECRYPT.get(), false, true, true, false);
    decryptArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_OUTPUT.get());
    parser.addArgument(decryptArg);
    // Collection-related arguments.
    collectExpensiveDataArg = new BooleanArgument(null, "collectExpensiveData", 1, INFO_CSD_ARG_DESC_COLLECT_EXPENSIVE_DATA.get());
    collectExpensiveDataArg.addLongIdentifier("collect-expensive-data", true);
    collectExpensiveDataArg.addLongIdentifier("includeExpensiveData", true);
    collectExpensiveDataArg.addLongIdentifier("include-expensive-data", true);
    collectExpensiveDataArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(collectExpensiveDataArg);
    collectReplicationStateDumpArg = new BooleanArgument(null, "collectReplicationStateDump", 1, INFO_CSD_ARG_DESC_COLLECT_REPL_STATE.get());
    collectReplicationStateDumpArg.addLongIdentifier("collect-replication-state-dump", true);
    collectReplicationStateDumpArg.addLongIdentifier("collectReplicationState", true);
    collectReplicationStateDumpArg.addLongIdentifier("collect-replication-state", true);
    collectReplicationStateDumpArg.addLongIdentifier("includeReplicationStateDump", true);
    collectReplicationStateDumpArg.addLongIdentifier("include-replication-state-dump", true);
    collectReplicationStateDumpArg.addLongIdentifier("includeReplicationState", true);
    collectReplicationStateDumpArg.addLongIdentifier("include-replication-state", true);
    collectReplicationStateDumpArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(collectReplicationStateDumpArg);
    includeBinaryFilesArg = new BooleanArgument(null, "includeBinaryFiles", 1, INFO_CSD_ARG_DESC_INCLUDE_BINARY_FILES.get());
    includeBinaryFilesArg.addLongIdentifier("include-binary-files", true);
    includeBinaryFilesArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(includeBinaryFilesArg);
    archiveExtensionSourceArg = new BooleanArgument(null, "archiveExtensionSource", 1, INFO_CSD_ARG_DESC_ARCHIVE_EXTENSION_SOURCE.get());
    archiveExtensionSourceArg.addLongIdentifier("archive-extension-source", true);
    archiveExtensionSourceArg.addLongIdentifier("includeExtensionSource", true);
    archiveExtensionSourceArg.addLongIdentifier("include-extension-source", true);
    archiveExtensionSourceArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(archiveExtensionSourceArg);
    sequentialArg = new BooleanArgument(null, "sequential", 1, INFO_CSD_ARG_DESC_SEQUENTIAL.get());
    sequentialArg.addLongIdentifier("sequentialMode", true);
    sequentialArg.addLongIdentifier("sequential-mode", true);
    sequentialArg.addLongIdentifier("useSequentialMode", true);
    sequentialArg.addLongIdentifier("use-sequential-mode", true);
    sequentialArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(sequentialArg);
    securityLevelArg = new StringArgument(null, "securityLevel", false, 1, INFO_CSD_ARG_PLACEHOLDER_SECURITY_LEVEL.get(), INFO_CSD_ARG_DESC_SECURITY_LEVEL.get(), StaticUtils.setOf(CollectSupportDataSecurityLevel.NONE.getName(), CollectSupportDataSecurityLevel.OBSCURE_SECRETS.getName(), CollectSupportDataSecurityLevel.MAXIMUM.getName()));
    securityLevelArg.addLongIdentifier("security-level", true);
    securityLevelArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(securityLevelArg);
    jstackCountArg = new IntegerArgument(null, "jstackCount", false, 1, INFO_CSD_ARG_PLACEHOLDER_COUNT.get(), INFO_CSD_ARG_DESC_JSTACK_COUNT.get(), 0, Integer.MAX_VALUE);
    jstackCountArg.addLongIdentifier("jstack-count", true);
    jstackCountArg.addLongIdentifier("maxJstacks", true);
    jstackCountArg.addLongIdentifier("max-jstacks", true);
    jstackCountArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(jstackCountArg);
    reportCountArg = new IntegerArgument(null, "reportCount", false, 1, INFO_CSD_ARG_PLACEHOLDER_COUNT.get(), INFO_CSD_ARG_DESC_REPORT_COUNT.get(), 0, Integer.MAX_VALUE);
    reportCountArg.addLongIdentifier("report-count", true);
    reportCountArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(reportCountArg);
    reportIntervalSecondsArg = new IntegerArgument(null, "reportIntervalSeconds", false, 1, INFO_CSD_ARG_PLACEHOLDER_SECONDS.get(), INFO_CSD_ARG_DESC_REPORT_INTERVAL_SECONDS.get(), 1, Integer.MAX_VALUE);
    reportIntervalSecondsArg.addLongIdentifier("report-interval-seconds", true);
    reportIntervalSecondsArg.addLongIdentifier("reportInterval", true);
    reportIntervalSecondsArg.addLongIdentifier("report-interval", true);
    reportIntervalSecondsArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(reportIntervalSecondsArg);
    logTimeRangeArg = new StringArgument(null, "logTimeRange", false, 1, INFO_CSD_ARG_PLACEHOLDER_TIME_RANGE.get(), INFO_CSD_ARG_DESC_TIME_RANGE.get());
    logTimeRangeArg.addLongIdentifier("log-time-range", true);
    logTimeRangeArg.addLongIdentifier("timeRange", true);
    logTimeRangeArg.addLongIdentifier("time-range", true);
    logTimeRangeArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(logTimeRangeArg);
    logDurationArg = new DurationArgument(null, "logDuration", false, null, INFO_CSD_ARG_DESC_DURATION.get());
    logDurationArg.addLongIdentifier("log-duration", true);
    logDurationArg.addLongIdentifier("duration", true);
    logDurationArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(logDurationArg);
    logFileHeadCollectionSizeKBArg = new IntegerArgument(null, "logFileHeadCollectionSizeKB", false, 1, INFO_CSD_ARG_PLACEHOLDER_SIZE_KB.get(), INFO_CSD_ARG_DESC_LOG_HEAD_SIZE_KB.get(), 0, Integer.MAX_VALUE);
    logFileHeadCollectionSizeKBArg.addLongIdentifier("log-file-head-collection-size-kb", true);
    logFileHeadCollectionSizeKBArg.addLongIdentifier("logFileHeadSizeKB", true);
    logFileHeadCollectionSizeKBArg.addLongIdentifier("log-file-head-size-kb", true);
    logFileHeadCollectionSizeKBArg.addLongIdentifier("logHeadCollectionSizeKB", true);
    logFileHeadCollectionSizeKBArg.addLongIdentifier("log-head-collection-size-kb", true);
    logFileHeadCollectionSizeKBArg.addLongIdentifier("logHeadSizeKB", true);
    logFileHeadCollectionSizeKBArg.addLongIdentifier("log-head-size-kb", true);
    logFileHeadCollectionSizeKBArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(logFileHeadCollectionSizeKBArg);
    logFileTailCollectionSizeKBArg = new IntegerArgument(null, "logFileTailCollectionSizeKB", false, 1, INFO_CSD_ARG_PLACEHOLDER_SIZE_KB.get(), INFO_CSD_ARG_DESC_LOG_TAIL_SIZE_KB.get(), 0, Integer.MAX_VALUE);
    logFileTailCollectionSizeKBArg.addLongIdentifier("log-file-tail-collection-size-kb", true);
    logFileTailCollectionSizeKBArg.addLongIdentifier("logFileTailSizeKB", true);
    logFileTailCollectionSizeKBArg.addLongIdentifier("log-file-tail-size-kb", true);
    logFileTailCollectionSizeKBArg.addLongIdentifier("logTailCollectionSizeKB", true);
    logFileTailCollectionSizeKBArg.addLongIdentifier("log-tail-collection-size-kb", true);
    logFileTailCollectionSizeKBArg.addLongIdentifier("logTailSizeKB", true);
    logFileTailCollectionSizeKBArg.addLongIdentifier("log-tail-size-kb", true);
    logFileTailCollectionSizeKBArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(logFileTailCollectionSizeKBArg);
    pidArg = new IntegerArgument(null, "pid", false, 0, INFO_CSD_ARG_PLACEHOLDER_PID.get(), INFO_CSD_ARG_DESC_PID.get());
    pidArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(pidArg);
    commentArg = new StringArgument(null, "comment", false, 1, null, INFO_CSD_ARG_DESC_COMMENT.get());
    commentArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COLLECTION.get());
    parser.addArgument(commentArg);
    // Communication-related arguments.
    useRemoteServerArg = new BooleanArgument(null, "useRemoteServer", 1, INFO_CSD_ARG_DEC_USE_REMOTE_SERVER.get());
    useRemoteServerArg.addLongIdentifier("use-remote-server", true);
    useRemoteServerArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COMMUNICATION.get());
    parser.addArgument(useRemoteServerArg);
    useAdministrativeSessionArg = new BooleanArgument(null, "useAdministrativeSession", 1, INFO_CSD_ARG_DESC_USE_ADMIN_SESSION.get());
    useAdministrativeSessionArg.addLongIdentifier("use-administrative-session", true);
    useAdministrativeSessionArg.addLongIdentifier("useAdminSession", true);
    useAdministrativeSessionArg.addLongIdentifier("use-admin-session", true);
    useAdministrativeSessionArg.addLongIdentifier("administrativeSession", true);
    useAdministrativeSessionArg.addLongIdentifier("administrative-session", true);
    useAdministrativeSessionArg.addLongIdentifier("adminSession", true);
    useAdministrativeSessionArg.addLongIdentifier("admin-session", true);
    useAdministrativeSessionArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COMMUNICATION.get());
    parser.addArgument(useAdministrativeSessionArg);
    proxyToServerAddressArg = new StringArgument(null, "proxyToServerAddress", false, 1, INFO_CSD_ARG_PLACEHOLDER_ADDRESS.get(), INFO_CSD_ARG_DESC_PROXY_TO_ADDRESS.get());
    proxyToServerAddressArg.addLongIdentifier("proxy-to-server-address", true);
    proxyToServerAddressArg.addLongIdentifier("proxyToAddress", true);
    proxyToServerAddressArg.addLongIdentifier("proxy-to-address", true);
    proxyToServerAddressArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COMMUNICATION.get());
    parser.addArgument(proxyToServerAddressArg);
    proxyToServerPortArg = new IntegerArgument(null, "proxyToServerPort", false, 1, INFO_CSD_ARG_PLACEHOLDER_PORT.get(), INFO_CSD_ARG_DESC_PROXY_TO_PORT.get(), 1, 65535);
    proxyToServerPortArg.addLongIdentifier("proxy-to-server-port", true);
    proxyToServerPortArg.addLongIdentifier("proxyToPort", true);
    proxyToServerPortArg.addLongIdentifier("proxy-to-port", true);
    proxyToServerPortArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COMMUNICATION.get());
    parser.addArgument(proxyToServerPortArg);
    noLDAPArg = new BooleanArgument(null, "noLDAP", 1, INFO_CSD_ARG_DESC_NO_LDAP.get());
    noLDAPArg.addLongIdentifier("no-ldap", true);
    noLDAPArg.setArgumentGroupName(INFO_CSD_ARG_GROUP_COMMUNICATION.get());
    parser.addArgument(noLDAPArg);
    // Other arguments.
    noPromptArg = new BooleanArgument('n', "noPrompt", 1, INFO_CSD_ARG_DESC_NO_PROMPT.get());
    noPromptArg.addLongIdentifier("no-prompt", true);
    parser.addArgument(noPromptArg);
    dryRunArg = new BooleanArgument(null, "dryRun", 1, INFO_CSD_ARG_DESC_DRY_RUN.get());
    dryRunArg.addLongIdentifier("dry-run", true);
    dryRunArg.addLongIdentifier("noOperation", true);
    dryRunArg.addLongIdentifier("no-operation", true);
    dryRunArg.addLongIdentifier("noOp", true);
    dryRunArg.addLongIdentifier("no-op", true);
    parser.addArgument(dryRunArg);
    scriptFriendlyArg = new BooleanArgument(null, "scriptFriendly", 1, INFO_CSD_ARG_DESC_SCRIPT_FRIENDLY.get());
    scriptFriendlyArg.addLongIdentifier("script-friendly", true);
    scriptFriendlyArg.setHidden(true);
    parser.addArgument(scriptFriendlyArg);
    // If the --useRemoteServer argument is provided, then none of the --pid,
    // --decrypt, --noLDAP, or --scriptFriendly arguments may be given.
    parser.addExclusiveArgumentSet(useRemoteServerArg, pidArg);
    parser.addExclusiveArgumentSet(useRemoteServerArg, decryptArg);
    parser.addExclusiveArgumentSet(useRemoteServerArg, noLDAPArg);
    parser.addExclusiveArgumentSet(useRemoteServerArg, scriptFriendlyArg);
    // The --useAdministrativeSession argument can only be provided if the
    // --useRemoteServer argument is also given.
    parser.addDependentArgumentSet(useAdministrativeSessionArg, useRemoteServerArg);
    // If the --proxyToServerAddress or --proxyToServerPort argument is given,
    // then the other must be provided as well.
    parser.addMutuallyDependentArgumentSet(proxyToServerAddressArg, proxyToServerPortArg);
    // The --proxyToServerAddress and --proxyToServerPort arguments can only
    // be used if the --useRemoteServer argument is given.
    parser.addDependentArgumentSet(proxyToServerAddressArg, useRemoteServerArg);
    parser.addDependentArgumentSet(proxyToServerPortArg, useRemoteServerArg);
    // The --logTimeRange and --logDuration arguments cannot be used together.
    parser.addExclusiveArgumentSet(logTimeRangeArg, logDurationArg);
    // Neither the --logFileHeadCollectionSizeKB argument nor the
    // --logFileTailCollectionSizeKB argument can be used in conjunction with
    // either the --logTimeRange or --logDuration argument.
    parser.addExclusiveArgumentSet(logFileHeadCollectionSizeKBArg, logTimeRangeArg, logDurationArg);
    parser.addExclusiveArgumentSet(logFileTailCollectionSizeKBArg, logTimeRangeArg, logDurationArg);
    // The --generatePassphrase argument can only be used if both the
    // --encrypt and --passphraseFile arguments are provided.
    parser.addDependentArgumentSet(generatePassphraseArg, encryptArg);
    parser.addDependentArgumentSet(generatePassphraseArg, passphraseFileArg);
    // The --encrypt and --decrypt arguments cannot be used together.
    parser.addExclusiveArgumentSet(encryptArg, decryptArg);
    // --useRemoteServer argument.
    for (final String argumentIdentifier : Arrays.asList("promptForBindPassword", "promptForKeyStorePassword", "promptForTrustStorePassword", "enableSSLDebugging", "useSASLExternal")) {
        final Argument arg = parser.getNamedArgument(argumentIdentifier);
        parser.addDependentArgumentSet(arg, useRemoteServerArg);
    }
}
Also used : DurationArgument(com.unboundid.util.args.DurationArgument) IntegerArgument(com.unboundid.util.args.IntegerArgument) DurationArgument(com.unboundid.util.args.DurationArgument) Argument(com.unboundid.util.args.Argument) BooleanArgument(com.unboundid.util.args.BooleanArgument) TimestampArgument(com.unboundid.util.args.TimestampArgument) FileArgument(com.unboundid.util.args.FileArgument) StringArgument(com.unboundid.util.args.StringArgument) BooleanArgument(com.unboundid.util.args.BooleanArgument) IntegerArgument(com.unboundid.util.args.IntegerArgument) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) FileArgument(com.unboundid.util.args.FileArgument) StringArgument(com.unboundid.util.args.StringArgument)

Example 10 with Argument

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

the class CollectSupportData method doLocalProcessing.

/**
 * Performs the collect-support-data tool using reflection to invoke the
 * server-side version of the tool.
 *
 * @return  A result code that indicates the result of the processing.
 */
@NotNull()
private ResultCode doLocalProcessing() {
    // Construct the argument list to use when invoking the server-side code.
    // Although this tool supports all of the arguments that the server-side
    // tool provides, the server-side tool does not support all of the arguments
    // that this version offers, nor does it support all of the variants (e.g.,
    // alternate names) for the arguments that do overlap.
    final List<String> argList = new ArrayList<>(20);
    if (outputPathArg.isPresent()) {
        argList.add("--outputPath");
        argList.add(outputPathArg.getValue().getAbsolutePath());
    }
    if (noLDAPArg.isPresent()) {
        argList.add("--noLdap");
    }
    if (pidArg.isPresent()) {
        for (final Integer pid : pidArg.getValues()) {
            argList.add("--pid");
            argList.add(pid.toString());
        }
    }
    if (sequentialArg.isPresent()) {
        argList.add("--sequential");
    }
    if (reportCountArg.isPresent()) {
        argList.add("--reportCount");
        argList.add(reportCountArg.getValue().toString());
    }
    if (reportIntervalSecondsArg.isPresent()) {
        argList.add("--reportInterval");
        argList.add(reportIntervalSecondsArg.getValue().toString());
    }
    if (jstackCountArg.isPresent()) {
        argList.add("--maxJstacks");
        argList.add(jstackCountArg.getValue().toString());
    }
    if (collectExpensiveDataArg.isPresent()) {
        argList.add("--collectExpensiveData");
    }
    if (collectReplicationStateDumpArg.isPresent()) {
        argList.add("--collectReplicationStateDump");
    }
    if (commentArg.isPresent()) {
        argList.add("--comment");
        argList.add(commentArg.getValue());
    }
    if (includeBinaryFilesArg.isPresent()) {
        argList.add("--includeBinaryFiles");
    }
    if (securityLevelArg.isPresent()) {
        argList.add("--securityLevel");
        argList.add(securityLevelArg.getValue());
    }
    if (encryptArg.isPresent()) {
        argList.add("--encrypt");
    }
    if (passphraseFileArg.isPresent()) {
        argList.add("--passphraseFile");
        argList.add(passphraseFileArg.getValue().getAbsolutePath());
    }
    if (generatePassphraseArg.isPresent()) {
        argList.add("--generatePassphrase");
    }
    if (decryptArg.isPresent()) {
        argList.add("--decrypt");
        argList.add(decryptArg.getValue().getAbsolutePath());
    }
    if (logTimeRangeArg.isPresent()) {
        final ObjectPair<Date, Date> timeRange;
        try {
            timeRange = parseTimeRange(logTimeRangeArg.getValue(), false);
        } catch (final LDAPException e) {
            // This should never happen because we should have pre-validated the
            // value.  But handle it just in case.
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, e.getMessage());
            return e.getResultCode();
        }
        if (timeRange == null) {
            // We'll assume that this means the time range was specified using
            // rotated log filenames, which we can't handle in the LDAP SDK code so
            // we'll just pass the argument value through to the server code.
            argList.add("--timeRange");
            argList.add(logTimeRangeArg.getValue());
        } else {
            final Date startTime = timeRange.getFirst();
            Date endTime = timeRange.getSecond();
            if (endTime == null) {
                endTime = new Date(Math.max(System.currentTimeMillis(), startTime.getTime()));
            }
            final SimpleDateFormat timestampFormatter = new SimpleDateFormat(SERVER_LOG_TIMESTAMP_FORMAT_WITH_MILLIS);
            argList.add("--timeRange");
            argList.add(timestampFormatter.format(startTime) + ',' + timestampFormatter.format(endTime));
        }
    }
    if (logDurationArg.isPresent()) {
        argList.add("--duration");
        argList.add(DurationArgument.nanosToDuration(logDurationArg.getValue(TimeUnit.NANOSECONDS)));
    }
    if (logFileHeadCollectionSizeKBArg.isPresent()) {
        argList.add("--logFileHeadCollectionSizeKB");
        argList.add(String.valueOf(logFileHeadCollectionSizeKBArg.getValue()));
    }
    if (logFileTailCollectionSizeKBArg.isPresent()) {
        argList.add("--logFileTailCollectionSizeKB");
        argList.add(String.valueOf(logFileTailCollectionSizeKBArg.getValue()));
    }
    if (archiveExtensionSourceArg.isPresent()) {
        argList.add("--archiveExtensionSource");
    }
    if (noPromptArg.isPresent()) {
        argList.add("--no-prompt");
    }
    if (scriptFriendlyArg.isPresent()) {
        argList.add("--script-friendly");
    }
    // command-line tool framework.
    for (final String argumentIdentifier : Arrays.asList("hostname", "port", "bindDN", "bindPassword", "bindPasswordFile", "useSSL", "useStartTLS", "trustAll", "keyStorePath", "keyStorePassword", "keyStorePasswordFile", "keyStoreFormat", "trustStorePath", "trustStorePassword", "trustStorePasswordFile", "trustStoreFormat", "certNickname", "saslOption", "propertiesFilePath", "noPropertiesFile")) {
        final Argument arg = parser.getNamedArgument(argumentIdentifier);
        if (arg.getNumOccurrences() > 0) {
            for (final String value : arg.getValueStringRepresentations(false)) {
                argList.add("--" + argumentIdentifier);
                if (arg.takesValue()) {
                    argList.add(value);
                }
            }
        }
    }
    // invoking the tool.
    if (dryRunArg.isPresent()) {
        final String message = INFO_CSD_LOCAL_MODE_DRY_RUN.get();
        wrapOut(0, WRAP_COLUMN, message);
        toolCompletionMessage.set(message);
        return ResultCode.NO_OPERATION;
    }
    // Make sure that we have access to the method in the server codebase that
    // we need to invoke local collect-support-data processing.
    final Method doMainMethod;
    try {
        final Class<?> csdToolClass = Class.forName(SERVER_CSD_TOOL_CLASS);
        doMainMethod = csdToolClass.getMethod("doMain", Boolean.TYPE, OutputStream.class, OutputStream.class, String[].class);
    } catch (final Throwable t) {
        Debug.debugException(t);
        final String message = ERR_CSD_SERVER_CODE_NOT_AVAILABLE.get();
        wrapErr(0, WRAP_COLUMN, message);
        toolCompletionMessage.set(message);
        return ResultCode.NOT_SUPPORTED;
    }
    // Invoke the doMain method via reflection
    final String[] argArray = new String[argList.size()];
    argList.toArray(argArray);
    try {
        final Object doMainMethodReturnValue = doMainMethod.invoke(null, true, getOut(), getErr(), argArray);
        final int exitCode = ((Integer) doMainMethodReturnValue).intValue();
        return ResultCode.valueOf(exitCode);
    } catch (final Throwable t) {
        Debug.debugException(t);
        final String message = ERR_CSD_INVOKE_ERROR.get(StaticUtils.getExceptionMessage(t));
        wrapErr(0, WRAP_COLUMN, message);
        toolCompletionMessage.set(message);
        return ResultCode.LOCAL_ERROR;
    }
}
Also used : IntegerArgument(com.unboundid.util.args.IntegerArgument) DurationArgument(com.unboundid.util.args.DurationArgument) Argument(com.unboundid.util.args.Argument) BooleanArgument(com.unboundid.util.args.BooleanArgument) TimestampArgument(com.unboundid.util.args.TimestampArgument) FileArgument(com.unboundid.util.args.FileArgument) StringArgument(com.unboundid.util.args.StringArgument) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) ASN1OctetString(com.unboundid.asn1.ASN1OctetString) Method(java.lang.reflect.Method) Date(java.util.Date) LDAPException(com.unboundid.ldap.sdk.LDAPException) SimpleDateFormat(java.text.SimpleDateFormat) NotNull(com.unboundid.util.NotNull)

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