Search in sources :

Example 86 with DefaultAttribute

use of org.apache.directory.api.ldap.model.entry.DefaultAttribute in project ldapchai by ldapchai.

the class ApacheLdapProviderImpl method writeBinaryAttribute.

public void writeBinaryAttribute(final String entryDN, final String attributeName, final byte[][] values, final boolean overwrite, final ChaiRequestControl[] controls) throws ChaiUnavailableException, ChaiOperationException {
    try {
        final ModifyRequest modifyRequest = new ModifyRequestImpl();
        modifyRequest.setName(new Dn(entryDN));
        modifyRequest.addAllControls(figureControls(controls));
        {
            final Modification modification = new DefaultModification();
            modification.setOperation(overwrite ? ModificationOperation.REPLACE_ATTRIBUTE : ModificationOperation.ADD_ATTRIBUTE);
            modification.setAttribute(new DefaultAttribute(attributeName, values));
            modifyRequest.addModification(modification);
        }
        final ModifyResponse response = connection.modify(modifyRequest);
        processResponse(response);
    } catch (LdapException e) {
        throw ChaiOperationException.forErrorMessage(e.getMessage());
    }
}
Also used : DefaultModification(org.apache.directory.api.ldap.model.entry.DefaultModification) Modification(org.apache.directory.api.ldap.model.entry.Modification) ModifyRequestImpl(org.apache.directory.api.ldap.model.message.ModifyRequestImpl) DefaultModification(org.apache.directory.api.ldap.model.entry.DefaultModification) Dn(org.apache.directory.api.ldap.model.name.Dn) ModifyRequest(org.apache.directory.api.ldap.model.message.ModifyRequest) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) ModifyResponse(org.apache.directory.api.ldap.model.message.ModifyResponse)

Example 87 with DefaultAttribute

use of org.apache.directory.api.ldap.model.entry.DefaultAttribute in project airavata by apache.

the class IULdapSSHAccountProvisioner method installSSHKey.

@Override
public String installSSHKey(String userId, String sshPublicKey) throws InvalidUsernameException {
    String username = getUsername(userId);
    String finalSSHPublicKey = sshPublicKey.trim();
    boolean success = withLdapConnection(ldapConnection -> {
        try {
            String dn = "uid=" + username + "," + ldapBaseDN;
            Entry entry = ldapConnection.lookup(dn);
            if (entry == null) {
                throw new RuntimeException("User [" + username + "] has no entry for " + dn);
            }
            boolean hasLdapPublicKey = entry.hasObjectClass(LDAP_PUBLIC_KEY_OBJECT_CLASS);
            ModifyRequest modifyRequest = new ModifyRequestImpl();
            modifyRequest.setName(new Dn(dn));
            // Add or Replace, depending on whether there is already an ldapPublicKey on the entry
            if (!hasLdapPublicKey) {
                modifyRequest.addModification(new DefaultAttribute("objectclass", LDAP_PUBLIC_KEY_OBJECT_CLASS), ModificationOperation.ADD_ATTRIBUTE);
                modifyRequest.addModification(new DefaultAttribute(SSH_PUBLIC_KEY_ATTRIBUTE_NAME, finalSSHPublicKey), ModificationOperation.ADD_ATTRIBUTE);
            } else {
                String oldSshPublicKey = entry.get(SSH_PUBLIC_KEY_ATTRIBUTE_NAME).getString();
                if (!oldSshPublicKey.equals(finalSSHPublicKey)) {
                    // Disallow overwriting the SSH key
                    throw new RuntimeException("User [" + username + "] already has an SSH public key in LDAP for [" + ldapBaseDN + "] and overwriting it isn't allowed.");
                // modifyRequest.addModification(new DefaultAttribute(SSH_PUBLIC_KEY_ATTRIBUTE_NAME,
                // sshPublicKey), ModificationOperation.REPLACE_ATTRIBUTE);
                } else {
                    // SSH key is already installed so just return
                    return true;
                }
            }
            ModifyResponse modifyResponse = ldapConnection.modify(modifyRequest);
            if (modifyResponse.getLdapResult().getResultCode() != ResultCodeEnum.SUCCESS) {
                logger.warn("installSSHKey ldap operation reported not being successful: " + modifyResponse);
            } else {
                logger.debug("installSSHKey ldap operation was successful: " + modifyResponse);
            }
            return true;
        } catch (LdapException e) {
            throw new RuntimeException(e);
        }
    });
    return username;
}
Also used : Entry(org.apache.directory.api.ldap.model.entry.Entry) ModifyRequestImpl(org.apache.directory.api.ldap.model.message.ModifyRequestImpl) Dn(org.apache.directory.api.ldap.model.name.Dn) ModifyRequest(org.apache.directory.api.ldap.model.message.ModifyRequest) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) ModifyResponse(org.apache.directory.api.ldap.model.message.ModifyResponse)

Example 88 with DefaultAttribute

use of org.apache.directory.api.ldap.model.entry.DefaultAttribute in project directory-ldap-api by apache.

the class LdifReader method parseModify.

/**
 * Parse a modify change type.
 *
 * The grammar is :
 * <pre>
 * &lt;changerecord&gt; ::= "changetype:" FILL "modify" SEP &lt;mod-spec&gt; &lt;mod-specs-e&gt;
 * &lt;mod-spec&gt; ::= "add:" &lt;mod-val&gt; | "delete:" &lt;mod-val-del&gt; | "replace:" &lt;mod-val&gt;
 * &lt;mod-specs-e&gt; ::= &lt;mod-spec&gt;
 * &lt;mod-specs-e&gt; | e
 * &lt;mod-val&gt; ::= FILL ATTRIBUTE-DESCRIPTION SEP ATTRVAL-SPEC &lt;attrval-specs-e&gt; "-" SEP
 * &lt;mod-val-del&gt; ::= FILL ATTRIBUTE-DESCRIPTION SEP &lt;attrval-specs-e&gt; "-" SEP
 * &lt;attrval-specs-e&gt; ::= ATTRVAL-SPEC &lt;attrval-specs&gt; | e
 * </pre>
 *
 * @param entry The entry to feed
 * @param iter The lines
 * @exception LdapLdifException If the modify operation is invalid
 */
private void parseModify(LdifEntry entry, Iterator<String> iter) throws LdapLdifException {
    int state = MOD_SPEC;
    String modified = null;
    ModificationOperation modificationType = ModificationOperation.ADD_ATTRIBUTE;
    Attribute attribute = null;
    // The following flag is used to deal with empty modifications
    boolean isEmptyValue = true;
    while (iter.hasNext()) {
        String line = iter.next();
        String lowerLine = Strings.toLowerCaseAscii(line);
        if (lowerLine.startsWith("-")) {
            if ((state != ATTRVAL_SPEC_OR_SEP) && (state != ATTRVAL_SPEC)) {
                String msg = I18n.err(I18n.ERR_13413_BAD_MODIFY_SEPARATOR, lineNumber);
                LOG.error(msg);
                throw new LdapLdifException(msg);
            } else {
                if (isEmptyValue) {
                    if (state == ATTRVAL_SPEC_OR_SEP) {
                        entry.addModification(modificationType, modified);
                    } else {
                        // Update the entry with a null value
                        entry.addModification(modificationType, modified, null);
                    }
                } else {
                    // Update the entry with the attribute
                    entry.addModification(modificationType, attribute);
                }
                state = MOD_SPEC;
                isEmptyValue = true;
            }
        } else if (lowerLine.startsWith("add:")) {
            if ((state != MOD_SPEC) && (state != ATTRVAL_SPEC)) {
                String msg = I18n.err(I18n.ERR_13414_BAD_MODIFY_SEPARATOR_2, lineNumber);
                LOG.error(msg);
                throw new LdapLdifException(msg);
            }
            modified = Strings.trim(line.substring("add:".length()));
            modificationType = ModificationOperation.ADD_ATTRIBUTE;
            attribute = new DefaultAttribute(modified);
            state = ATTRVAL_SPEC;
        } else if (lowerLine.startsWith("delete:")) {
            if ((state != MOD_SPEC) && (state != ATTRVAL_SPEC)) {
                String msg = I18n.err(I18n.ERR_13414_BAD_MODIFY_SEPARATOR_2, lineNumber);
                LOG.error(msg);
                throw new LdapLdifException(msg);
            }
            modified = Strings.trim(line.substring("delete:".length()));
            modificationType = ModificationOperation.REMOVE_ATTRIBUTE;
            attribute = new DefaultAttribute(modified);
            isEmptyValue = false;
            state = ATTRVAL_SPEC_OR_SEP;
        } else if (lowerLine.startsWith("replace:")) {
            if ((state != MOD_SPEC) && (state != ATTRVAL_SPEC)) {
                String msg = I18n.err(I18n.ERR_13414_BAD_MODIFY_SEPARATOR_2, lineNumber);
                LOG.error(msg);
                throw new LdapLdifException(msg);
            }
            modified = Strings.trim(line.substring("replace:".length()));
            modificationType = ModificationOperation.REPLACE_ATTRIBUTE;
            if (schemaManager != null) {
                AttributeType attributeType = schemaManager.getAttributeType(modified);
                attribute = new DefaultAttribute(modified, attributeType);
            } else {
                attribute = new DefaultAttribute(modified);
            }
            state = ATTRVAL_SPEC_OR_SEP;
        } else {
            if ((state != ATTRVAL_SPEC) && (state != ATTRVAL_SPEC_OR_SEP)) {
                String msg = I18n.err(I18n.ERR_13413_BAD_MODIFY_SEPARATOR, lineNumber);
                LOG.error(msg);
                throw new LdapLdifException(msg);
            }
            // A standard AttributeType/AttributeValue pair
            int colonIndex = line.indexOf(':');
            String attributeType = line.substring(0, colonIndex);
            if (!attributeType.equalsIgnoreCase(modified)) {
                LOG.error(I18n.err(I18n.ERR_13415_MOD_ATTR_AND_VALUE_SPEC_NOT_EQUAL, lineNumber));
                throw new LdapLdifException(I18n.err(I18n.ERR_13454_BAD_MODIFY_ATTRIBUTE));
            }
            // We should *not* have a Dn twice
            if ("dn".equalsIgnoreCase(attributeType)) {
                LOG.error(I18n.err(I18n.ERR_13400_ENTRY_WITH_TWO_DNS, lineNumber));
                throw new LdapLdifException(I18n.err(I18n.ERR_13439_LDIF_ENTRY_WITH_TWO_DNS));
            }
            Object attributeValue = parseValue(attributeType, line, colonIndex);
            try {
                if (attributeValue instanceof String) {
                    attribute.add((String) attributeValue);
                } else {
                    attribute.add((byte[]) attributeValue);
                }
            } catch (LdapInvalidAttributeValueException liave) {
                throw new LdapLdifException(liave.getMessage(), liave);
            }
            isEmptyValue = false;
            state = ATTRVAL_SPEC_OR_SEP;
        }
    }
    if (state != MOD_SPEC) {
        String msg = I18n.err(I18n.ERR_13414_BAD_MODIFY_SEPARATOR_2, lineNumber);
        LOG.error(msg);
        throw new LdapLdifException(msg);
    }
}
Also used : ModificationOperation(org.apache.directory.api.ldap.model.entry.ModificationOperation) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) AttributeType(org.apache.directory.api.ldap.model.schema.AttributeType) MutableAttributeType(org.apache.directory.api.ldap.model.schema.MutableAttributeType) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) LdapInvalidAttributeValueException(org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException)

Example 89 with DefaultAttribute

use of org.apache.directory.api.ldap.model.entry.DefaultAttribute in project directory-ldap-api by apache.

the class LdifRevertor method reverseModify.

/**
 * Compute the reversed LDIF for a modify request. We will deal with the
 * three kind of modifications :
 * <ul>
 * <li>add</li>
 * <li>remove</li>
 * <li>replace</li>
 * </ul>
 *
 * As the modifications should be issued in a reversed order ( ie, for
 * the initials modifications {A, B, C}, the reversed modifications will
 * be ordered like {C, B, A}), we will change the modifications order.
 *
 * @param dn the dn of the modified entry
 * @param forwardModifications the modification items for the forward change
 * @param modifiedEntry The modified entry. Necessary for the destructive modifications
 * @return A reversed LDIF
 * @throws LdapException If something went wrong
 */
public static LdifEntry reverseModify(Dn dn, List<Modification> forwardModifications, Entry modifiedEntry) throws LdapException {
    // First, protect the original entry by cloning it : we will modify it
    Entry clonedEntry = modifiedEntry.clone();
    LdifEntry entry = new LdifEntry();
    entry.setChangeType(ChangeType.Modify);
    entry.setDn(dn);
    // As the reversed modifications should be pushed in reversed order,
    // we create a list to temporarily store the modifications.
    List<Modification> reverseModifications = new ArrayList<>();
    // the reversed modification
    for (Modification modification : forwardModifications) {
        switch(modification.getOperation()) {
            case ADD_ATTRIBUTE:
                Attribute mod = modification.getAttribute();
                Attribute previous = clonedEntry.get(mod.getId());
                if (mod.equals(previous)) {
                    continue;
                }
                Modification reverseModification = new DefaultModification(ModificationOperation.REMOVE_ATTRIBUTE, mod);
                reverseModifications.add(0, reverseModification);
                break;
            case REMOVE_ATTRIBUTE:
                mod = modification.getAttribute();
                previous = clonedEntry.get(mod.getId());
                if (previous == null) {
                    // Nothing to do if the previous attribute didn't exist
                    continue;
                }
                if (mod.get() == null) {
                    reverseModification = new DefaultModification(ModificationOperation.ADD_ATTRIBUTE, previous);
                    reverseModifications.add(0, reverseModification);
                    break;
                }
                reverseModification = new DefaultModification(ModificationOperation.ADD_ATTRIBUTE, mod);
                reverseModifications.add(0, reverseModification);
                break;
            case REPLACE_ATTRIBUTE:
                mod = modification.getAttribute();
                previous = clonedEntry.get(mod.getId());
                /*
                     * The server accepts without complaint replace
                     * modifications to non-existing attributes in the
                     * entry.  When this occurs nothing really happens
                     * but this method freaks out.  To prevent that we
                     * make such no-op modifications produce the same
                     * modification for the reverse direction which should
                     * do nothing as well.
                     */
                if ((mod.get() == null) && (previous == null)) {
                    reverseModification = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, new DefaultAttribute(mod.getId()));
                    reverseModifications.add(0, reverseModification);
                    continue;
                }
                if (mod.get() == null) {
                    reverseModification = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, previous);
                    reverseModifications.add(0, reverseModification);
                    continue;
                }
                if (previous == null) {
                    Attribute emptyAttribute = new DefaultAttribute(mod.getId());
                    reverseModification = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, emptyAttribute);
                    reverseModifications.add(0, reverseModification);
                    continue;
                }
                reverseModification = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, previous);
                reverseModifications.add(0, reverseModification);
                break;
            default:
                // Do nothing
                break;
        }
        AttributeUtils.applyModification(clonedEntry, modification);
    }
    // Special case if we don't have any reverse modifications
    if (reverseModifications.isEmpty()) {
        throw new IllegalArgumentException(I18n.err(I18n.ERR_13465_CANT_DEDUCE_REVERSE_FOR_MOD, forwardModifications));
    }
    // Now, push the reversed list into the entry
    for (Modification modification : reverseModifications) {
        entry.addModification(modification);
    }
    // Return the reverted entry
    return entry;
}
Also used : DefaultModification(org.apache.directory.api.ldap.model.entry.DefaultModification) Modification(org.apache.directory.api.ldap.model.entry.Modification) Entry(org.apache.directory.api.ldap.model.entry.Entry) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) Attribute(org.apache.directory.api.ldap.model.entry.Attribute) DefaultModification(org.apache.directory.api.ldap.model.entry.DefaultModification) ArrayList(java.util.ArrayList) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute)

Example 90 with DefaultAttribute

use of org.apache.directory.api.ldap.model.entry.DefaultAttribute in project directory-ldap-api by apache.

the class LdifRevertor method generateModify.

/**
 * A helper method to generate the modified attribute after a rename.
 */
private static LdifEntry generateModify(Dn parentDn, Entry entry, Rdn oldRdn, Rdn newRdn) {
    LdifEntry restored = new LdifEntry();
    restored.setChangeType(ChangeType.Modify);
    // We have to use the parent Dn, the entry has already
    // been renamed
    restored.setDn(parentDn);
    for (Ava ava : newRdn) {
        // in the previous modification
        if (!entry.contains(ava.getNormType(), ava.getValue().getValue()) && !(ava.getNormType().equals(oldRdn.getNormType()) && ava.getValue().getValue().equals(oldRdn.getValue()))) {
            // Create the modification, which is an Remove
            Modification modification = new DefaultModification(ModificationOperation.REMOVE_ATTRIBUTE, new DefaultAttribute(ava.getType(), ava.getValue().getValue()));
            restored.addModification(modification);
        }
    }
    return restored;
}
Also used : DefaultModification(org.apache.directory.api.ldap.model.entry.DefaultModification) Modification(org.apache.directory.api.ldap.model.entry.Modification) DefaultModification(org.apache.directory.api.ldap.model.entry.DefaultModification) DefaultAttribute(org.apache.directory.api.ldap.model.entry.DefaultAttribute) Ava(org.apache.directory.api.ldap.model.name.Ava)

Aggregations

DefaultAttribute (org.apache.directory.api.ldap.model.entry.DefaultAttribute)159 Attribute (org.apache.directory.api.ldap.model.entry.Attribute)131 Test (org.junit.Test)106 DefaultModification (org.apache.directory.api.ldap.model.entry.DefaultModification)41 Modification (org.apache.directory.api.ldap.model.entry.Modification)40 Entry (org.apache.directory.api.ldap.model.entry.Entry)36 DefaultEntry (org.apache.directory.api.ldap.model.entry.DefaultEntry)35 Value (org.apache.directory.api.ldap.model.entry.Value)20 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ObjectInputStream (java.io.ObjectInputStream)13 ByteArrayOutputStream (java.io.ByteArrayOutputStream)12 ObjectOutputStream (java.io.ObjectOutputStream)12 Dn (org.apache.directory.api.ldap.model.name.Dn)12 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)11 AttributeType (org.apache.directory.api.ldap.model.schema.AttributeType)11 LdapInvalidAttributeValueException (org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException)8 ModifyRequest (org.apache.directory.api.ldap.model.message.ModifyRequest)7 ModifyRequestImpl (org.apache.directory.api.ldap.model.message.ModifyRequestImpl)7 ModifyResponse (org.apache.directory.api.ldap.model.message.ModifyResponse)7 HashSet (java.util.HashSet)6