Example usage for javax.naming.directory DirContext ADD_ATTRIBUTE

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

Introduction

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

Prototype

int ADD_ATTRIBUTE

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

Click Source Link

Document

This constant specifies to add an attribute with the specified values.

Usage

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

/**
 * Imports the LDIF record./*from   w  w w .  j  av  a 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/*  ww  w  .jav  a 2s.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.bedework.selfreg.common.DirMaintImpl.java

@Override
public void addGroupMember(final String group, final String account) throws SelfregException {
    //if (!accountExists(account)) {
    //  error("Account " + account + " does not exist");
    //}// ww  w  . j a v  a  2 s.  c  om

    BasicAttribute attr = new BasicAttribute("member", accountDn(account));
    ModificationItem mi = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr);

    ModificationItem[] mods = { mi };
    getLdir().modify(groupDn(group), mods);
}

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

/**
 * @param rootDn/*from  w  w  w  .ja v a2s.com*/
 * @param type
 * @param rdnValue
 */
public void addRdn(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.ADD_ATTRIBUTE, attribute);

        ctx.modifyAttributes("", modifications);

    }

    catch (NamingException e) {
        throw new RuntimeException(e);
    }

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

}

From source file:org.exoplatform.services.organization.DummyLDAPServiceImpl.java

private void addNewSchema() throws NamingException {
    DirContext ctx = getLdapContext();
    try {/*from ww w .  j  a va  2s  .  c o  m*/
        Attributes atAttrs = new BasicAttributes(true);
        atAttrs.put("attributeTypes",
                "( 1.2.840.113556.1.4.8 NAME 'userAccountControl' DESC 'Flags that control the behavior of the user account' EQUALITY integerMatch SYNTAX '1.3.6.1.4.1.1466.115.121.1.27' SINGLE-VALUE )");
        ctx.modifyAttributes("cn=schema", DirContext.ADD_ATTRIBUTE, atAttrs);
        Attributes ocAttrs = new BasicAttributes(true);
        ocAttrs.put("objectClasses",
                "( 1.2.840.113556.1.5.9 NAME 'user' SUP inetOrgPerson STRUCTURAL MAY (userAccountControl) )");
        ctx.modifyAttributes("cn=schema", DirContext.ADD_ATTRIBUTE, ocAttrs);
    } finally {
        ctx.close();
    }
}

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

protected void addAuthorities(DistinguishedName userDn, Collection<? extends GrantedAuthority> authorities) {
    modifyAuthorities(userDn, authorities, DirContext.ADD_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/*from  w ww . j  av  a2s  .  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);
}

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

@Override
public void addAttributes(final String dn, final String attribute, final Collection<String> values) {
    if (values.isEmpty()) {
        // Ignore this call
        return;//w w w.  j a  v a2 s. c om
    }

    // Build the modification operation
    final ModificationItem[] mods = values.stream()
            .map(v -> new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute(attribute, v)))
            .toArray(ModificationItem[]::new);
    try {
        // Perform the addition
        template.modifyAttributes(org.springframework.ldap.support.LdapUtils.newLdapName(dn), mods);
    } catch (final org.springframework.ldap.AttributeInUseException aiue) {
        if (!aiue.getMessage()
                .matches(".*(value #0 already exists|error code 20|ATTRIBUTE_OR_VALUE_EXISTS).*")) {
            throw aiue;
        }
        log.info("{} is already member of {}", values, dn);
    }
}

From source file:org.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

/**
 * @param dn//from   w  w  w .  jav a 2 s  .co m
 * @param attribute
 * @throws LDAPException
 * @see org.mule.module.ldap.api.LDAPConnection#addAttribute(java.lang.String,
 *      org.mule.module.ldap.api.LDAPEntryAttribute)
 */
public void addAttribute(String dn, LDAPEntryAttribute attribute) throws LDAPException {
    try {
        ModificationItem[] mods = new ModificationItem[1];
        mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, buildBasicAttribute(attribute));
        getConn().modifyAttributes(dn, mods);
    } catch (NamingException nex) {
        throw handleNamingException(nex, "Add attribute failed.");
    }
}

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)
 *///from   www .  j  av a  2  s . c  o m
@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);
    }
}