Example usage for javax.naming.directory DirContext REMOVE_ATTRIBUTE

List of usage examples for javax.naming.directory DirContext REMOVE_ATTRIBUTE

Introduction

In this page you can find the example usage for javax.naming.directory DirContext REMOVE_ATTRIBUTE.

Prototype

int REMOVE_ATTRIBUTE

To view the source code for javax.naming.directory DirContext REMOVE_ATTRIBUTE.

Click Source Link

Document

This constant specifies to delete the specified attribute values from the attribute.

Usage

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

/**
 * Converts spml modifications to jndi modifications.
 * //  w  w w. j  a  va  2  s.co  m
 * @param modification the spml modification
 * @return the jndi modifications
 * @throws PspException if a psp error occurs
 */
protected List<ModificationItem> getReferenceMods(Modification modification) throws PspException {
    List<ModificationItem> mods = new ArrayList<ModificationItem>();

    Map<String, List<Reference>> references = PSPUtil.getReferences(modification.getCapabilityData());

    if (references.isEmpty()) {
        return mods;
    }

    for (String typeOfReference : references.keySet()) {

        List<String> ids = new ArrayList<String>();
        for (Reference reference : references.get(typeOfReference)) {
            if (reference.getToPsoID().getTargetID().equals(getId())) {
                String id = reference.getToPsoID().getID();
                // fake empty string since the spml toolkit ignores an empty string psoID
                // if (id.equals(PSOReferencesDefinition.EMPTY_STRING)) {
                // id = "";
                // }
                if (id == null) {
                    id = "";
                }
                ids.add(id);
            }
        }

        Attribute attribute = new BasicAttribute(typeOfReference);
        for (String id : ids) {
            attribute.add(id);
        }

        int op = -1;
        if (modification.getModificationMode().equals(ModificationMode.ADD)) {
            op = DirContext.ADD_ATTRIBUTE;
        } else if (modification.getModificationMode().equals(ModificationMode.DELETE)) {
            op = DirContext.REMOVE_ATTRIBUTE;
        } else if (modification.getModificationMode().equals(ModificationMode.REPLACE)) {
            op = DirContext.REPLACE_ATTRIBUTE;
        } else {
            throw new PspException("Unknown modification operation : " + modification.getModificationMode());
        }

        mods.add(new ModificationItem(op, attribute));
    }

    return mods;
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationDelete(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        String result = null;//from   ww w . j ava2  s . com
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Delete attribute: " + a.getID());
            NamingEnumeration values;
            try {
                values = a.getAll();
            } catch (NamingException e1) {
                storeLdapException(e1, prc);
                throw new SenderException("cannot obtain values of Attribute [" + a.getID() + "]", e1);
            }
            while (values.hasMoreElements()) {
                Attributes partialAttrs = new BasicAttributes();
                Attribute singleValuedAttribute;
                String id = a.getID();
                Object value = values.nextElement();
                if (log.isDebugEnabled()) {
                    if (id.toLowerCase().contains("password") || id.toLowerCase().contains("pwd")) {
                        log.debug("Delete value: ***");
                    } else {
                        log.debug("Delete value: " + value);
                    }
                }
                if (unicodePwd && "unicodePwd".equalsIgnoreCase(id)) {
                    singleValuedAttribute = new BasicAttribute(id, encodeUnicodePwd(value));
                } else {
                    singleValuedAttribute = new BasicAttribute(id, value);
                }
                partialAttrs.put(singleValuedAttribute);
                DirContext dirContext = null;
                try {
                    dirContext = getDirContext(paramValueMap);
                    dirContext.modifyAttributes(entryName, DirContext.REMOVE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
                    //   16 LDAP_NO_SUCH_ATTRIBUTE Indicates that the attribute specified in the modify or compare operation does not exist in the entry.
                    //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
                    // Sun:
                    //   [LDAP: error code 16 - No Such Attribute...
                    //   [LDAP: error code 32 - No Such Object...
                    // AD:
                    //   [LDAP: error code 16 - 00002085: AtrErr: DSID-03151F03, #1...
                    if (e.getMessage().startsWith("[LDAP: error code 16 - ")
                            || e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                        if (log.isDebugEnabled())
                            log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                        result = DEFAULT_RESULT_DELETE;
                    } else {
                        storeLdapException(e, prc);
                        throw new SenderException(
                                "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]",
                                e);
                    }
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        if (result != null) {
            return result;
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            dirContext.unbind(entryName);
            return DEFAULT_RESULT;
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   32 LDAP_NO_SUCH_OBJECT Indicates the target object cannot be found. This code is not returned on following operations: Search operations that find the search base but cannot find any entries that match the search filter. Bind operations. 
            // Sun:
            //   [LDAP: error code 32 - No Such Object...
            if (e.getMessage().startsWith("[LDAP: error code 32 - ")) {
                if (log.isDebugEnabled())
                    log.debug("Operation [" + getOperation() + "] successful: " + e.getMessage());
                return DEFAULT_RESULT_DELETE;
            } else {
                storeLdapException(e, prc);
                throw new SenderException(
                        "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
            }
        } finally {
            closeDirContext(dirContext);
        }
    }
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationChangeUnicodePwd(String entryName, ParameterResolutionContext prc,
        Map paramValueMap) throws SenderException, ParameterException {
    ModificationItem[] modificationItems = new ModificationItem[2];
    modificationItems[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
            new BasicAttribute("unicodePwd", encodeUnicodePwd((String) paramValueMap.get("oldPassword"))));
    modificationItems[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
            new BasicAttribute("unicodePwd", encodeUnicodePwd((String) paramValueMap.get("newPassword"))));
    DirContext dirContext = null;
    try {//from   w w w.j  a  va2s  . c o m
        dirContext = getDirContext(paramValueMap);
        dirContext.modifyAttributes(entryName, modificationItems);
        return DEFAULT_RESULT_CHANGE_UNICODE_PWD_OK;
    } catch (NamingException e) {
        // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
        //   19 LDAP_CONSTRAINT_VIOLATION Indicates that the attribute value specified in a modify, add, or modify DN operation violates constraints placed on the attribute. The constraint can be one of size or content (string only, no binary).
        // AD:
        //   [LDAP: error code 19 - 0000052D: AtrErr: DSID-03191041, #1...
        if (e.getMessage().startsWith("[LDAP: error code 19 - ")) {
            if (log.isDebugEnabled())
                log.debug("Operation [" + getOperation()
                        + "] old password doesn't match or new password doesn't comply with policy for: "
                        + entryName);
            return DEFAULT_RESULT_CHANGE_UNICODE_PWD_NOK;
        } else {
            storeLdapException(e, prc);
            throw new SenderException(
                    "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}

From source file:org.apache.directory.studio.connection.core.io.api.DirectoryApiConnectionWrapper.java

/**
 * Converts a modification operation.//from  w  w w  .  j a  v  a 2 s.  c  o m
 *
 * @param modificationOp
 *      a modification operation
 * @return
 *      the converted modification operation
 */
private ModificationOperation convertModificationOperation(int modificationOp) {
    if (modificationOp == DirContext.ADD_ATTRIBUTE) {
        return ModificationOperation.ADD_ATTRIBUTE;
    } else if (modificationOp == DirContext.REPLACE_ATTRIBUTE) {
        return ModificationOperation.REPLACE_ATTRIBUTE;
    } else if (modificationOp == DirContext.REMOVE_ATTRIBUTE) {
        return ModificationOperation.REMOVE_ATTRIBUTE;
    }

    return null;
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportDsmlRunnable.java

/**
 * Converts the modification operation from Shared LDAP to JNDI
 *
 * @param operation/* w  w w .j  av  a  2s.c  o  m*/
 *      the Shared LDAP modification operation
 * @return
 *      the equivalent modification operation in JNDI
 */
private int convertModificationOperation(ModificationOperation operation) {
    switch (operation) {
    case ADD_ATTRIBUTE:
        return DirContext.ADD_ATTRIBUTE;
    case REMOVE_ATTRIBUTE:
        return DirContext.REMOVE_ATTRIBUTE;
    case REPLACE_ATTRIBUTE:
        return DirContext.REPLACE_ATTRIBUTE;
    default:
        return 0;
    }
}

From source file:org.apache.directory.studio.ldapbrowser.core.jobs.ImportLdifRunnable.java

/**
 * Imports the LDIF record./*www.  jav  a  2s  .  co  m*/
 * 
 * @param browserConnection the browser connection
 * @param record the LDIF record
 * @param updateIfEntryExists the update if entry exists flag
 * @param monitor the progress monitor
 * 
 * @throws NamingException the naming exception
 * @throws LdapInvalidDnException
 */
static void importLdifRecord(IBrowserConnection browserConnection, LdifRecord record,
        boolean updateIfEntryExists, StudioProgressMonitor monitor)
        throws NamingException, LdapInvalidDnException {
    if (!record.isValid()) {
        throw new NamingException(
                BrowserCoreMessages.bind(BrowserCoreMessages.model__invalid_record, record.getInvalidString()));
    }

    String dn = record.getDnLine().getValueAsString();

    if (record instanceof LdifContentRecord || record instanceof LdifChangeAddRecord) {
        LdifAttrValLine[] attrVals;
        IEntry dummyEntry;
        if (record instanceof LdifContentRecord) {
            LdifContentRecord attrValRecord = (LdifContentRecord) record;
            attrVals = attrValRecord.getAttrVals();
            try {
                dummyEntry = ModelConverter.ldifContentRecordToEntry(attrValRecord, browserConnection);
            } catch (LdapInvalidDnException e) {
                monitor.reportError(e);
                return;
            }
        } else {
            LdifChangeAddRecord changeAddRecord = (LdifChangeAddRecord) record;
            attrVals = changeAddRecord.getAttrVals();
            try {
                dummyEntry = ModelConverter.ldifChangeAddRecordToEntry(changeAddRecord, browserConnection);
            } catch (LdapInvalidDnException e) {
                monitor.reportError(e);
                return;
            }
        }

        Attributes jndiAttributes = new BasicAttributes();
        for (LdifAttrValLine attrVal : attrVals) {
            String attributeName = attrVal.getUnfoldedAttributeDescription();
            Object realValue = attrVal.getValueAsObject();

            if (jndiAttributes.get(attributeName) != null) {
                jndiAttributes.get(attributeName).add(realValue);
            } else {
                jndiAttributes.put(attributeName, realValue);
            }
        }

        browserConnection.getConnection().getConnectionWrapper().createEntry(dn, jndiAttributes,
                getControls(record), monitor, null);

        if (monitor.errorsReported() && updateIfEntryExists
                && monitor.getException() instanceof NameAlreadyBoundException) {
            // creation failed with Error 68, now try to update the existing entry
            monitor.reset();

            ModificationItem[] mis = ModelConverter.entryToReplaceModificationItems(dummyEntry);
            browserConnection.getConnection().getConnectionWrapper().modifyEntry(dn, mis, getControls(record),
                    monitor, null);
        }
    } else if (record instanceof LdifChangeDeleteRecord) {
        LdifChangeDeleteRecord changeDeleteRecord = (LdifChangeDeleteRecord) record;
        browserConnection.getConnection().getConnectionWrapper().deleteEntry(dn,
                getControls(changeDeleteRecord), monitor, null);
    } else if (record instanceof LdifChangeModifyRecord) {
        LdifChangeModifyRecord modifyRecord = (LdifChangeModifyRecord) record;
        LdifModSpec[] modSpecs = modifyRecord.getModSpecs();
        ModificationItem[] mis = new ModificationItem[modSpecs.length];
        for (int ii = 0; ii < modSpecs.length; ii++) {
            LdifModSpecTypeLine modSpecType = modSpecs[ii].getModSpecType();
            LdifAttrValLine[] attrVals = modSpecs[ii].getAttrVals();

            Attribute attribute = new BasicAttribute(modSpecType.getUnfoldedAttributeDescription());
            for (int x = 0; x < attrVals.length; x++) {
                attribute.add(attrVals[x].getValueAsObject());
            }

            if (modSpecType.isAdd()) {
                mis[ii] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attribute);
            } else if (modSpecType.isDelete()) {
                mis[ii] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute);
            } else if (modSpecType.isReplace()) {
                mis[ii] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attribute);
            }
        }

        browserConnection.getConnection().getConnectionWrapper().modifyEntry(dn, mis, getControls(modifyRecord),
                monitor, null);
    } else if (record instanceof LdifChangeModDnRecord) {
        LdifChangeModDnRecord modDnRecord = (LdifChangeModDnRecord) record;
        if (modDnRecord.getNewrdnLine() != null && modDnRecord.getDeloldrdnLine() != null) {
            String newRdn = modDnRecord.getNewrdnLine().getValueAsString();
            boolean deleteOldRdn = modDnRecord.getDeloldrdnLine().isDeleteOldRdn();

            Dn newDn;
            if (modDnRecord.getNewsuperiorLine() != null) {
                newDn = new Dn(newRdn, modDnRecord.getNewsuperiorLine().getValueAsString());
            } else {
                Dn dnObject = new Dn(dn);
                Dn parent = dnObject.getParent();
                newDn = new Dn(newRdn, parent.getName());
            }

            browserConnection.getConnection().getConnectionWrapper().renameEntry(dn, newDn.toString(),
                    deleteOldRdn, getControls(modDnRecord), monitor, null);
        }
    }
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

/***************************************************************************
 * Collect all the value from the table (Arguments), using this create the
 * basicAttributes This will create the Basic Attributes for the User
 * defined TestCase for Modify test//ww  w.  j  a v  a2 s .c  o m
 *
 * @return The BasicAttributes
 **************************************************************************/
private ModificationItem[] getUserModAttributes() {
    ModificationItem[] mods = new ModificationItem[getLDAPArguments().getArguments().size()];
    BasicAttribute attr;
    PropertyIterator iter = getLDAPArguments().iterator();
    int count = 0;
    while (iter.hasNext()) {
        LDAPArgument item = (LDAPArgument) iter.next().getObjectValue();
        if ((item.getValue()).length() == 0) {
            attr = new BasicAttribute(item.getName());
        } else {
            attr = getBasicAttribute(item.getName(), item.getValue());
        }

        final String opcode = item.getOpcode();
        if ("add".equals(opcode)) { // $NON-NLS-1$
            mods[count++] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr);
        } else if ("delete".equals(opcode) // $NON-NLS-1$
                || "remove".equals(opcode)) { // $NON-NLS-1$
            mods[count++] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attr);
        } else if ("replace".equals(opcode)) { // $NON-NLS-1$
            mods[count++] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);
        } else {
            log.warn("Invalid opCode: " + opcode);
        }
    }
    return mods;
}

From source file:org.easy.ldap.LdapDao.java

/**
 * @param rootDn/*from  w  w w  . j a v a 2 s  .  c  o m*/
 * @param type
 * @param rdnValue
 */
public void removeRdn(LdapName rootDn, RdnType type, String rdnValue) {
    DirContext ctx = null;

    try {
        ctx = contextFactory.createContext(rootDn.toString());

        ModificationItem[] modifications = new ModificationItem[1];

        Attribute attribute = new BasicAttribute(type.toString(), rdnValue);

        modifications[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attribute);

        ctx.modifyAttributes("", modifications);

    }

    catch (NamingException e) {
        throw new RuntimeException(type.toString() + "=" + rdnValue + "," + rootDn.toString(), e);
    }

    finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.debug(e);
            }
        }
    }

}

From source file:org.fao.geonet.kernel.security.ldap.LdapUserDetailsManager.java

protected void removeAuthorities(DistinguishedName userDn, Collection<? extends GrantedAuthority> authorities) {
    modifyAuthorities(userDn, authorities, DirContext.REMOVE_ATTRIBUTE);
}

From source file:org.ligoj.app.plugin.id.ldap.dao.GroupLdapRepository.java

/**
 * Update the uniqueMember attribute of the user having changed DN. Cache is not updated since.
 *
 * @param oldUniqueMemberDn//w w w  . j a  v a  2  s .  c  o  m
 *            Old DN of the member to update.
 * @param newUniqueMemberDn
 *            New DN of the member to update. UID of the DN should unchanged.
 * @param group
 *            CN of the group to update.
 */
public void updateMemberDn(final String group, final String oldUniqueMemberDn, final String newUniqueMemberDn) {
    final GroupOrg groupLdap = findById(group);
    final ModificationItem[] mods = new ModificationItem[2];
    mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE,
            new BasicAttribute(UNIQUE_MEMBER, oldUniqueMemberDn));
    mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
            new BasicAttribute(UNIQUE_MEMBER, newUniqueMemberDn));
    template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(groupLdap.getDn()), mods);
}