Example usage for javax.naming.directory SchemaViolationException getMessage

List of usage examples for javax.naming.directory SchemaViolationException getMessage

Introduction

In this page you can find the example usage for javax.naming.directory SchemaViolationException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/**
 * Execute a modify request and optionally retry with the empty reference value if adding an empty reference is a
 * schema violation.// w w  w.j a v  a  2  s.co  m
 * 
 * @param modifyRequest the modify request
 * @param modifyResponse the modify response
 * @param retry whether or not to retry with the empty reference value if adding an empty reference is a schema
 *            violation
 */
public void execute(ModifyRequest modifyRequest, ModifyResponse modifyResponse, boolean retry) {

    Ldap ldap = null;
    try {
        String dn = modifyRequest.getPsoID().getID();

        List<AlternateIdentifier> alternateIdentifiers = new ArrayList<AlternateIdentifier>();
        List<ModificationItem> modificationItems = new ArrayList<ModificationItem>();
        for (Modification modification : modifyRequest.getModifications()) {
            modificationItems.addAll(getDsmlMods(modification));
            modificationItems.addAll(getReferenceMods(modification));
            alternateIdentifiers.addAll(PSPUtil.getAlternateIdentifiers(modification));
        }

        if (alternateIdentifiers.size() == 1) {
            AlternateIdentifier alternateIdentifier = alternateIdentifiers.get(0);
            if (!alternateIdentifier.getTargetID().equals(getId())) {
                fail(modifyResponse, ErrorCode.CUSTOM_ERROR,
                        "Unable to rename object with a different target ID.");
                return;
            }
        }

        ldap = ldapPool.checkOut();

        PSOIdentifier responseLookupPsoID = modifyRequest.getPsoID();

        // rename
        if (alternateIdentifiers.size() == 1) {
            String oldDn = LdapSpmlTarget.escapeForwardSlash(dn);
            String newDn = LdapSpmlTarget.escapeForwardSlash(alternateIdentifiers.get(0).getID());
            LOG.info("Target '{}' - Renaming '{}' to '{}'", new Object[] { getId(), oldDn, newDn });
            ldap.rename(oldDn, newDn);
            dn = newDn;
            responseLookupPsoID = alternateIdentifiers.get(0).getPSOIdentifier();
        }

        // modify
        LOG.debug("Target '{}' - Modifying '{}'", getId(), PSPUtil.toString(modifyRequest));
        LOG.debug("Target '{}' - Modifications '{}'", getId(), modificationItems);
        String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn);
        LOG.debug("Target '{}' - Modify DN '{}'", getId(), escapedDn);
        ldap.modifyAttributes(escapedDn, modificationItems.toArray(new ModificationItem[] {}));
        LOG.debug("Target '{}' - Modified '{}'", getId(), PSPUtil.toString(modifyRequest));

        // response PSO
        if (modifyRequest.getReturnData().equals(ReturnData.IDENTIFIER)) {
            PSO responsePSO = new PSO();
            responsePSO.setPsoID(responseLookupPsoID);
            // TODO entityName attribute ?
            modifyResponse.setPso(responsePSO);
        } else {
            LookupRequest lookupRequest = new LookupRequest();
            lookupRequest.setPsoID(responseLookupPsoID);
            lookupRequest.setReturnData(modifyRequest.getReturnData());

            LookupResponse lookupResponse = this.execute(lookupRequest);
            if (lookupResponse.getStatus() == StatusCode.SUCCESS) {
                modifyResponse.setPso(lookupResponse.getPso());
            } else {
                fail(modifyResponse, lookupResponse.getError());
            }
        }
    } catch (SchemaViolationException e) {

        // optionally retry after adding an empty reference if this is an openldap schema violation
        if (retry) {
            LOG.error("Target '{}' - A schema violation occurred {}", getId(), e);
            if (GROUP_OF_NAMES_ERROR.equals(e.getMessage())
                    || GROUP_OF_UNIQUE_NAMES_ERROR.equals(e.getMessage())) {
                ModifyRequest emptyReference = null;
                try {
                    emptyReference = handleEmptyReferences(modifyRequest);
                } catch (PspException e1) {
                    fail(modifyResponse, ErrorCode.CUSTOM_ERROR, e1);
                    return;
                }
                if (emptyReference != null) {
                    LOG.info("Target '{}' - Retrying modify request", getId(),
                            PSPUtil.toString(emptyReference));
                    execute(emptyReference, modifyResponse, false);
                }
            } else {
                //send a failure up the chain due to objectClass violation we haven't trapped yet GRP-821
                fail(modifyResponse, ErrorCode.CUSTOM_ERROR, e);
                return;
            }
        } else {
            // return the failure response
            fail(modifyResponse, ErrorCode.CUSTOM_ERROR, e);
            return;
        }

    } catch (LdapPoolException e) {
        fail(modifyResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (NamingException e) {
        fail(modifyResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        fail(modifyResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        ldapPool.checkIn(ldap);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Store new links using the LDAP staticAttributeId strategy.
 *
 * @see org.nuxeo.ecm.directory.Reference#addLinks(String, List)
 *//*  w  ww  .  j  av  a2  s.  c om*/
@Override
public void addLinks(String sourceId, List<String> targetIds) throws DirectoryException {

    if (targetIds.isEmpty()) {
        // optim: nothing to do, return silently without further creating
        // session instances
        return;
    }

    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    if (attributeId == null) {
        if (log.isTraceEnabled()) {
            log.trace(String.format("trying to edit a non-static reference from %s in directory %s: ignoring",
                    sourceId, ldapSourceDirectory.getName()));
        }
        return;
    }
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        // fetch the entry to be able to run the security policy
        // implemented in an entry adaptor
        DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false);
        if (sourceEntry == null) {
            throw new DirectoryException(String.format("could not add links from unexisting %s in directory %s",
                    sourceId, ldapSourceDirectory.getName()));
        }
        if (!BaseSession.isReadOnlyEntry(sourceEntry)) {
            SearchResult ldapEntry = sourceSession.getLdapEntry(sourceId);

            String sourceDn = ldapEntry.getNameInNamespace();
            Attribute storedAttr = ldapEntry.getAttributes().get(attributeId);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attribute attrToAdd = new BasicAttribute(attributeId);
            for (String targetId : targetIds) {
                if (staticAttributeIdIsDn) {
                    // TODO optim: avoid LDAP search request when targetDn
                    // can be forged client side (rdnAttribute = idAttribute and scope is onelevel)
                    ldapEntry = targetSession.getLdapEntry(targetId);
                    if (ldapEntry == null) {
                        log.warn(String.format(
                                "entry '%s' in directory '%s' not found: could not add link from '%s' in directory '%s' for '%s'",
                                targetId, ldapTargetDirectory.getName(), sourceId,
                                ldapSourceDirectory.getName(), this));
                        continue;
                    }
                    String dn = ldapEntry.getNameInNamespace();
                    if (storedAttr == null || !storedAttr.contains(dn)) {
                        attrToAdd.add(dn);
                    }
                } else {
                    if (storedAttr == null || !storedAttr.contains(targetId)) {
                        attrToAdd.add(targetId);
                    }
                }
            }
            if (attrToAdd.size() > 0) {
                try {
                    // do the LDAP request to store missing dns
                    Attributes attrsToAdd = new BasicAttributes();
                    attrsToAdd.put(attrToAdd);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s' "
                                        + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                sourceId, StringUtils.join(targetIds, ", "), sourceDn, attrsToAdd, this));
                    }
                    sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrsToAdd);

                    // robustly clean any existing empty marker now that we are sure that the list in not empty
                    if (storedAttr.contains(emptyRefMarker)) {
                        Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker);

                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.addLinks(%s, [%s]): LDAP modifyAttributes dn='%s'"
                                            + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    sourceId, StringUtils.join(targetIds, ", "), sourceDn, cleanAttrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE,
                                cleanAttrs);
                    }
                } catch (SchemaViolationException e) {
                    if (isDynamic()) {
                        // we are editing an entry that has no static part
                        log.warn(String.format("cannot update dynamic reference in field %s for source %s",
                                getFieldName(), sourceId));
                    } else {
                        // this is a real schema configuration problem,
                        // wrap up the exception
                        throw new DirectoryException(e);
                    }
                }
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("addLinks failed: " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Store new links using the LDAP staticAttributeId strategy.
 *
 * @see org.nuxeo.ecm.directory.Reference#addLinks(List, String)
 *//*from  www.ja  v  a 2  s .  c o m*/
@Override
public void addLinks(List<String> sourceIds, String targetId) throws DirectoryException {
    String attributeId = getStaticAttributeId();
    if (attributeId == null && !sourceIds.isEmpty()) {
        log.warn("trying to edit a non-static reference: ignoring");
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();

    String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // compute the target dn to add to all the matching source
            // entries
            SearchResult ldapEntry = targetSession.getLdapEntry(targetId);
            if (ldapEntry == null) {
                throw new DirectoryException(
                        String.format("could not add links to unexisting %s in directory %s", targetId,
                                ldapTargetDirectory.getName()));
            }
            String targetAttributeValue;
            if (staticAttributeIdIsDn) {
                targetAttributeValue = ldapEntry.getNameInNamespace();
            } else {
                targetAttributeValue = targetId;
            }

            for (String sourceId : sourceIds) {
                // fetch the entry to be able to run the security policy
                // implemented in an entry adaptor
                DocumentModel sourceEntry = sourceSession.getEntry(sourceId, false);
                if (sourceEntry == null) {
                    log.warn(String.format(
                            "entry %s in directory %s not found: could not add link to %s in directory %s",
                            sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName()));
                    continue;
                }
                if (BaseSession.isReadOnlyEntry(sourceEntry)) {
                    // skip this entry since it cannot be edited to add the
                    // reference to targetId
                    log.warn(String.format(
                            "entry %s in directory %s is readonly: could not add link to %s in directory %s",
                            sourceId, ldapSourceDirectory.getName(), targetId, ldapTargetDirectory.getName()));
                    continue;
                }
                ldapEntry = sourceSession.getLdapEntry(sourceId);
                String sourceDn = ldapEntry.getNameInNamespace();
                Attribute storedAttr = ldapEntry.getAttributes().get(attributeId);
                if (storedAttr.contains(targetAttributeValue)) {
                    // no need to readd
                    continue;
                }
                try {
                    // add the new dn
                    Attributes attrs = new BasicAttributes(attributeId, targetAttributeValue);

                    if (log.isDebugEnabled()) {
                        log.debug(String.format(
                                "LDAPReference.addLinks([%s], %s): LDAP modifyAttributes dn='%s'"
                                        + " mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                StringUtils.join(sourceIds, ", "), targetId, sourceDn, attrs, this));
                    }
                    sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.ADD_ATTRIBUTE, attrs);

                    // robustly clean any existing empty marker now that we
                    // are sure that the list in not empty
                    if (storedAttr.contains(emptyRefMarker)) {
                        Attributes cleanAttrs = new BasicAttributes(attributeId, emptyRefMarker);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.addLinks(%s, %s): LDAP modifyAttributes dn='%s'"
                                            + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    StringUtils.join(sourceIds, ", "), targetId, sourceDn,
                                    cleanAttrs.toString(), this));
                        }
                        sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE,
                                cleanAttrs);
                    }
                } catch (SchemaViolationException e) {
                    if (isDynamic()) {
                        // we are editing an entry that has no static part
                        log.warn(String.format("cannot add dynamic reference in field %s for target %s",
                                getFieldName(), targetId));
                    } else {
                        // this is a real schema configuration problem,
                        // wrap the exception
                        throw new DirectoryException(e);
                    }
                }
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("addLinks failed: " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Remove existing statically defined links for the given source id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForSource(String)
 *///from   w ww . ja  v a  2 s . c om
@Override
public void removeLinksForSource(String sourceId) throws DirectoryException {
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession();
            LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
        if (sourceSession.isReadOnly() || attributeId == null) {
            // do not try to do anything on a read only server or to a
            // purely dynamic reference
            return;
        }
        // get the dn of the entry that matches sourceId
        SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId);
        if (sourceLdapEntry == null) {
            throw new DirectoryException(
                    String.format("cannot edit the links hold by missing entry '%s' in directory '%s'",
                            sourceId, ldapSourceDirectory.getName()));
        }
        String sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace());

        Attribute oldAttr = sourceLdapEntry.getAttributes().get(attributeId);
        if (oldAttr == null) {
            // consider it as an empty attribute to simplify the following
            // code
            oldAttr = new BasicAttribute(attributeId);
        }
        Attribute attrToRemove = new BasicAttribute(attributeId);

        NamingEnumeration<?> oldAttrs = oldAttr.getAll();
        String targetBaseDn = pseudoNormalizeDn(ldapTargetDirectory.getDescriptor().getSearchBaseDn());
        try {
            while (oldAttrs.hasMore()) {
                String targetKeyAttr = oldAttrs.next().toString();

                if (staticAttributeIdIsDn) {
                    String dn = pseudoNormalizeDn(targetKeyAttr);
                    if (forceDnConsistencyCheck) {
                        String id = getIdForDn(targetSession, dn);
                        if (id != null && targetSession.hasEntry(id)) {
                            // this is an entry managed by the current
                            // reference
                            attrToRemove.add(dn);
                        }
                    } else if (dn.endsWith(targetBaseDn)) {
                        // this is an entry managed by the current
                        // reference
                        attrToRemove.add(dn);
                    }
                } else {
                    attrToRemove.add(targetKeyAttr);
                }
            }
        } finally {
            oldAttrs.close();
        }
        try {
            if (attrToRemove.size() == oldAttr.size()) {
                // use the empty ref marker to avoid empty attr
                String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
                Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes key='%s' "
                                    + " mod_op='REPLACE_ATTRIBUTE' attrs='%s' [%s]",
                            sourceId, sourceDn, emptyAttribute, this));
                }
                sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REPLACE_ATTRIBUTE,
                        emptyAttribute);
            } else if (attrToRemove.size() > 0) {
                // remove the attribute managed by the current reference
                Attributes attrsToRemove = new BasicAttributes();
                attrsToRemove.put(attrToRemove);
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes dn='%s' "
                                    + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                            sourceId, sourceDn, attrsToRemove, this));
                }
                sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, attrsToRemove);
            }
        } catch (SchemaViolationException e) {
            if (isDynamic()) {
                // we are editing an entry that has no static part
                log.warn(String.format("cannot remove dynamic reference in field %s for source %s",
                        getFieldName(), sourceId));
            } else {
                // this is a real schma configuration problem, wrapup the
                // exception
                throw new DirectoryException(e);
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForSource failed: " + e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java

/**
 * Remove existing statically defined links for the given target id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String)
 *//*from   www.  j  av a 2s  .c o m*/
@Override
public void removeLinksForTarget(String targetId) throws DirectoryException {
    if (!isStatic()) {
        // nothing to do: dynamic references cannot be updated
        return;
    }
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();
            LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) {
        if (!sourceSession.isReadOnly()) {
            // get the dn of the target that matches targetId
            String targetAttributeValue;

            if (staticAttributeIdIsDn) {
                SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId);
                if (targetLdapEntry == null) {
                    String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute();
                    if (!rdnAttribute.equals(targetSession.idAttribute)) {
                        log.warn(String.format(
                                "cannot remove links to missing entry %s in directory %s for reference %s",
                                targetId, ldapTargetDirectory.getName(), this));
                        return;
                    }
                    // the entry might have already been deleted, try to
                    // re-forge it if possible (might not work if scope is
                    // subtree)
                    targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId,
                            ldapTargetDirectory.getDescriptor().getSearchBaseDn());
                } else {
                    targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace());
                }
            } else {
                targetAttributeValue = targetId;
            }

            // build a LDAP query to find entries that point to the target
            String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue);
            String sourceFilter = ldapSourceDirectory.getBaseFilter();

            if (sourceFilter != null && !"".equals(sourceFilter)) {
                searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter);
            }

            SearchControls scts = new SearchControls();
            scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope());
            scts.setReturningAttributes(new String[] { attributeId });

            // find all source entries that point to the target key and
            // clean
            // those references
            if (log.isDebugEnabled()) {
                log.debug(String.format(
                        "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' "
                                + " filter='%s' scope='%s' [%s]",
                        targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this));
            }
            NamingEnumeration<SearchResult> results = sourceSession.dirContext
                    .search(sourceSession.searchBaseDn, searchFilter, scts);
            String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
            Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);

            try {
                while (results.hasMore()) {
                    SearchResult result = results.next();
                    Attributes attrs = result.getAttributes();
                    Attribute attr = attrs.get(attributeId);
                    try {
                        if (attr.size() == 1) {
                            // the attribute holds the last reference, put
                            // the
                            // empty ref. marker before removing the
                            // attribute
                            // since empty attribute are often not allowed
                            // by
                            // the server schema
                            if (log.isDebugEnabled()) {
                                log.debug(String.format(
                                        "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                                + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]",
                                        targetId, result.getNameInNamespace(), attrs, this));
                            }
                            sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                    DirContext.ADD_ATTRIBUTE, emptyAttribute);
                        }
                        // remove the reference to the target key
                        attrs = new BasicAttributes();
                        attr = new BasicAttribute(attributeId);
                        attr.add(targetAttributeValue);
                        attrs.put(attr);
                        if (log.isDebugEnabled()) {
                            log.debug(String.format(
                                    "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' "
                                            + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                                    targetId, result.getNameInNamespace(), attrs, this));
                        }
                        sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(),
                                DirContext.REMOVE_ATTRIBUTE, attrs);
                    } catch (SchemaViolationException e) {
                        if (isDynamic()) {
                            // we are editing an entry that has no static
                            // part
                            log.warn(String.format("cannot remove dynamic reference in field %s for target %s",
                                    getFieldName(), targetId));
                        } else {
                            // this is a real schema configuration problem,
                            // wrapup the exception
                            throw new DirectoryException(e);
                        }
                    }
                }
            } finally {
                results.close();
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e);
    }
}