Search in sources :

Example 36 with BooleanArgument

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

the class LDIFDiff method addToolArguments.

/**
 * {@inheritDoc}
 */
@Override()
public void addToolArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
    sourceLDIF = new FileArgument('s', "sourceLDIF", true, 1, null, INFO_LDIF_DIFF_ARG_DESC_SOURCE_LDIF.get(), true, true, true, false);
    sourceLDIF.addLongIdentifier("source-ldif", true);
    sourceLDIF.addLongIdentifier("source", true);
    sourceLDIF.addLongIdentifier("sourceFile", true);
    sourceLDIF.addLongIdentifier("source-file", true);
    sourceLDIF.addLongIdentifier("sourceLDIFFile", true);
    sourceLDIF.addLongIdentifier("source-ldif-file", true);
    sourceLDIF.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_SOURCE.get());
    parser.addArgument(sourceLDIF);
    final String sourcePWDesc;
    if (PING_SERVER_AVAILABLE) {
        sourcePWDesc = INFO_LDIF_DIFF_ARG_DESC_SOURCE_PW_FILE_PING_SERVER.get();
    } else {
        sourcePWDesc = INFO_LDIF_DIFF_ARG_DESC_SOURCE_PW_FILE_STANDALONE.get();
    }
    sourceEncryptionPassphraseFile = new FileArgument(null, "sourceEncryptionPassphraseFile", false, 1, null, sourcePWDesc, true, true, true, false);
    sourceEncryptionPassphraseFile.addLongIdentifier("source-encryption-passphrase-file", true);
    sourceEncryptionPassphraseFile.addLongIdentifier("sourcePassphraseFile", true);
    sourceEncryptionPassphraseFile.addLongIdentifier("source-passphrase-file", true);
    sourceEncryptionPassphraseFile.addLongIdentifier("sourceEncryptionPasswordFile", true);
    sourceEncryptionPassphraseFile.addLongIdentifier("source-encryption-password-file", true);
    sourceEncryptionPassphraseFile.addLongIdentifier("sourcePasswordFile", true);
    sourceEncryptionPassphraseFile.addLongIdentifier("source-password-file", true);
    sourceEncryptionPassphraseFile.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_SOURCE.get());
    parser.addArgument(sourceEncryptionPassphraseFile);
    targetLDIF = new FileArgument('t', "targetLDIF", true, 1, null, INFO_LDIF_DIFF_ARG_DESC_TARGET_LDIF.get(), true, true, true, false);
    targetLDIF.addLongIdentifier("target-ldif", true);
    targetLDIF.addLongIdentifier("target", true);
    targetLDIF.addLongIdentifier("targetFile", true);
    targetLDIF.addLongIdentifier("target-file", true);
    targetLDIF.addLongIdentifier("targetLDIFFile", true);
    targetLDIF.addLongIdentifier("target-ldif-file", true);
    targetLDIF.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_TARGET.get());
    parser.addArgument(targetLDIF);
    final String targetPWDesc;
    if (PING_SERVER_AVAILABLE) {
        targetPWDesc = INFO_LDIF_DIFF_ARG_DESC_TARGET_PW_FILE_PING_SERVER.get();
    } else {
        targetPWDesc = INFO_LDIF_DIFF_ARG_DESC_TARGET_PW_FILE_STANDALONE.get();
    }
    targetEncryptionPassphraseFile = new FileArgument(null, "targetEncryptionPassphraseFile", false, 1, null, targetPWDesc, true, true, true, false);
    targetEncryptionPassphraseFile.addLongIdentifier("target-encryption-passphrase-file", true);
    targetEncryptionPassphraseFile.addLongIdentifier("targetPassphraseFile", true);
    targetEncryptionPassphraseFile.addLongIdentifier("target-passphrase-file", true);
    targetEncryptionPassphraseFile.addLongIdentifier("targetEncryptionPasswordFile", true);
    targetEncryptionPassphraseFile.addLongIdentifier("target-encryption-password-file", true);
    targetEncryptionPassphraseFile.addLongIdentifier("targetPasswordFile", true);
    targetEncryptionPassphraseFile.addLongIdentifier("target-password-file", true);
    targetEncryptionPassphraseFile.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_TARGET.get());
    parser.addArgument(targetEncryptionPassphraseFile);
    outputLDIF = new FileArgument('o', "outputLDIF", false, 1, null, INFO_LDIF_DIFF_ARG_DESC_OUTPUT_LDIF.get(), false, true, true, false);
    outputLDIF.addLongIdentifier("output-ldif", true);
    outputLDIF.addLongIdentifier("output", true);
    outputLDIF.addLongIdentifier("outputFile", true);
    outputLDIF.addLongIdentifier("output-file", true);
    outputLDIF.addLongIdentifier("outputLDIFFile", true);
    outputLDIF.addLongIdentifier("output-ldif-file", true);
    outputLDIF.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_OUTPUT.get());
    parser.addArgument(outputLDIF);
    compressOutput = new BooleanArgument(null, "compressOutput", 1, INFO_LDIF_DIFF_ARG_DESC_COMPRESS_OUTPUT.get());
    compressOutput.addLongIdentifier("compress-output", true);
    compressOutput.addLongIdentifier("compress", true);
    compressOutput.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_OUTPUT.get());
    parser.addArgument(compressOutput);
    encryptOutput = new BooleanArgument(null, "encryptOutput", 1, INFO_LDIF_DIFF_ARG_DESC_ENCRYPT_OUTPUT.get());
    encryptOutput.addLongIdentifier("encrypt-output", true);
    encryptOutput.addLongIdentifier("encrypt", true);
    encryptOutput.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_OUTPUT.get());
    parser.addArgument(encryptOutput);
    outputEncryptionPassphraseFile = new FileArgument(null, "outputEncryptionPassphraseFile", false, 1, null, INFO_LDIF_DIFF_ARG_DESC_OUTPUT_PW_FILE.get(), true, true, true, false);
    outputEncryptionPassphraseFile.addLongIdentifier("output-encryption-passphrase-file", true);
    outputEncryptionPassphraseFile.addLongIdentifier("outputPassphraseFile", true);
    outputEncryptionPassphraseFile.addLongIdentifier("output-passphrase-file", true);
    outputEncryptionPassphraseFile.addLongIdentifier("outputEncryptionPasswordFile", true);
    outputEncryptionPassphraseFile.addLongIdentifier("output-encryption-password-file", true);
    outputEncryptionPassphraseFile.addLongIdentifier("outputPasswordFile", true);
    outputEncryptionPassphraseFile.addLongIdentifier("output-password-file", true);
    outputEncryptionPassphraseFile.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_OUTPUT.get());
    parser.addArgument(outputEncryptionPassphraseFile);
    overwriteExistingOutputLDIF = new BooleanArgument('O', "overwriteExistingOutputLDIF", 1, INFO_LDIF_DIFF_ARG_DESC_OVERWRITE_EXISTING.get());
    overwriteExistingOutputLDIF.addLongIdentifier("overwrite-existing-output-ldif", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwriteExistingOutputFile", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwrite-existing-output-file", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwriteExistingOutput", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwrite-existing-output", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwriteExisting", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwrite-existing", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwriteOutputLDIF", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwrite-output-ldif", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwriteOutputFile", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwrite-output-file", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwriteOutput", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwrite-output", true);
    overwriteExistingOutputLDIF.addLongIdentifier("overwrite", true);
    overwriteExistingOutputLDIF.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_OUTPUT.get());
    parser.addArgument(overwriteExistingOutputLDIF);
    changeType = new StringArgument(null, "changeType", false, 0, INFO_LDIF_DIFF_ARG_PLACEHOLDER_CHANGE_TYPE.get(), INFO_LDIF_DIFF_ARG_DESC_CHANGE_TYPE.get(), StaticUtils.setOf(CHANGE_TYPE_ADD, CHANGE_TYPE_DELETE, CHANGE_TYPE_MODIFY), Collections.unmodifiableList(Arrays.asList(CHANGE_TYPE_ADD, CHANGE_TYPE_DELETE, CHANGE_TYPE_MODIFY)));
    changeType.addLongIdentifier("change-type", true);
    changeType.addLongIdentifier("operationType", true);
    changeType.addLongIdentifier("operation-type", true);
    changeType.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(changeType);
    includeFilter = new FilterArgument(null, "includeFilter", false, 0, null, INFO_LDIF_DIFF_ARG_DESC_INCLUDE_FILTER.get());
    includeFilter.addLongIdentifier("include-filter", true);
    includeFilter.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(includeFilter);
    excludeFilter = new FilterArgument(null, "excludeFilter", false, 0, null, INFO_LDIF_DIFF_ARG_DESC_EXCLUDE_FILTER.get());
    excludeFilter.addLongIdentifier("exclude-filter", true);
    excludeFilter.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(excludeFilter);
    includeAttribute = new StringArgument(null, "includeAttribute", false, 0, INFO_LDIF_DIFF_ARG_PLACEHOLDER_ATTRIBUTE.get(), INFO_LDIF_DIFF_ARG_DESC_INCLUDE_ATTRIBUTE.get());
    includeAttribute.addLongIdentifier("include-attribute", true);
    includeAttribute.addLongIdentifier("includeAttr", true);
    includeAttribute.addLongIdentifier("include-attr", true);
    includeAttribute.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(includeAttribute);
    excludeAttribute = new StringArgument(null, "excludeAttribute", false, 0, INFO_LDIF_DIFF_ARG_PLACEHOLDER_ATTRIBUTE.get(), INFO_LDIF_DIFF_ARG_DESC_EXCLUDE_ATTRIBUTE.get());
    excludeAttribute.addLongIdentifier("exclude-attribute", true);
    excludeAttribute.addLongIdentifier("excludeAttr", true);
    excludeAttribute.addLongIdentifier("exclude-attr", true);
    excludeAttribute.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(excludeAttribute);
    includeOperationalAttributes = new BooleanArgument('i', "includeOperationalAttributes", 1, INFO_LDIF_DIFF_ARG_DESC_INCLUDE_OPERATIONAL.get());
    includeOperationalAttributes.addLongIdentifier("include-operational-attributes", true);
    includeOperationalAttributes.addLongIdentifier("includeOperational", true);
    includeOperationalAttributes.addLongIdentifier("include-operational", true);
    includeOperationalAttributes.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(includeOperationalAttributes);
    excludeNoUserModificationAttributes = new BooleanArgument('e', "excludeNoUserModificationAttributes", 1, INFO_LDIF_DIFF_ARG_DESC_EXCLUDE_NO_USER_MOD.get());
    excludeNoUserModificationAttributes.addLongIdentifier("exclude-no-user-modification-attributes", true);
    excludeNoUserModificationAttributes.addLongIdentifier("excludeNoUserModAttributes", true);
    excludeNoUserModificationAttributes.addLongIdentifier("exclude-no-user-mod-attributes", true);
    excludeNoUserModificationAttributes.addLongIdentifier("excludeNoUserModification", true);
    excludeNoUserModificationAttributes.addLongIdentifier("exclude-no-user-modification", true);
    excludeNoUserModificationAttributes.addLongIdentifier("excludeNoUserMod", true);
    excludeNoUserModificationAttributes.addLongIdentifier("exclude-no-user-mod", true);
    excludeNoUserModificationAttributes.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(excludeNoUserModificationAttributes);
    nonReversibleModifications = new BooleanArgument(null, "nonReversibleModifications", 1, INFO_LDIF_DIFF_ARG_DESC_NON_REVERSIBLE_MODS.get());
    nonReversibleModifications.addLongIdentifier("non-reversible-modifications", true);
    nonReversibleModifications.addLongIdentifier("nonReversibleMods", true);
    nonReversibleModifications.addLongIdentifier("non-reversible-mods", true);
    nonReversibleModifications.addLongIdentifier("nonReversible", true);
    nonReversibleModifications.addLongIdentifier("non-reversible", true);
    nonReversibleModifications.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(nonReversibleModifications);
    singleValueChanges = new BooleanArgument('S', "singleValueChanges", 1, INFO_LDIF_DIFF_ARG_DESC_SINGLE_VALUE_CHANGES.get());
    singleValueChanges.addLongIdentifier("single-value-changes", true);
    parser.addArgument(singleValueChanges);
    stripTrailingSpaces = new BooleanArgument(null, "stripTrailingSpaces", 1, INFO_LDIF_DIFF_ARG_DESC_STRIP_TRAILING_SPACES.get());
    stripTrailingSpaces.addLongIdentifier("strip-trailing-spaces", true);
    stripTrailingSpaces.addLongIdentifier("ignoreTrailingSpaces", true);
    stripTrailingSpaces.addLongIdentifier("ignore-trailing-spaces", true);
    stripTrailingSpaces.setArgumentGroupName(INFO_LDIF_DIFF_ARG_GROUP_CONTENT.get());
    parser.addArgument(stripTrailingSpaces);
    final String schemaPathDesc;
    if (PING_SERVER_AVAILABLE) {
        schemaPathDesc = INFO_LDIF_DIFF_ARG_DESC_SCHEMA_PATH_PING_SERVER.get();
    } else {
        schemaPathDesc = INFO_LDIF_DIFF_ARG_DESC_SCHEMA_PATH_STANDALONE.get();
    }
    schemaPath = new FileArgument(null, "schemaPath", false, 0, null, schemaPathDesc, true, true, false, false);
    schemaPath.addLongIdentifier("schema-path", true);
    schemaPath.addLongIdentifier("schemaFile", true);
    schemaPath.addLongIdentifier("schema-file", true);
    schemaPath.addLongIdentifier("schemaDirectory", true);
    schemaPath.addLongIdentifier("schema-directory", true);
    schemaPath.addLongIdentifier("schema", true);
    parser.addArgument(schemaPath);
    parser.addDependentArgumentSet(compressOutput, outputLDIF);
    parser.addDependentArgumentSet(encryptOutput, outputLDIF);
    parser.addDependentArgumentSet(outputEncryptionPassphraseFile, outputLDIF);
    parser.addDependentArgumentSet(overwriteExistingOutputLDIF, outputLDIF);
    parser.addDependentArgumentSet(outputEncryptionPassphraseFile, encryptOutput);
    parser.addExclusiveArgumentSet(includeAttribute, excludeAttribute);
    parser.addExclusiveArgumentSet(includeAttribute, includeOperationalAttributes);
    parser.addExclusiveArgumentSet(includeFilter, excludeFilter);
    parser.addDependentArgumentSet(excludeNoUserModificationAttributes, includeOperationalAttributes);
    parser.addExclusiveArgumentSet(nonReversibleModifications, singleValueChanges);
}
Also used : FilterArgument(com.unboundid.util.args.FilterArgument) BooleanArgument(com.unboundid.util.args.BooleanArgument) FileArgument(com.unboundid.util.args.FileArgument) StringArgument(com.unboundid.util.args.StringArgument)

Example 37 with BooleanArgument

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

the class LDIFSearch method addToolArguments.

/**
 * {@inheritDoc}
 */
@Override()
public void addToolArguments(@NotNull final ArgumentParser parser) throws ArgumentException {
    this.parser = parser;
    ldifFile = new FileArgument('l', "ldifFile", true, 0, null, INFO_LDIFSEARCH_ARG_DESC_LDIF_FILE.get(), true, true, true, false);
    ldifFile.addLongIdentifier("ldif-file", true);
    ldifFile.addLongIdentifier("inputFile", true);
    ldifFile.addLongIdentifier("input-file", true);
    ldifFile.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_INPUT.get());
    parser.addArgument(ldifFile);
    final String ldifPWDesc;
    if (PING_SERVER_AVAILABLE) {
        ldifPWDesc = INFO_LDIFSEARCH_ARG_DESC_LDIF_PW_FILE_PING_SERVER.get();
    } else {
        ldifPWDesc = INFO_LDIFSEARCH_ARG_DESC_LDIF_PW_FILE_STANDALONE.get();
    }
    ldifEncryptionPassphraseFile = new FileArgument(null, "ldifEncryptionPassphraseFile", false, 1, null, ldifPWDesc, true, true, true, false);
    ldifEncryptionPassphraseFile.addLongIdentifier("ldif-encryption-passphrase-file", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("ldifPassphraseFile", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("ldif-passphrase-file", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("ldifEncryptionPasswordFile", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("ldif-encryption-password-file", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("ldifPasswordFile", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("ldif-password-file", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("inputEncryptionPassphraseFile", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("input-encryption-passphrase-file", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("inputPassphraseFile", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("input-passphrase-file", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("inputEncryptionPasswordFile", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("input-encryption-password-file", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("inputPasswordFile", true);
    ldifEncryptionPassphraseFile.addLongIdentifier("input-password-file", true);
    ldifEncryptionPassphraseFile.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_INPUT.get());
    parser.addArgument(ldifEncryptionPassphraseFile);
    stripTrailingSpaces = new BooleanArgument(null, "stripTrailingSpaces", 1, INFO_LDIFSEARCH_ARG_DESC_STRIP_TRAILING_SPACES.get());
    stripTrailingSpaces.addLongIdentifier("strip-trailing-spaces", true);
    stripTrailingSpaces.addLongIdentifier("ignoreTrailingSpaces", true);
    stripTrailingSpaces.addLongIdentifier("ignore-trailing-spaces", true);
    stripTrailingSpaces.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_INPUT.get());
    parser.addArgument(stripTrailingSpaces);
    final String schemaPathDesc;
    if (PING_SERVER_AVAILABLE) {
        schemaPathDesc = INFO_LDIFSEARCH_ARG_DESC_SCHEMA_PATH_PING_SERVER.get();
    } else {
        schemaPathDesc = INFO_LDIFSEARCH_ARG_DESC_SCHEMA_PATH_STANDALONE.get();
    }
    schemaPath = new FileArgument(null, "schemaPath", false, 0, null, schemaPathDesc, true, true, false, false);
    schemaPath.addLongIdentifier("schema-path", true);
    schemaPath.addLongIdentifier("schemaFile", true);
    schemaPath.addLongIdentifier("schema-file", true);
    schemaPath.addLongIdentifier("schemaDirectory", true);
    schemaPath.addLongIdentifier("schema-directory", true);
    schemaPath.addLongIdentifier("schema", true);
    schemaPath.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_INPUT.get());
    parser.addArgument(schemaPath);
    checkSchema = new BooleanArgument(null, "checkSchema", 1, INFO_LDIFSEARCH_ARG_DESC_CHECK_SCHEMA.get());
    checkSchema.addLongIdentifier("check-schema", true);
    checkSchema.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_INPUT.get());
    parser.addArgument(checkSchema);
    isCompressed = new BooleanArgument(null, "isCompressed", 1, INFO_LDIFSEARCH_ARG_DESC_IS_COMPRESSED.get());
    isCompressed.addLongIdentifier("is-compressed", true);
    isCompressed.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_INPUT.get());
    isCompressed.setHidden(true);
    parser.addArgument(isCompressed);
    outputFile = new FileArgument('o', "outputFile", false, 1, null, INFO_LDIFSEARCH_ARG_DESC_OUTPUT_FILE.get(), false, true, true, false);
    outputFile.addLongIdentifier("output-file", true);
    outputFile.addLongIdentifier("outputLDIF", true);
    outputFile.addLongIdentifier("output-ldif", true);
    outputFile.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(outputFile);
    separateOutputFilePerSearch = new BooleanArgument(null, "separateOutputFilePerSearch", 1, INFO_LDIFSEARCH_ARG_DESC_SEPARATE_OUTPUT_FILES.get());
    separateOutputFilePerSearch.addLongIdentifier("separate-output-file-per-search", true);
    separateOutputFilePerSearch.addLongIdentifier("separateOutputFiles", true);
    separateOutputFilePerSearch.addLongIdentifier("separate-output-files", true);
    separateOutputFilePerSearch.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(separateOutputFilePerSearch);
    compressOutput = new BooleanArgument(null, "compressOutput", 1, INFO_LDIFSEARCH_ARG_DESC_COMPRESS_OUTPUT.get());
    compressOutput.addLongIdentifier("compress-output", true);
    compressOutput.addLongIdentifier("compressLDIF", true);
    compressOutput.addLongIdentifier("compress-ldif", true);
    compressOutput.addLongIdentifier("compress", true);
    compressOutput.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(compressOutput);
    encryptOutput = new BooleanArgument(null, "encryptOutput", 1, INFO_LDIFSEARCH_ARG_DESC_ENCRYPT_OUTPUT.get());
    encryptOutput.addLongIdentifier("encrypt-output", true);
    encryptOutput.addLongIdentifier("encryptLDIF", true);
    encryptOutput.addLongIdentifier("encrypt-ldif", true);
    encryptOutput.addLongIdentifier("encrypt", true);
    encryptOutput.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(encryptOutput);
    outputEncryptionPassphraseFile = new FileArgument(null, "outputEncryptionPassphraseFile", false, 1, null, INFO_LDIFSEARCH_ARG_DESC_OUTPUT_PW_FILE.get(), true, true, true, false);
    outputEncryptionPassphraseFile.addLongIdentifier("output-encryption-passphrase-file", true);
    outputEncryptionPassphraseFile.addLongIdentifier("outputPassphraseFile", true);
    outputEncryptionPassphraseFile.addLongIdentifier("output-passphrase-file", true);
    outputEncryptionPassphraseFile.addLongIdentifier("outputEncryptionPasswordFile", true);
    outputEncryptionPassphraseFile.addLongIdentifier("output-encryption-password-file", true);
    outputEncryptionPassphraseFile.addLongIdentifier("outputPasswordFile", true);
    outputEncryptionPassphraseFile.addLongIdentifier("output-password-file", true);
    outputEncryptionPassphraseFile.addLongIdentifier("outputEncryptionPasswordFile", true);
    outputEncryptionPassphraseFile.addLongIdentifier("output-encryption-password-file", true);
    outputEncryptionPassphraseFile.addLongIdentifier("outputPasswordFile", true);
    outputEncryptionPassphraseFile.addLongIdentifier("output-password-file", true);
    outputEncryptionPassphraseFile.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(outputEncryptionPassphraseFile);
    overwriteExistingOutputFile = new BooleanArgument('O', "overwriteExistingOutputFile", 1, INFO_LDIFSEARCH_ARG_DESC_OVERWRITE_EXISTING.get());
    overwriteExistingOutputFile.addLongIdentifier("overwrite-existing-output-file", true);
    overwriteExistingOutputFile.addLongIdentifier("overwriteExistingOutputFiles", true);
    overwriteExistingOutputFile.addLongIdentifier("overwrite-existing-output-files", true);
    overwriteExistingOutputFile.addLongIdentifier("overwriteExistingOutput", true);
    overwriteExistingOutputFile.addLongIdentifier("overwrite-existing-output", true);
    overwriteExistingOutputFile.addLongIdentifier("overwriteExisting", true);
    overwriteExistingOutputFile.addLongIdentifier("overwrite-existing", true);
    overwriteExistingOutputFile.addLongIdentifier("overwrite", true);
    overwriteExistingOutputFile.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(overwriteExistingOutputFile);
    final Set<String> outputFormatAllowedValues = StaticUtils.setOf("ldif", "json", "csv", "multi-valued-csv", "tab-delimited", "multi-valued-tab-delimited", "dns-only", "values-only");
    outputFormat = new StringArgument(null, "outputFormat", false, 1, "{ldif|json|csv|multi-valued-csv|tab-delimited|" + "multi-valued-tab-delimited|dns-only|values-only}", INFO_LDIFSEARCH_ARG_DESC_OUTPUT_FORMAT.get(), outputFormatAllowedValues, "ldif");
    outputFormat.addLongIdentifier("output-format", true);
    outputFormat.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(outputFormat);
    wrapColumn = new IntegerArgument(null, "wrapColumn", false, 1, null, INFO_LDIFSEARCH_ARG_DESC_WRAP_COLUMN.get(), 5, Integer.MAX_VALUE);
    wrapColumn.addLongIdentifier("wrap-column", true);
    wrapColumn.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(wrapColumn);
    doNotWrap = new BooleanArgument('T', "doNotWrap", 1, INFO_LDIFSEARCH_ARG_DESC_DO_NOT_WRAP.get());
    doNotWrap.addLongIdentifier("do-not-wrap", true);
    doNotWrap.addLongIdentifier("dontWrap", true);
    doNotWrap.addLongIdentifier("dont-wrap", true);
    doNotWrap.addLongIdentifier("noWrap", true);
    doNotWrap.addLongIdentifier("no-wrap", true);
    doNotWrap.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_OUTPUT.get());
    parser.addArgument(doNotWrap);
    baseDN = new DNArgument('b', "baseDN", false, 1, null, INFO_LDIFSEARCH_ARG_DESC_BASE_DN.get());
    baseDN.addLongIdentifier("base-dn", true);
    baseDN.addLongIdentifier("searchBaseDN", true);
    baseDN.addLongIdentifier("search-base-dn", true);
    baseDN.addLongIdentifier("searchBase", true);
    baseDN.addLongIdentifier("search-base", true);
    baseDN.addLongIdentifier("base", true);
    baseDN.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_CRITERIA.get());
    parser.addArgument(baseDN);
    scope = new ScopeArgument('s', "scope", false, null, INFO_LDIFSEARCH_ARG_DESC_SCOPE.get());
    scope.addLongIdentifier("searchScope", true);
    scope.addLongIdentifier("search-scope", true);
    scope.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_CRITERIA.get());
    parser.addArgument(scope);
    filterFile = new FileArgument('f', "filterFile", false, 0, null, INFO_LDIFSEARCH_ARG_DESC_FILTER_FILE.get(), true, true, true, false);
    filterFile.addLongIdentifier("filter-file", true);
    filterFile.addLongIdentifier("filtersFile", true);
    filterFile.addLongIdentifier("filters-file", true);
    filterFile.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_CRITERIA.get());
    parser.addArgument(filterFile);
    ldapURLFile = new FileArgument(null, "ldapURLFile", false, 0, null, INFO_LDIFSEARCH_ARG_DESC_LDAP_URL_FILE.get(), true, true, true, false);
    ldapURLFile.addLongIdentifier("ldap-url-file", true);
    ldapURLFile.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_CRITERIA.get());
    parser.addArgument(ldapURLFile);
    sizeLimit = new IntegerArgument('z', "sizeLimit", false, 1, null, INFO_LDIFSEARCH_ARG_DESC_SIZE_LIMIT.get(), 0, Integer.MAX_VALUE, 0);
    sizeLimit.addLongIdentifier("size-limit", true);
    sizeLimit.addLongIdentifier("searchSizeLimit", true);
    sizeLimit.addLongIdentifier("search-size-limit", true);
    sizeLimit.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_CRITERIA.get());
    sizeLimit.setHidden(true);
    parser.addArgument(sizeLimit);
    timeLimitSeconds = new IntegerArgument('t', "timeLimitSeconds", false, 1, null, INFO_LDIFSEARCH_ARG_DESC_TIME_LIMIT_SECONDS.get(), 0, Integer.MAX_VALUE, 0);
    timeLimitSeconds.addLongIdentifier("time-limit-seconds", true);
    timeLimitSeconds.addLongIdentifier("timeLimit", true);
    timeLimitSeconds.setArgumentGroupName(INFO_LDIFSEARCH_ARG_GROUP_CRITERIA.get());
    timeLimitSeconds.setHidden(true);
    parser.addArgument(timeLimitSeconds);
    parser.addDependentArgumentSet(separateOutputFilePerSearch, outputFile);
    parser.addDependentArgumentSet(compressOutput, outputFile);
    parser.addDependentArgumentSet(encryptOutput, outputFile);
    parser.addDependentArgumentSet(overwriteExistingOutputFile, outputFile);
    parser.addDependentArgumentSet(outputEncryptionPassphraseFile, encryptOutput);
    parser.addExclusiveArgumentSet(wrapColumn, doNotWrap);
    parser.addExclusiveArgumentSet(baseDN, ldapURLFile);
    parser.addExclusiveArgumentSet(scope, ldapURLFile);
    parser.addExclusiveArgumentSet(filterFile, ldapURLFile);
    parser.addExclusiveArgumentSet(outputFormat, separateOutputFilePerSearch);
}
Also used : DNArgument(com.unboundid.util.args.DNArgument) 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 38 with BooleanArgument

use of com.unboundid.util.args.BooleanArgument 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)

Example 39 with BooleanArgument

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

the class ManageCertificates method doCheckCertificateUsability.

/**
 * Performs the necessary processing for the check-certificate-usability
 * subcommand.
 *
 * @return  A result code that indicates whether the processing completed
 *          successfully.
 */
@NotNull()
private ResultCode doCheckCertificateUsability() {
    // Get the values of a number of configured arguments.
    final StringArgument aliasArgument = subCommandParser.getStringArgument("alias");
    final String alias = aliasArgument.getValue();
    final String keystoreType;
    final File keystorePath = getKeystorePath();
    try {
        keystoreType = inferKeystoreType(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final char[] keystorePassword;
    try {
        keystorePassword = getKeystorePassword(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Get the keystore.
    final KeyStore keystore;
    try {
        keystore = getKeystore(keystoreType, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Make sure that the specified entry exists in the keystore and is
    // associated with a certificate chain and a private key.
    final X509Certificate[] chain;
    if (hasKeyAlias(keystore, alias)) {
        try {
            final Certificate[] genericChain = keystore.getCertificateChain(alias);
            Validator.ensureTrue((genericChain.length > 0), "ERROR:  The keystore has a private key entry for alias '" + alias + "', but the associated certificate chain is empty.");
            chain = new X509Certificate[genericChain.length];
            for (int i = 0; i < genericChain.length; i++) {
                chain[i] = new X509Certificate(genericChain[i].getEncoded());
            }
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_GOT_CHAIN.get(alias));
            for (final X509Certificate c : chain) {
                out();
                printCertificate(c, "", false);
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_CANNOT_GET_CHAIN.get(alias));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
    } else if (hasCertificateAlias(keystore, alias)) {
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_NO_PRIVATE_KEY.get(alias));
        return ResultCode.PARAM_ERROR;
    } else {
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_NO_SUCH_ALIAS.get(alias));
        return ResultCode.PARAM_ERROR;
    }
    // Check to see if the certificate is self-signed.  If so, then that's a
    // warning.  If not, then make sure that the chain is complete and that each
    // subsequent certificate is the issuer of the previous.
    int numWarnings = 0;
    int numErrors = 0;
    if (chain[0].isSelfSigned()) {
        err();
        wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_CERT_IS_SELF_SIGNED.get(chain[0].getSubjectDN()));
        numWarnings++;
    } else if ((chain.length == 1) || (!chain[chain.length - 1].isSelfSigned())) {
        err();
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_END_OF_CHAIN_NOT_SELF_SIGNED.get(alias));
        numErrors++;
    } else {
        boolean chainError = false;
        final StringBuilder nonMatchReason = new StringBuilder();
        for (int i = 1; i < chain.length; i++) {
            if (!chain[i].isIssuerFor(chain[i - 1], nonMatchReason)) {
                err();
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_CHAIN_ISSUER_MISMATCH.get(alias, chain[i].getSubjectDN(), chain[i - 1].getSubjectDN(), nonMatchReason));
                numErrors++;
                chainError = true;
            }
        }
        if (!chainError) {
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_CHAIN_COMPLETE.get());
        }
    }
    // display a notice, but we won't consider it a warning in and of itself.
    if ((chain.length > 1) && chain[chain.length - 1].isSelfSigned()) {
        final X509Certificate caCert = chain[chain.length - 1];
        try {
            final String jvmDefaultTrustStoreType = inferKeystoreType(JVM_DEFAULT_CACERTS_FILE);
            final KeyStore jvmDefaultTrustStore = CryptoHelper.getKeyStore(jvmDefaultTrustStoreType);
            try (FileInputStream inputStream = new FileInputStream(JVM_DEFAULT_CACERTS_FILE)) {
                jvmDefaultTrustStore.load(inputStream, null);
            }
            boolean found = false;
            final Enumeration<String> aliases = jvmDefaultTrustStore.aliases();
            while (aliases.hasMoreElements()) {
                final String jvmDefaultCertAlias = aliases.nextElement();
                if (jvmDefaultTrustStore.isCertificateEntry(jvmDefaultCertAlias)) {
                    final Certificate c = jvmDefaultTrustStore.getCertificate(jvmDefaultCertAlias);
                    final X509Certificate xc = new X509Certificate(c.getEncoded());
                    if ((caCert.getSubjectDN().equals(xc.getSubjectDN())) && Arrays.equals(caCert.getSignatureValue().getBits(), xc.getSignatureValue().getBits())) {
                        found = true;
                        break;
                    }
                }
            }
            if (found) {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_CA_TRUSTED_OK.get(caCert.getSubjectDN()));
            } else {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_CA_NOT_IN_JVM_DEFAULT_TS.get(caCert.getSubjectDN()));
            }
        } catch (final Exception e) {
            Debug.debugException(e);
            err();
            wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_CHECK_CA_IN_TS_ERROR.get(caCert.getSubjectDN(), StaticUtils.getExceptionMessage(e)));
            numWarnings++;
        }
    }
    // error.
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate c = chain[i];
        try {
            if (c.isSelfSigned()) {
                c.verifySignature(null);
            } else if ((i + 1) < chain.length) {
                c.verifySignature(chain[i + 1]);
            }
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_CERT_SIGNATURE_VALID.get(c.getSubjectDN()));
        } catch (final CertException ce) {
            err();
            wrapErr(0, WRAP_COLUMN, ce.getMessage());
            numErrors++;
        }
    }
    // Check the validity window for each certificate in the chain.  If any of
    // them is expired or not yet valid, then that's an error.  If any of them
    // will expire in the near future, then that's a warning.
    final long currentTime = System.currentTimeMillis();
    final long thirtyDaysFromNow = currentTime + (30L * 24L * 60L * 60L * 1000L);
    for (int i = 0; i < chain.length; i++) {
        final X509Certificate c = chain[i];
        if (c.getNotBeforeTime() > currentTime) {
            err();
            if (i == 0) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_END_CERT_NOT_YET_VALID.get(c.getSubjectDN(), formatDateAndTime(c.getNotBeforeDate())));
            } else {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_NOT_YET_VALID.get(c.getSubjectDN(), formatDateAndTime(c.getNotBeforeDate())));
            }
            numErrors++;
        } else if (c.getNotAfterTime() < currentTime) {
            err();
            if (i == 0) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_END_CERT_EXPIRED.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            } else {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_EXPIRED.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            }
            numErrors++;
        } else if (c.getNotAfterTime() < thirtyDaysFromNow) {
            err();
            if (i == 0) {
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_END_CERT_NEAR_EXPIRATION.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            } else {
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_NEAR_EXPIRATION.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            }
            numWarnings++;
        } else {
            if (i == 0) {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_END_CERT_VALIDITY_OK.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            } else {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_VALIDITY_OK.get(c.getSubjectDN(), formatDateAndTime(c.getNotAfterDate())));
            }
        }
    }
    // determine whether the certificate has been revoked.
    for (int i = 0; i < chain.length; i++) {
        boolean basicConstraintsFound = false;
        boolean extendedKeyUsageFound = false;
        boolean keyUsageFound = false;
        final X509Certificate c = chain[i];
        for (final X509CertificateExtension extension : c.getExtensions()) {
            if (extension instanceof ExtendedKeyUsageExtension) {
                extendedKeyUsageFound = true;
                if (i == 0) {
                    final ExtendedKeyUsageExtension e = (ExtendedKeyUsageExtension) extension;
                    if (!e.getKeyPurposeIDs().contains(ExtendedKeyUsageID.TLS_SERVER_AUTHENTICATION.getOID())) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_END_CERT_BAD_EKU.get(c.getSubjectDN()));
                        numErrors++;
                    } else {
                        out();
                        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_END_CERT_GOOD_EKU.get(c.getSubjectDN()));
                    }
                }
            } else if (extension instanceof BasicConstraintsExtension) {
                basicConstraintsFound = true;
                if (i > 0) {
                    final BasicConstraintsExtension e = (BasicConstraintsExtension) extension;
                    if (!e.isCA()) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_BAD_BC_CA.get(c.getSubjectDN()));
                        numErrors++;
                    } else if ((e.getPathLengthConstraint() != null) && ((i - 1) > e.getPathLengthConstraint())) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_BAD_BC_LENGTH.get(c.getSubjectDN(), e.getPathLengthConstraint(), chain[0].getSubjectDN(), (i - 1)));
                        numErrors++;
                    } else {
                        out();
                        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_ISSUER_CERT_GOOD_BC.get(c.getSubjectDN()));
                    }
                }
            } else if (extension instanceof KeyUsageExtension) {
                keyUsageFound = true;
                if (i > 0) {
                    final KeyUsageExtension e = (KeyUsageExtension) extension;
                    if (!e.isKeyCertSignBitSet()) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ISSUER_NO_CERT_SIGN_KU.get(c.getSubjectDN()));
                        numErrors++;
                    } else {
                        out();
                        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_ISSUER_GOOD_KU.get(c.getSubjectDN()));
                    }
                }
            }
        }
        if (i == 0) {
            if (!extendedKeyUsageFound) {
                err();
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_NO_EKU.get(c.getSubjectDN()));
                numWarnings++;
            }
        } else {
            if (!basicConstraintsFound) {
                err();
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_NO_BC.get(c.getSubjectDN()));
                numWarnings++;
            }
            if (!keyUsageFound) {
                err();
                wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_NO_KU.get(c.getSubjectDN()));
                numWarnings++;
            }
        }
    }
    // Make sure that none of the certificates has a signature algorithm that
    // uses MD5 or SHA-1.  If it uses an unrecognized signature algorithm, then
    // that's a warning.
    boolean isIssuer = false;
    final BooleanArgument ignoreSHA1WarningArg = subCommandParser.getBooleanArgument("allow-sha-1-signature-for-issuer-certificates");
    final boolean ignoreSHA1SignatureWarningForIssuerCertificates = ((ignoreSHA1WarningArg != null) && ignoreSHA1WarningArg.isPresent());
    for (final X509Certificate c : chain) {
        final OID signatureAlgorithmOID = c.getSignatureAlgorithmOID();
        final SignatureAlgorithmIdentifier id = SignatureAlgorithmIdentifier.forOID(signatureAlgorithmOID);
        if (id == null) {
            err();
            wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_UNKNOWN_SIG_ALG.get(c.getSubjectDN(), signatureAlgorithmOID));
            numWarnings++;
        } else {
            switch(id) {
                case MD2_WITH_RSA:
                case MD5_WITH_RSA:
                    err();
                    wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_WEAK_SIG_ALG.get(c.getSubjectDN(), id.getUserFriendlyName()));
                    numErrors++;
                    break;
                case SHA_1_WITH_RSA:
                case SHA_1_WITH_DSA:
                case SHA_1_WITH_ECDSA:
                    if (isIssuer && ignoreSHA1SignatureWarningForIssuerCertificates) {
                        err();
                        wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_CHECK_USABILITY_ISSUER_WITH_SHA1_SIG.get(c.getSubjectDN(), id.getUserFriendlyName(), ignoreSHA1WarningArg.getIdentifierString()));
                    } else {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_WEAK_SIG_ALG.get(c.getSubjectDN(), id.getUserFriendlyName()));
                        numErrors++;
                    }
                    break;
                case SHA_224_WITH_RSA:
                case SHA_224_WITH_DSA:
                case SHA_224_WITH_ECDSA:
                case SHA_256_WITH_RSA:
                case SHA_256_WITH_DSA:
                case SHA_256_WITH_ECDSA:
                case SHA_384_WITH_RSA:
                case SHA_384_WITH_ECDSA:
                case SHA_512_WITH_RSA:
                case SHA_512_WITH_ECDSA:
                    out();
                    wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_SIG_ALG_OK.get(c.getSubjectDN(), id.getUserFriendlyName()));
                    break;
            }
        }
        isIssuer = true;
    }
    // has a public modulus size smaller than 2048 bits.
    for (final X509Certificate c : chain) {
        if ((c.getDecodedPublicKey() != null) && (c.getDecodedPublicKey() instanceof RSAPublicKey)) {
            final RSAPublicKey rsaPublicKey = (RSAPublicKey) c.getDecodedPublicKey();
            final byte[] modulusBytes = rsaPublicKey.getModulus().toByteArray();
            int modulusSizeBits = modulusBytes.length * 8;
            if (((modulusBytes.length % 2) != 0) && (modulusBytes[0] == 0x00)) {
                modulusSizeBits -= 8;
            }
            if (modulusSizeBits < 2048) {
                err();
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_WEAK_RSA_MODULUS.get(c.getSubjectDN(), modulusSizeBits));
                numErrors++;
            } else {
                out();
                wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_RSA_MODULUS_OK.get(c.getSubjectDN(), modulusSizeBits));
            }
        }
    }
    switch(numErrors) {
        case 0:
            break;
        case 1:
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ONE_ERROR.get());
            return ResultCode.PARAM_ERROR;
        default:
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_MULTIPLE_ERRORS.get(numErrors));
            return ResultCode.PARAM_ERROR;
    }
    switch(numWarnings) {
        case 0:
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_CHECK_USABILITY_NO_ERRORS_OR_WARNINGS.get());
            return ResultCode.SUCCESS;
        case 1:
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_ONE_WARNING.get());
            return ResultCode.PARAM_ERROR;
        default:
            err();
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_CHECK_USABILITY_MULTIPLE_WARNINGS.get(numWarnings));
            return ResultCode.PARAM_ERROR;
    }
}
Also used : ASN1BitString(com.unboundid.asn1.ASN1BitString) BooleanArgument(com.unboundid.util.args.BooleanArgument) OID(com.unboundid.util.OID) KeyStore(java.security.KeyStore) ArgumentException(com.unboundid.util.args.ArgumentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) StringArgument(com.unboundid.util.args.StringArgument) LDAPException(com.unboundid.ldap.sdk.LDAPException) File(java.io.File) Certificate(java.security.cert.Certificate) NotNull(com.unboundid.util.NotNull)

Example 40 with BooleanArgument

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

the class ManageCertificates method doImportCertificate.

/**
 * Performs the necessary processing for the import-certificate subcommand.
 *
 * @return  A result code that indicates whether the processing completed
 *          successfully.
 */
@NotNull()
private ResultCode doImportCertificate() {
    // Get the values of a number of configured arguments.
    final StringArgument aliasArgument = subCommandParser.getStringArgument("alias");
    final String alias = aliasArgument.getValue();
    final FileArgument certificateFileArgument = subCommandParser.getFileArgument("certificate-file");
    final List<File> certFiles = certificateFileArgument.getValues();
    final File privateKeyFile;
    final FileArgument privateKeyFileArgument = subCommandParser.getFileArgument("private-key-file");
    if ((privateKeyFileArgument != null) && privateKeyFileArgument.isPresent()) {
        privateKeyFile = privateKeyFileArgument.getValue();
    } else {
        privateKeyFile = null;
    }
    final BooleanArgument noPromptArgument = subCommandParser.getBooleanArgument("no-prompt");
    final boolean noPrompt = ((noPromptArgument != null) && noPromptArgument.isPresent());
    final String keystoreType;
    final File keystorePath = getKeystorePath();
    final boolean isNewKeystore = (!keystorePath.exists());
    try {
        keystoreType = inferKeystoreType(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    final char[] keystorePassword;
    try {
        keystorePassword = getKeystorePassword(keystorePath);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // Read the contents of the certificate files.
    final ArrayList<X509Certificate> certList = new ArrayList<>(5);
    for (final File certFile : certFiles) {
        try {
            final List<X509Certificate> certs = readCertificatesFromFile(certFile);
            if (certs.isEmpty()) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_NO_CERTS_IN_FILE.get(certFile.getAbsolutePath()));
                return ResultCode.PARAM_ERROR;
            }
            certList.addAll(certs);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            wrapErr(0, WRAP_COLUMN, le.getMessage());
            return le.getResultCode();
        }
    }
    // If a private key file was specified, then read the private key.
    final PKCS8PrivateKey privateKey;
    if (privateKeyFile == null) {
        privateKey = null;
    } else {
        try {
            privateKey = readPrivateKeyFromFile(privateKeyFile);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            wrapErr(0, WRAP_COLUMN, le.getMessage());
            return le.getResultCode();
        }
    }
    // Get the keystore.
    final KeyStore keystore;
    try {
        keystore = getKeystore(keystoreType, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // If there is a private key, then see if we need to use a private key
    // password that is different from the keystore password.
    final char[] privateKeyPassword;
    try {
        privateKeyPassword = getPrivateKeyPassword(keystore, alias, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    // If we should display an equivalent keytool command, then do that now.
    final BooleanArgument displayKeytoolCommandArgument = subCommandParser.getBooleanArgument("display-keytool-command");
    if ((displayKeytoolCommandArgument != null) && displayKeytoolCommandArgument.isPresent()) {
        final ArrayList<String> keytoolArgs = new ArrayList<>(10);
        keytoolArgs.add("-import");
        keytoolArgs.add("-keystore");
        keytoolArgs.add(keystorePath.getAbsolutePath());
        keytoolArgs.add("-storetype");
        keytoolArgs.add(keystoreType);
        keytoolArgs.add("-storepass");
        keytoolArgs.add("*****REDACTED*****");
        keytoolArgs.add("-keypass");
        keytoolArgs.add("*****REDACTED*****");
        keytoolArgs.add("-alias");
        keytoolArgs.add(alias);
        keytoolArgs.add("-file");
        keytoolArgs.add(certFiles.get(0).getAbsolutePath());
        keytoolArgs.add("-trustcacerts");
        displayKeytoolCommand(keytoolArgs);
    }
    // Look at all the certificates to be imported.  Make sure that every
    // subsequent certificate in the chain is the issuer for the previous.
    final Iterator<X509Certificate> certIterator = certList.iterator();
    X509Certificate subjectCert = certIterator.next();
    while (true) {
        if (subjectCert.isSelfSigned()) {
            if (certIterator.hasNext()) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_SELF_SIGNED_NOT_LAST.get(subjectCert.getSubjectDN()));
                return ResultCode.PARAM_ERROR;
            }
        }
        if (!certIterator.hasNext()) {
            break;
        }
        final X509Certificate issuerCert = certIterator.next();
        final StringBuilder notIssuerReason = new StringBuilder();
        if (!issuerCert.isIssuerFor(subjectCert, notIssuerReason)) {
            // silently ignore it.
            if (Arrays.equals(issuerCert.getX509CertificateBytes(), subjectCert.getX509CertificateBytes())) {
                certIterator.remove();
            } else {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_NEXT_NOT_ISSUER_OF_PREV.get(notIssuerReason.toString()));
                return ResultCode.PARAM_ERROR;
            }
        }
        subjectCert = issuerCert;
    }
    // If the last certificate in the chain is not self-signed, then make sure
    // that we can complete the chain using other certificates in the keystore
    // or in the JVM's set of default trusted issuers.  If we can't complete
    // the chain, then that's an error, although we'll go ahead and proceed
    // anyway with the import if we're not also importing a private key.
    final ArrayList<X509Certificate> chain;
    if (certList.get(certList.size() - 1).isSelfSigned()) {
        chain = certList;
    } else {
        chain = new ArrayList<>(certList.size() + 5);
        chain.addAll(certList);
        final AtomicReference<KeyStore> jvmDefaultTrustStoreRef = new AtomicReference<>();
        final AtomicReference<DN> missingIssuerRef = new AtomicReference<>();
        X509Certificate c = certList.get(certList.size() - 1);
        while (!c.isSelfSigned()) {
            final X509Certificate issuer;
            try {
                issuer = getIssuerCertificate(c, keystore, jvmDefaultTrustStoreRef, missingIssuerRef);
            } catch (final Exception e) {
                Debug.debugException(e);
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_CANNOT_GET_ISSUER.get(c.getIssuerDN()));
                e.printStackTrace(getErr());
                return ResultCode.LOCAL_ERROR;
            }
            if (issuer == null) {
                final byte[] authorityKeyIdentifier = getAuthorityKeyIdentifier(c);
                // with just a warning.
                if ((privateKey != null) || hasKeyAlias(keystore, alias)) {
                    if (authorityKeyIdentifier == null) {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_NO_ISSUER_NO_AKI.get(c.getIssuerDN()));
                    } else {
                        err();
                        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_NO_ISSUER_WITH_AKI.get(c.getIssuerDN(), toColonDelimitedHex(authorityKeyIdentifier)));
                    }
                    return ResultCode.PARAM_ERROR;
                } else {
                    if (authorityKeyIdentifier == null) {
                        err();
                        wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_IMPORT_CERT_NO_ISSUER_NO_AKI.get(c.getIssuerDN()));
                    } else {
                        err();
                        wrapErr(0, WRAP_COLUMN, WARN_MANAGE_CERTS_IMPORT_CERT_NO_ISSUER_WITH_AKI.get(c.getIssuerDN(), toColonDelimitedHex(authorityKeyIdentifier)));
                    }
                    break;
                }
            } else {
                chain.add(issuer);
                c = issuer;
            }
        }
    }
    // perform the necessary validation and do the import.
    if (privateKey != null) {
        // with the specified alias.
        if (hasKeyAlias(keystore, alias)) {
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_WITH_PK_KEY_ALIAS_CONFLICT.get(alias));
            return ResultCode.PARAM_ERROR;
        } else if (hasCertificateAlias(keystore, alias)) {
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_WITH_PK_CERT_ALIAS_CONFLICT.get(alias));
            return ResultCode.PARAM_ERROR;
        }
        // Make sure that the private key has a key algorithm of either RSA or EC,
        // and convert it into a Java PrivateKey object.
        final PrivateKey javaPrivateKey;
        try {
            javaPrivateKey = privateKey.toPrivateKey();
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_ERROR_CONVERTING_KEY.get(privateKeyFile.getAbsolutePath()));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
        // Convert the certificate chain into a Java Certificate[].
        final Certificate[] javaCertificateChain = new Certificate[chain.size()];
        for (int i = 0; i < javaCertificateChain.length; i++) {
            final X509Certificate c = chain.get(i);
            try {
                javaCertificateChain[i] = c.toCertificate();
            } catch (final Exception e) {
                Debug.debugException(e);
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_ERROR_CONVERTING_CERT.get(c.getSubjectDN()));
                e.printStackTrace(getErr());
                return ResultCode.LOCAL_ERROR;
            }
        }
        // Prompt the user to confirm the import, if appropriate.
        if (!noPrompt) {
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_CONFIRM_IMPORT_CHAIN_NEW_KEY.get(alias));
            for (final X509Certificate c : chain) {
                out();
                printCertificate(c, "", false);
            }
            out();
            try {
                if (!promptForYesNo(INFO_MANAGE_CERTS_IMPORT_CERT_PROMPT_IMPORT_CHAIN.get())) {
                    wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_CANCELED.get());
                    return ResultCode.USER_CANCELED;
                }
            } catch (final LDAPException le) {
                Debug.debugException(le);
                err();
                wrapErr(0, WRAP_COLUMN, le.getMessage());
                return le.getResultCode();
            }
        }
        // Set the private key entry in the keystore.
        try {
            keystore.setKeyEntry(alias, javaPrivateKey, privateKeyPassword, javaCertificateChain);
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_ERROR_UPDATING_KS_WITH_CHAIN.get(alias));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
        // Write the updated keystore to disk.
        try {
            writeKeystore(keystore, keystorePath, keystorePassword);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            wrapErr(0, WRAP_COLUMN, le.getMessage());
            return le.getResultCode();
        }
        if (isNewKeystore) {
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_CREATED_KEYSTORE.get(getUserFriendlyKeystoreType(keystoreType)));
        }
        out();
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_IMPORTED_CHAIN_WITH_PK.get());
        return ResultCode.SUCCESS;
    }
    // the specified alias.  If so, then that's always an error.
    if (hasCertificateAlias(keystore, alias)) {
        wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_WITH_CONFLICTING_CERT_ALIAS.get(alias));
        return ResultCode.PARAM_ERROR;
    }
    // of the existing chain in that alias.
    if (hasKeyAlias(keystore, alias)) {
        // Make sure that the existing key pair uses the same public key as the
        // new certificate we are importing.
        final PrivateKey existingPrivateKey;
        final Certificate[] existingChain;
        final X509Certificate existingEndCertificate;
        try {
            existingPrivateKey = (PrivateKey) keystore.getKey(alias, privateKeyPassword);
            existingChain = keystore.getCertificateChain(alias);
            existingEndCertificate = new X509Certificate(existingChain[0].getEncoded());
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_INTO_KEY_ALIAS_CANNOT_GET_KEY.get(alias));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
        final boolean[] existingPublicKeyBits = existingEndCertificate.getEncodedPublicKey().getBits();
        final boolean[] newPublicKeyBits = chain.get(0).getEncodedPublicKey().getBits();
        if (!Arrays.equals(existingPublicKeyBits, newPublicKeyBits)) {
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_INTO_KEY_ALIAS_KEY_MISMATCH.get(alias));
            return ResultCode.PARAM_ERROR;
        }
        // Prepare the new certificate chain to store in the alias.
        final Certificate[] newChain = new Certificate[chain.size()];
        for (int i = 0; i < chain.size(); i++) {
            final X509Certificate c = chain.get(i);
            try {
                newChain[i] = c.toCertificate();
            } catch (final Exception e) {
                Debug.debugException(e);
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_ERROR_CONVERTING_CERT.get(c.getSubjectDN()));
                e.printStackTrace(getErr());
                return ResultCode.LOCAL_ERROR;
            }
        }
        // Prompt the user to confirm the import, if appropriate.
        if (!noPrompt) {
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_CONFIRM_IMPORT_CHAIN_EXISTING_KEY.get(alias));
            for (final X509Certificate c : chain) {
                out();
                printCertificate(c, "", false);
            }
            out();
            try {
                if (!promptForYesNo(INFO_MANAGE_CERTS_IMPORT_CERT_PROMPT_IMPORT_CHAIN.get())) {
                    wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_CANCELED.get());
                    return ResultCode.USER_CANCELED;
                }
            } catch (final LDAPException le) {
                Debug.debugException(le);
                err();
                wrapErr(0, WRAP_COLUMN, le.getMessage());
                return le.getResultCode();
            }
        }
        // Set the private key entry in the keystore.
        try {
            keystore.setKeyEntry(alias, existingPrivateKey, privateKeyPassword, newChain);
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_ERROR_UPDATING_KS_WITH_CHAIN.get(alias));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
        // Write the updated keystore to disk.
        try {
            writeKeystore(keystore, keystorePath, keystorePassword);
        } catch (final LDAPException le) {
            Debug.debugException(le);
            wrapErr(0, WRAP_COLUMN, le.getMessage());
            return le.getResultCode();
        }
        out();
        if (isNewKeystore) {
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_CREATED_KEYSTORE.get(getUserFriendlyKeystoreType(keystoreType)));
        }
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_IMPORTED_CHAIN_WITHOUT_PK.get());
        return ResultCode.SUCCESS;
    }
    // If we've gotten here, then we know that we're just going to add
    // certificate entries to the keystore.  Iterate through the certificates
    // and add them to the keystore under the appropriate aliases, first making
    // sure that the alias isn't already in use.
    final LinkedHashMap<String, X509Certificate> certMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(certList.size()));
    for (int i = 0; i < certList.size(); i++) {
        final X509Certificate x509Certificate = certList.get(i);
        final Certificate javaCertificate;
        try {
            javaCertificate = x509Certificate.toCertificate();
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_ERROR_CONVERTING_CERT.get(x509Certificate.getSubjectDN()));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
        final String certAlias;
        if (i == 0) {
            certAlias = alias;
        } else if (certList.size() > 2) {
            certAlias = alias + "-issuer-" + i;
        } else {
            certAlias = alias + "-issuer";
        }
        certMap.put(certAlias, x509Certificate);
        if (hasKeyAlias(keystore, certAlias) || hasCertificateAlias(keystore, certAlias)) {
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_WITH_CONFLICTING_ISSUER_ALIAS.get(x509Certificate.getSubjectDN(), certAlias));
            return ResultCode.PARAM_ERROR;
        }
        try {
            keystore.setCertificateEntry(certAlias, javaCertificate);
        } catch (final Exception e) {
            Debug.debugException(e);
            wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_ERROR_UPDATING_KS_WITH_CERT.get(x509Certificate.getSubjectDN(), alias));
            e.printStackTrace(getErr());
            return ResultCode.LOCAL_ERROR;
        }
    }
    // Prompt about whether to perform the import, if appropriate.
    if (!noPrompt) {
        out();
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_CONFIRM_IMPORT_CHAIN_NO_KEY.get(alias));
        for (final Map.Entry<String, X509Certificate> e : certMap.entrySet()) {
            out();
            wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_LABEL_ALIAS.get(e.getKey()));
            printCertificate(e.getValue(), "", false);
        }
        out();
        try {
            if (!promptForYesNo(INFO_MANAGE_CERTS_IMPORT_CERT_PROMPT_IMPORT_CHAIN.get())) {
                wrapErr(0, WRAP_COLUMN, ERR_MANAGE_CERTS_IMPORT_CERT_CANCELED.get());
                return ResultCode.USER_CANCELED;
            }
        } catch (final LDAPException le) {
            Debug.debugException(le);
            err();
            wrapErr(0, WRAP_COLUMN, le.getMessage());
            return le.getResultCode();
        }
    }
    // Write the updated keystore to disk.
    try {
        writeKeystore(keystore, keystorePath, keystorePassword);
    } catch (final LDAPException le) {
        Debug.debugException(le);
        wrapErr(0, WRAP_COLUMN, le.getMessage());
        return le.getResultCode();
    }
    out();
    if (isNewKeystore) {
        wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_CREATED_KEYSTORE.get(getUserFriendlyKeystoreType(keystoreType)));
    }
    wrapOut(0, WRAP_COLUMN, INFO_MANAGE_CERTS_IMPORT_CERT_IMPORTED_CHAIN_WITHOUT_PK.get());
    return ResultCode.SUCCESS;
}
Also used : PrivateKey(java.security.PrivateKey) ArrayList(java.util.ArrayList) DN(com.unboundid.ldap.sdk.DN) ASN1BitString(com.unboundid.asn1.ASN1BitString) FileArgument(com.unboundid.util.args.FileArgument) LinkedHashMap(java.util.LinkedHashMap) BooleanArgument(com.unboundid.util.args.BooleanArgument) AtomicReference(java.util.concurrent.atomic.AtomicReference) KeyStore(java.security.KeyStore) ArgumentException(com.unboundid.util.args.ArgumentException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException) StringArgument(com.unboundid.util.args.StringArgument) LDAPException(com.unboundid.ldap.sdk.LDAPException) File(java.io.File) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) Certificate(java.security.cert.Certificate) NotNull(com.unboundid.util.NotNull)

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