Search in sources :

Example 56 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class SchemaValidator method validateSchema.

/**
 * Validates the schema definitions in the file or set of files at the given
 * path.
 *
 * @param  schemaPath
 *              The file or directory containing the schema definitions to
 *              validate.  It must not be {@code null}, and the target file
 *              or directory must exist.  If it is a directory, then files in
 *              the directory will be processed in lexicographic order by
 *              filename, optionally restricted to files matching the schema
 *              file name pattern.
 * @param  existingSchema
 *              An existing schema to use in the course of validating
 *              definitions.  It may be {@code null} if there is no existing
 *              schema and only the definitions read from the provided path
 *              should be used.
 * @param  errorMessages
 *              A list that will be updated with error messages about any
 *              problems identified during processing.  It must not be
 *              {@code null}, and it must be updatable.
 *
 * @return  A {@code Schema} object that contains the definitions that were
 *          loaded.  This may include schema elements that were flagged as
 *          invalid (if they could be parsed).  If an existing schema was
 *          already available, the schema that is returned will be a merged
 *          representation of the existing schema and the newly loaded schema.
 *          This may be {@code null} if an error prevented any schema files
 *          from being processed and no existing schema was provided.
 */
@Nullable()
public Schema validateSchema(@NotNull final File schemaPath, @Nullable final Schema existingSchema, @NotNull final List<String> errorMessages) {
    final boolean originalAllowEmptyDescription = SchemaElement.allowEmptyDescription();
    try {
        SchemaElement.setAllowEmptyDescription(true);
        final int originalErrorMessagesSize = errorMessages.size();
        final AtomicInteger schemaFilesProcessed = new AtomicInteger(0);
        final List<File> nonSchemaFilesIgnored = new ArrayList<>();
        final Schema schema = validateSchema(schemaPath, errorMessages, existingSchema, schemaFilesProcessed, nonSchemaFilesIgnored);
        // processed, then add an error message to indicate that.
        if ((schemaFilesProcessed.get() == 0) && (errorMessages.size() == originalErrorMessagesSize)) {
            switch(nonSchemaFilesIgnored.size()) {
                case 0:
                    errorMessages.add(ERR_SCHEMA_VALIDATOR_NO_SCHEMA_FILES_NONE_IGNORED.get(schemaPath.getAbsolutePath()));
                    break;
                case 1:
                    errorMessages.add(ERR_SCHEMA_VALIDATOR_NO_SCHEMA_FILES_ONE_IGNORED.get(schemaPath.getAbsolutePath(), nonSchemaFilesIgnored.get(0).getAbsolutePath()));
                    break;
                default:
                    final StringBuilder buffer = new StringBuilder();
                    final Iterator<File> fileIterator = nonSchemaFilesIgnored.iterator();
                    while (fileIterator.hasNext()) {
                        buffer.append('\'');
                        buffer.append(fileIterator.next().getAbsolutePath());
                        buffer.append('\'');
                        if (fileIterator.hasNext()) {
                            buffer.append(", ");
                        }
                    }
                    errorMessages.add(ERR_SCHEMA_VALIDATOR_NO_SCHEMA_FILES_MULTIPLE_IGNORED.get(schemaPath.getAbsolutePath(), buffer.toString()));
                    break;
            }
        }
        return schema;
    } finally {
        SchemaElement.setAllowEmptyDescription(originalAllowEmptyDescription);
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) File(java.io.File) Nullable(com.unboundid.util.Nullable)

Example 57 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class SchemaValidator method validateSchemaDirectory.

/**
 * Identifies and validates all schema files in the provided directory.
 *
 * @param  schemaDirectory
 *              The directory containing the schema files to examine.  It must
 *              must not be {@code null}, it must exist, and it must be a
 *              directory.
 * @param  errorMessages
 *              A list that will be updated with error messages about any
 *              problems identified during processing.  It must not be
 *              {@code null}, and it must be updatable.
 * @param  existingSchema
 *              The existing schema to use in the course of validating
 *              definitions.  It may be {@code null} if there is no
 *              existing schema and only the definitions read from the
 *              provided path should be used.
 * @param  schemaFilesProcessed
 *              A counter that will be incremented for each schema file that
 *              is processed.
 * @param  nonSchemaFilesIgnored
 *              A list that should be updated with any files that are ignored
 *              because they do not match the configured schema file name
 *              pattern.
 *
 * @return  A {@code Schema} object that contains the definitions that were
 *          loaded.  If an existing schema was already available, the schema
 *          that is returned will be a merged representation of the existing
 *          schema and the newly loaded schema.  This may be {@code null} if
 *          an error prevented any schema files from being processed and no
 *          existing schema was provided.
 */
@Nullable()
private Schema validateSchemaDirectory(@NotNull final File schemaDirectory, @NotNull final List<String> errorMessages, @Nullable final Schema existingSchema, @NotNull final AtomicInteger schemaFilesProcessed, @NotNull final List<File> nonSchemaFilesIgnored) {
    final TreeMap<String, File> schemaFiles = new TreeMap<>();
    final TreeMap<String, File> subDirectories = new TreeMap<>();
    for (final File f : schemaDirectory.listFiles()) {
        final String name = f.getName();
        if (f.isFile()) {
            schemaFiles.put(name, f);
        } else {
            if (allowSchemaFilesInSubDirectories) {
                subDirectories.put(name, f);
            } else {
                errorMessages.add(ERR_SCHEMA_VALIDATOR_DIR_CONTAINS_SUBDIR.get(schemaDirectory.getAbsolutePath(), name));
            }
        }
    }
    Schema schema = existingSchema;
    for (final File f : schemaFiles.values()) {
        final Schema newSchema = validateSchemaFile(f, errorMessages, schema, schemaFilesProcessed, nonSchemaFilesIgnored);
        if (schema == null) {
            schema = newSchema;
        } else {
            schema = Schema.mergeSchemas(schema, newSchema);
        }
    }
    for (final File f : subDirectories.values()) {
        final Schema newSchema = validateSchemaDirectory(f, errorMessages, schema, schemaFilesProcessed, nonSchemaFilesIgnored);
        if (schema == null) {
            schema = newSchema;
        } else {
            schema = Schema.mergeSchemas(schema, newSchema);
        }
    }
    return schema;
}
Also used : TreeMap(java.util.TreeMap) File(java.io.File) Nullable(com.unboundid.util.Nullable)

Example 58 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class AddAttributeTransformation method transformEntry.

/**
 * {@inheritDoc}
 */
@Override()
@Nullable()
public Entry transformEntry(@NotNull final Entry e) {
    if (e == null) {
        return null;
    }
    // already exists in the entry.  If so, then just return the original entry.
    if (onlyIfMissing) {
        for (final String name : names) {
            if (e.hasAttribute(name)) {
                return e;
            }
        }
    }
    // criteria.  If not, then return the original entry.
    try {
        if (examineScope && (!e.matchesBaseAndScope(baseDN, scope))) {
            return e;
        }
    } catch (final Exception ex) {
        // This should only happen if the entry has a malformed DN.  In that case,
        // we'll assume it isn't within the scope and return the provided entry.
        Debug.debugException(ex);
        return e;
    }
    // return the original entry.
    try {
        if (examineFilter && (!filter.matchesEntry(e, schema))) {
            return e;
        }
    } catch (final Exception ex) {
        // If we can't verify whether the entry matches the filter, then assume
        // it doesn't and return the provided entry.
        Debug.debugException(ex);
        return e;
    }
    // If we've gotten here, then we should add the attribute to the entry.
    final Entry copy = e.duplicate();
    final Attribute existingAttribute = copy.getAttribute(attributeToAdd.getName(), schema);
    if (existingAttribute == null) {
        copy.addAttribute(attributeToAdd);
    } else {
        copy.addAttribute(existingAttribute.getName(), attributeToAdd.getValueByteArrays());
    }
    return copy;
}
Also used : Entry(com.unboundid.ldap.sdk.Entry) Attribute(com.unboundid.ldap.sdk.Attribute) Nullable(com.unboundid.util.Nullable)

Example 59 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class Schema method mergeSchemas.

/**
 * Retrieves a schema containing all of the elements of each of the provided
 * schemas.
 *
 * @param  schemas  The schemas to be merged.  It must not be {@code null} or
 *                  empty.
 *
 * @return  A merged representation of the provided schemas.
 */
@Nullable()
public static Schema mergeSchemas(@NotNull final Schema... schemas) {
    if ((schemas == null) || (schemas.length == 0)) {
        return null;
    } else if (schemas.length == 1) {
        return schemas[0];
    }
    final LinkedHashMap<String, String> asMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(100));
    final LinkedHashMap<String, String> atMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(100));
    final LinkedHashMap<String, String> dcrMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(10));
    final LinkedHashMap<Integer, String> dsrMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(10));
    final LinkedHashMap<String, String> mrMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(100));
    final LinkedHashMap<String, String> mruMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(10));
    final LinkedHashMap<String, String> nfMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(10));
    final LinkedHashMap<String, String> ocMap = new LinkedHashMap<>(StaticUtils.computeMapCapacity(100));
    for (final Schema s : schemas) {
        for (final AttributeSyntaxDefinition as : s.asSet) {
            asMap.put(StaticUtils.toLowerCase(as.getOID()), as.toString());
        }
        for (final AttributeTypeDefinition at : s.atSet) {
            atMap.put(StaticUtils.toLowerCase(at.getOID()), at.toString());
        }
        for (final DITContentRuleDefinition dcr : s.dcrSet) {
            dcrMap.put(StaticUtils.toLowerCase(dcr.getOID()), dcr.toString());
        }
        for (final DITStructureRuleDefinition dsr : s.dsrSet) {
            dsrMap.put(dsr.getRuleID(), dsr.toString());
        }
        for (final MatchingRuleDefinition mr : s.mrSet) {
            mrMap.put(StaticUtils.toLowerCase(mr.getOID()), mr.toString());
        }
        for (final MatchingRuleUseDefinition mru : s.mruSet) {
            mruMap.put(StaticUtils.toLowerCase(mru.getOID()), mru.toString());
        }
        for (final NameFormDefinition nf : s.nfSet) {
            nfMap.put(StaticUtils.toLowerCase(nf.getOID()), nf.toString());
        }
        for (final ObjectClassDefinition oc : s.ocSet) {
            ocMap.put(StaticUtils.toLowerCase(oc.getOID()), oc.toString());
        }
    }
    final Entry e = new Entry(schemas[0].getSchemaEntry().getDN());
    final Attribute ocAttr = schemas[0].getSchemaEntry().getObjectClassAttribute();
    if (ocAttr == null) {
        e.addAttribute("objectClass", "top", "ldapSubEntry", "subschema");
    } else {
        e.addAttribute(ocAttr);
    }
    if (!asMap.isEmpty()) {
        final String[] values = new String[asMap.size()];
        e.addAttribute(ATTR_ATTRIBUTE_SYNTAX, asMap.values().toArray(values));
    }
    if (!mrMap.isEmpty()) {
        final String[] values = new String[mrMap.size()];
        e.addAttribute(ATTR_MATCHING_RULE, mrMap.values().toArray(values));
    }
    if (!atMap.isEmpty()) {
        final String[] values = new String[atMap.size()];
        e.addAttribute(ATTR_ATTRIBUTE_TYPE, atMap.values().toArray(values));
    }
    if (!ocMap.isEmpty()) {
        final String[] values = new String[ocMap.size()];
        e.addAttribute(ATTR_OBJECT_CLASS, ocMap.values().toArray(values));
    }
    if (!dcrMap.isEmpty()) {
        final String[] values = new String[dcrMap.size()];
        e.addAttribute(ATTR_DIT_CONTENT_RULE, dcrMap.values().toArray(values));
    }
    if (!dsrMap.isEmpty()) {
        final String[] values = new String[dsrMap.size()];
        e.addAttribute(ATTR_DIT_STRUCTURE_RULE, dsrMap.values().toArray(values));
    }
    if (!nfMap.isEmpty()) {
        final String[] values = new String[nfMap.size()];
        e.addAttribute(ATTR_NAME_FORM, nfMap.values().toArray(values));
    }
    if (!mruMap.isEmpty()) {
        final String[] values = new String[mruMap.size()];
        e.addAttribute(ATTR_MATCHING_RULE_USE, mruMap.values().toArray(values));
    }
    return new Schema(e);
}
Also used : Attribute(com.unboundid.ldap.sdk.Attribute) LinkedHashMap(java.util.LinkedHashMap) Entry(com.unboundid.ldap.sdk.Entry) ReadOnlyEntry(com.unboundid.ldap.sdk.ReadOnlyEntry) Nullable(com.unboundid.util.Nullable)

Example 60 with Nullable

use of com.unboundid.util.Nullable in project ldapsdk by pingidentity.

the class Schema method getSchema.

/**
 * Reads schema information from one or more files containing the schema
 * represented in LDIF form, with the definitions represented in the form
 * described in section 4.1 of RFC 4512.  Each file should contain a single
 * entry.
 *
 * @param  schemaFiles               The paths to the LDIF files containing
 *                                   the schema information to be read.  At
 *                                   least one file must be specified.  If
 *                                   multiple files are specified, then they
 *                                   will be processed in the order in which
 *                                   they have been listed.
 * @param  throwOnUnparsableElement  Indicates whether to throw an exception
 *                                   if the schema entry that is retrieved has
 *                                   one or more unparsable schema elements.
 *
 * @return  The schema read from the specified schema files, or {@code null}
 *          if none of the files contains any LDIF data to be read.
 *
 * @throws  IOException  If a problem occurs while attempting to read from
 *                       any of the specified files.
 *
 * @throws  LDIFException  If a problem occurs while attempting to parse the
 *                         contents of any of the schema files.  If
 *                         {@code throwOnUnparsableElement} is {@code true},
 *                         then this may also be thrown if any of the schema
 *                         files contains any unparsable schema elements.
 */
@Nullable()
public static Schema getSchema(@NotNull final List<File> schemaFiles, final boolean throwOnUnparsableElement) throws IOException, LDIFException {
    Validator.ensureNotNull(schemaFiles);
    Validator.ensureFalse(schemaFiles.isEmpty());
    Entry schemaEntry = null;
    for (final File f : schemaFiles) {
        final LDIFReader ldifReader = new LDIFReader(f);
        try {
            final Entry e = ldifReader.readEntry();
            if (e == null) {
                continue;
            }
            e.addAttribute("objectClass", "top", "ldapSubentry", "subschema");
            if (schemaEntry == null) {
                schemaEntry = e;
            } else {
                for (final Attribute a : e.getAttributes()) {
                    schemaEntry.addAttribute(a);
                }
            }
        } finally {
            ldifReader.close();
        }
    }
    if (schemaEntry == null) {
        return null;
    }
    if (throwOnUnparsableElement) {
        try {
            return parseSchemaEntry(schemaEntry);
        } catch (final LDAPException e) {
            Debug.debugException(e);
            throw new LDIFException(e.getMessage(), 0, false, e);
        }
    } else {
        return new Schema(schemaEntry);
    }
}
Also used : Entry(com.unboundid.ldap.sdk.Entry) ReadOnlyEntry(com.unboundid.ldap.sdk.ReadOnlyEntry) LDAPException(com.unboundid.ldap.sdk.LDAPException) Attribute(com.unboundid.ldap.sdk.Attribute) LDIFReader(com.unboundid.ldif.LDIFReader) LDIFException(com.unboundid.ldif.LDIFException) File(java.io.File) Nullable(com.unboundid.util.Nullable)

Aggregations

Nullable (com.unboundid.util.Nullable)149 ArrayList (java.util.ArrayList)47 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)42 Entry (com.unboundid.ldap.sdk.Entry)30 LDAPException (com.unboundid.ldap.sdk.LDAPException)30 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)21 Attribute (com.unboundid.ldap.sdk.Attribute)21 ASN1Element (com.unboundid.asn1.ASN1Element)20 Filter (com.unboundid.ldap.sdk.Filter)20 SearchResult (com.unboundid.ldap.sdk.SearchResult)18 IOException (java.io.IOException)16 ReadOnlyEntry (com.unboundid.ldap.sdk.ReadOnlyEntry)14 File (java.io.File)14 DN (com.unboundid.ldap.sdk.DN)12 ArgumentException (com.unboundid.util.args.ArgumentException)10 RDN (com.unboundid.ldap.sdk.RDN)9 LDIFException (com.unboundid.ldif.LDIFException)8 ChangeLogEntry (com.unboundid.ldap.sdk.ChangeLogEntry)7 Modification (com.unboundid.ldap.sdk.Modification)7 LDIFModifyChangeRecord (com.unboundid.ldif.LDIFModifyChangeRecord)7