Example usage for javax.naming.directory DirContext REPLACE_ATTRIBUTE

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

Introduction

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

Prototype

int REPLACE_ATTRIBUTE

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

Click Source Link

Document

This constant specifies to replace an attribute with specified values.

Usage

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

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

    for (Object object : modification.getOpenContentElements(DSMLModification.class)) {
        DSMLModification dsmlModification = (DSMLModification) object;

        Attribute attribute = new BasicAttribute(dsmlModification.getName());

        DSMLValue[] dsmlValues = dsmlModification.getValues();
        for (DSMLValue dsmlValue : dsmlValues) {
            // for example, when <dsmlValue><dsmlValue/> and op is a replace
            if (!DatatypeHelper.isEmpty(dsmlValue.getValue())) {
                attribute.add(dsmlValue.getValue());
            }
        }

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

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

    return mods;
}

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

/**
 * Converts spml modifications to jndi modifications.
 * // w w  w .  j  a  v  a 2s . c o  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 performOperationUpdate(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        Attributes attrs) throws SenderException, ParameterException {
    String entryNameAfter = entryName;
    if (paramValueMap != null) {
        String newEntryName = (String) paramValueMap.get("newEntryName");
        if (newEntryName != null && StringUtils.isNotEmpty(newEntryName)) {
            if (log.isDebugEnabled())
                log.debug("newEntryName=[" + newEntryName + "]");
            DirContext dirContext = null;
            try {
                dirContext = getDirContext(paramValueMap);
                dirContext.rename(entryName, newEntryName);
                entryNameAfter = newEntryName;
            } catch (NamingException e) {
                String msg;/* w ww  .  j  ava 2 s .c om*/
                // 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 - ")) {
                    msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryName + "]";
                } else {
                    msg = "Exception in operation [" + getOperation() + "] entryName [" + entryName + "]";
                }
                storeLdapException(e, prc);
                throw new SenderException(msg, e);
            } finally {
                closeDirContext(dirContext);
            }
        }
    }

    if (manipulationSubject.equals(MANIPULATION_ATTRIBUTE)) {
        NamingEnumeration na = attrs.getAll();
        while (na.hasMoreElements()) {
            Attribute a = (Attribute) na.nextElement();
            log.debug("Update 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("Update value: ***");
                    } else {
                        log.debug("Update 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(entryNameAfter, DirContext.REPLACE_ATTRIBUTE, partialAttrs);
                } catch (NamingException e) {
                    String msg;
                    // 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 - ")) {
                        msg = "Operation [" + getOperation() + "] failed - wrong entryName [" + entryNameAfter
                                + "]";
                    } else {
                        msg = "Exception in operation [" + getOperation() + "] entryName [" + entryNameAfter
                                + "]";
                    }
                    //result = DEFAULT_RESULT_UPDATE_NOK;
                    storeLdapException(e, prc);
                    throw new SenderException(msg, e);
                } finally {
                    closeDirContext(dirContext);
                }
            }
        }
        return DEFAULT_RESULT;
    } else {
        DirContext dirContext = null;
        try {
            dirContext = getDirContext(paramValueMap);
            //dirContext.rename(newEntryName, oldEntryName);
            //result = DEFAULT_RESULT;
            dirContext.rename(entryName, entryName);
            return "<LdapResult>Deze functionaliteit is nog niet beschikbaar - naam niet veranderd.</LdapResult>";
        } catch (NamingException e) {
            // https://wiki.servicenow.com/index.php?title=LDAP_Error_Codes:
            //   68 LDAP_ALREADY_EXISTS Indicates that the add operation attempted to add an entry that already exists, or that the modify operation attempted to rename an entry to the name of an entry that already exists.
            // Sun:
            //   [LDAP: error code 68 - Entry Already Exists]
            if (!e.getMessage().startsWith("[LDAP: error code 68 - ")) {
                storeLdapException(e, prc);
                throw new SenderException(e);
            }
            return DEFAULT_RESULT_CREATE_NOK;
        } finally {
            closeDirContext(dirContext);
        }
    }
}

From source file:org.apache.ambari.server.serveraction.kerberos.ADKerberosOperationHandler.java

/**
 * Updates the password for an existing principal in a previously configured KDC
 * <p/>/*w w  w  .j  a  v a2 s  . com*/
 * The implementation is specific to a particular type of KDC.
 *
 * @param principal a String containing the principal to update
 * @param password  a String containing the password to set
 * @return an Integer declaring the new key number
 * @throws KerberosOperationException
 */
@Override
public Integer setPrincipalPassword(String principal, String password) throws KerberosOperationException {
    if (!isOpen()) {
        throw new KerberosOperationException("This operation handler has not been opened");
    }
    if (principal == null) {
        throw new KerberosOperationException("principal is null");
    }
    if (password == null) {
        throw new KerberosOperationException("principal password is null");
    }

    DeconstructedPrincipal deconstructPrincipal = createDeconstructPrincipal(principal);

    try {
        String dn = findPrincipalDN(deconstructPrincipal.getNormalizedPrincipal());

        if (dn != null) {
            ldapContext.modifyAttributes(escapeDNCharacters(dn),
                    new ModificationItem[] {
                            new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("unicodePwd",
                                    String.format("\"%s\"", password).getBytes("UTF-16LE"))) });
        } else {
            throw new KerberosOperationException(
                    String.format("Can not set password for principal %s: Not Found", principal));
        }
    } catch (NamingException e) {
        throw new KerberosOperationException(
                String.format("Can not set password for principal %s: %s", principal, e.getMessage()), e);
    } catch (UnsupportedEncodingException e) {
        throw new KerberosOperationException("Unsupported encoding UTF-16LE", e);
    }

    return 0;
}

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

/**
 * Converts a modification operation.//from  w w  w. j av a  2 s . co 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//www . ja v a2  s .  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.//w  w w.  java  2 s .c om
 * 
 * @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//from  w  ww. j a va 2  s .c  om
 *
 * @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.apache.syncope.fit.AbstractITCase.java

protected void updateLdapRemoteObject(final String bindDn, final String bindPwd, final String objectDn,
        final Pair<String, String> attribute) {

    InitialDirContext ctx = null;
    try {/* w w w  .j  a  v a 2s  .  c  o m*/
        ctx = getLdapResourceDirContext(bindDn, bindPwd);

        Attribute ldapAttribute = new BasicAttribute(attribute.getKey(), attribute.getValue());
        ModificationItem[] item = new ModificationItem[1];
        item[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, ldapAttribute);
        ctx.modifyAttributes(objectDn, item);
    } catch (Exception e) {
        // ignore
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (NamingException e) {
                // ignore
            }
        }
    }
}

From source file:org.bedework.selfreg.common.DirMaintImpl.java

@Override
public void setUserPassword(final String account, final String password) throws SelfregException {
    BasicAttribute attr = new BasicAttribute("userPassword", encodedPassword(password.toCharArray()));
    ModificationItem mi = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr);

    ModificationItem[] mods = { mi };
    getLdir().modify(accountDn(account), mods);
}