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:Main.java

public static void main(String[] argv) throws Exception {
    ModificationItem[] mods = new ModificationItem[3];

    mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("mail", "g@w.com"));

    mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("number", "5555"));

    mods[2] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("jpeg"));
    String url = "ldap://localhost/o=JNDITutorial";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);

    DirContext ctx = new InitialDirContext(env);
    ctx.modifyAttributes("cn=Name, ou=People", mods);
}

From source file:Modify2Example.java

public static void main(String args[]) {
    Hashtable env = new Hashtable(11);

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://MyHost/o=JNDIExample");
    try {/*w  ww . j av  a  2  s.c o  m*/
        DirContext dctx = new InitialDirContext(env);

        ModificationItem[] mods = new ModificationItem[3];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("department", "sales"));
        mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("quota", "$1"));
        mods[2] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("assistant"));

        dctx.modifyAttributes("cn=Name, ou=People", mods);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:ModAttrs.java

public static void main(String[] args) {

    // Set up the environment for creating the initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {/*w w w .j  a va 2 s.  c o  m*/
        // Create the initial context
        DirContext ctx = new InitialDirContext(env);
        String name = "cn=Ted Geisel, ou=People";

        // Save original attributes
        Attributes orig = ctx.getAttributes(name, new String[] { "mail", "telephonenumber", "jpegphoto" });

        // Specify the changes to make
        ModificationItem[] mods = new ModificationItem[3];

        // Replace the "mail" attribute with a new value
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute("mail", "geisel@wizards.com"));

        // Add additional value to "telephonenumber"
        mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE,
                new BasicAttribute("telephonenumber", "+1 555 555 5555"));

        // Remove the "jpegphoto" attribute
        mods[2] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("jpegphoto"));

        // Perform the requested modifications on the named object
        ctx.modifyAttributes(name, mods);

        // Check attributes
        System.out.println("**** new attributes *****");
        printAttrs(ctx.getAttributes(name));

        // Revert changes
        ctx.modifyAttributes(name, DirContext.REPLACE_ATTRIBUTE, orig);

        // Check that the attributes got restored
        System.out.println("**** reverted to original attributes *****");
        printAttrs(ctx.getAttributes(name));

        // Close the context when we're done
        ctx.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ca.tnt.ldaputils.impl.LdapEntry.java

/**
 * Please note, the preferred method is to call setXXXX() where XXXX is the
 * attribute name, followed by save().//from   www. ja v  a2s . co m
 * <p/>
 * This sets a batch attribute.  This means that it will be added to a queue
 * for changing LDAP.  You can modify the same attribute multiple times,
 * assuming LDAP supports multivalued attributes for that attribute. You are
 * then required to call modifyBatchAttributes(), which will actually do the
 * operations requested.
 * <p/>
 * You should call this one or more times per attribute, followed by
 * modifyBatchAttributes().
 * <p/>
 * Each time you call this method, for the same attribute, you should
 * specify the same operation, otherwise you will get an
 * IllegalArgumentException, with an appropriate error message.
 *
 * @param operation one of ADD_ATTRIBUTE, REPLACE_ATTRIBUTE,
 *                  REMOVE_ATTRIBUTE
 * @param attribute the name of the attribute
 * @param value     the value of the attribute
 *
 * @see #ADD_ATTRIBUTE ADD_ATTRIBUTE
 * @see #REPLACE_ATTRIBUTE REPLACE_ATTRIBUTE
 * @see #REMOVE_ATTRIBUTE REMOVE_ATTRIBUTE
 */
public void modifyBatchAttribute(final int operation, final String attribute, final Object value) {
    final Attribute newAttribute;
    ModificationItem modItem;
    final int mod_op;

    switch (operation) {
    case ADD_ATTRIBUTE:
        mod_op = DirContext.ADD_ATTRIBUTE;
        break;
    case REPLACE_ATTRIBUTE:
        mod_op = DirContext.REPLACE_ATTRIBUTE;
        break;
    case REMOVE_ATTRIBUTE:
        mod_op = DirContext.REMOVE_ATTRIBUTE;
        break;
    default:
        mod_op = DirContext.ADD_ATTRIBUTE;
    }

    modItem = (ModificationItem) modificationItems.get(attribute);
    if (modItem == null) { // first time we are doing something with this attribute
        newAttribute = new BasicAttribute(attribute, value);
        modItem = new ModificationItem(mod_op, newAttribute);
    } else { // we will add it to the attribute values for this attribute
        if (modItem.getModificationOp() != mod_op) { // make sure they aren't changing their mind on which op
            throw new IllegalArgumentException(
                    "error, operation does not match previous batch items for this attribute");
        }

        modItem.getAttribute().add(value);
    }
    modified = true;
    modificationItems.put(attribute, modItem);
}

From source file:edu.kit.scc.ldap.LdapPosixGroupDao.java

/**
 * Removes a POSIX user from the specified POSIX group.
 * /*  ww w  .  j a va 2  s  .  c  om*/
 * @param group the POSIX group
 * @param memberUid the POSIX user's uid
 * @return true on success
 */
public boolean removeMember(PosixGroup group, String memberUid) {
    ModificationItem[] modificationItems = new ModificationItem[] {
            new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("memberUid", memberUid)) };
    LdapName groupDn = LdapUtils.emptyLdapName();
    try {
        groupDn = new LdapName(groupBase);
        groupDn.add("cn=" + group.getCommonName());
        log.debug("Remove member {} from {}", memberUid, groupDn.toString());
        ldapTemplate.modifyAttributes(groupDn, modificationItems);
        return true;
    } catch (AttributeInUseException ex) {
        log.error("ERROR {}", ex.toString());
    } catch (InvalidNameException ex) {
        log.error("ERROR {}", ex.toString());
    }
    return false;
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.mod", required = { "userId" })
@RequiresAuthentication/*from   w  ww  .j ava2  s  .c om*/
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> modifyUser(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    UserDn userDn = nameHelper.newUserDnFromId(userId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());
    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

    HashMap<String, Object> response = new HashMap<String, Object>();

    DirContextAdapter dca = (DirContextAdapter) userDirContext.lookup(userDn);

    HashMap<String, Object> modValues = displayAttributeHelper
            .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("mod"));
    HashMap<String, Object> addValues = displayAttributeHelper
            .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("add"));
    HashMap<String, Object> removeValues = displayAttributeHelper
            .apiToLdapAttrNames((HashMap<String, Object>) opContext.getParams().get("remove"));
    List<String> removeAttrs = (List<String>) opContext.getParams().get("removeAttr");

    IntegrityCheckUtil integrityCheckUtil = new IntegrityCheckUtil(userDirContext);
    HashMap<String, String> busyValues = new HashMap<String, String>();

    LinkedList<ModificationItem> removeAttrList = new LinkedList<ModificationItem>();
    if (removeAttrs != null) {
        for (String apiName : removeAttrs) {
            BasicAttribute attr = new BasicAttribute(displayAttributeHelper.getLdapName(apiName));
            ModificationItem mi = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, attr);
            removeAttrList.add(mi);
        }
    }

    for (Entry<String, Object> entry : modValues.entrySet()) {

        if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) {
            if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), entry.getValue().toString())) {
                busyValues.put(entry.getKey(), entry.getValue().toString());
            }
        }

        dca.setAttributeValue(entry.getKey(), entry.getValue().toString());
    }

    for (Entry<String, Object> entry : removeValues.entrySet()) {
        if (entry.getValue() instanceof List) {
            for (Object value : (List) entry.getValue()) {
                dca.removeAttributeValue(entry.getKey(), value);
            }
        } else {
            dca.removeAttributeValue(entry.getKey(), entry.getValue());
        }
    }

    for (Entry<String, Object> entry : addValues.entrySet()) {
        if (entry.getValue() instanceof List) {

            for (Object value : (List) entry.getValue()) {

                if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) {
                    if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), (String) value)) {
                        busyValues.put(entry.getKey(), (String) value);
                    }
                }

                dca.addAttributeValue(entry.getKey(), value);
            }
        } else {

            if (displayAttributeHelper.byLdapName(entry.getKey()).isDomainUnique()) {
                if (!integrityCheckUtil.isUnique(domainDn, entry.getKey(), (String) entry.getValue())) {
                    busyValues.put(entry.getKey(), (String) entry.getValue());
                }
            }

            dca.addAttributeValue(entry.getKey(), entry.getValue());
        }
    }

    if (busyValues.size() > 0) {
        response.put("success", false);
        response.put("busyValues", busyValues);
    } else {
        userDirContext.modifyAttributes(userDn, removeAttrList.toArray(new ModificationItem[0]));
        userDirContext.modifyAttributes(userDn, dca.getModificationItems());
        response.put("success", true);
    }

    return response;
}

From source file:gov.medicaid.dao.impl.LDAPIdentityProviderDAOBean.java

/**
 * Removes the given user from the given role.
 *
 * @param ctx the directory context/*from   ww w  .ja  v a  2  s . c o  m*/
 * @param username the user to be removed
 * @param existingRole the role to be removed from
 * @throws NamingException for any errors encountered
 */
private void removeRoleAssignment(DirContext ctx, String username, String existingRole) throws NamingException {
    ModificationItem[] mods = new ModificationItem[1];
    BasicAttribute m = new BasicAttribute(groupMemberAttr, MessageFormat.format(userDNPattern, username));
    mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, m);
    ctx.modifyAttributes(MessageFormat.format(groupDNPattern, existingRole), mods);
}

From source file:de.fiz.ddb.aas.auxiliaryoperations.ThreadOrganisationUpdate.java

private void updateOrg() throws NameNotFoundException, AASUnauthorizedException, AttributeModificationException,
        ExecutionException {//ww w  . jav a 2  s .com
    boolean vChange = false;
    InitialLdapContext vCtx = null;
    try {

        if (this._oldOrganisation == null) {
            LOG.log(Level.WARNING, "No such organization ''{0}'' with oid: ''{1}''.",
                    new Object[] { this._organisation.getDisplayName(), this._organisation.getOIDs() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        GeoAdresse vGeoAdresse;
        String vLocalDispalyName = null;
        if (_submit != null) { // hier ist "GeoLocationDisplayName" breits ausgefhrt
            try {
                vGeoAdresse = _submit.get(10, TimeUnit.SECONDS);
                if (vGeoAdresse.getRequestStatus() == GeoRequestStatus.OK) {
                    this._organisation.getAddress().setLatitude(vGeoAdresse.getLatitude());
                    this._organisation.getAddress().setLongitude(vGeoAdresse.getLongitude());
                    this._organisation.getAddress()
                            .setLocationDisplayName(vGeoAdresse.getLocationDisplayName());
                } else {
                    LOG.log(Level.WARNING, "GeoRequestStatus: {0}, (organization id: {1})",
                            new Object[] { vGeoAdresse.getRequestStatus(), this._organisation.getOIDs() });
                }
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        "Geocoding request exeption for organization id: " + this._organisation.getOIDs(), ex);
            }
        } else if (_submitGeoLocDisplayName != null) {
            try {
                vLocalDispalyName = _submitGeoLocDisplayName.get(5, TimeUnit.SECONDS);
                this._organisation.getAddress().setLocationDisplayName(vLocalDispalyName);
                //LOG.info("LocalDisplayName='" + vLocalDispalyName + "'" + vLocalDispalyName + "'");
            } catch (InterruptedException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (ExecutionException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            } catch (TimeoutException ex) {
                LOG.log(Level.WARNING,
                        this._organisation.getOIDs() + " without location display name: " + ex.getMessage());
            }

        }

        LOG.info("newOIDs: '" + this._organisation.getOIDs() + "'");
        LOG.info("oldOIDs: '" + this._oldOrganisation.getOIDs() + "'");

        if (this._organisation.getOrgRDN() == null) {
            // -- Ansonsten eine nicht gesetzte RDN kann zum Knall fhren...
            this._organisation.setOrgRDN(this._oldOrganisation.getOrgRDN());
        } else if (!this._organisation.getOrgRDN().equals(this._oldOrganisation.getOrgRDN())) {
            // -- Hier ist etwas faul...
            LOG.log(Level.WARNING,
                    "The organization ''{0}'' has RDN: ''{1}'', but there exist an organization ''{0}'' with RDN: ''{2}''!",
                    new Object[] { this._organisation.getId(), this._organisation.getOrgRDN(),
                            this._oldOrganisation.getOrgRDN() });
            throw new NameNotFoundException("No such organization '" + this._organisation.getDisplayName()
                    + "' with oid: '" + this._organisation.getOIDs() + "'.");
        }

        if (this.isPrivilegesUpdate()) {
            Set<PrivilegeEnum> removePrivileges = this.privilegeDiff(this._organisation.getPrivilegesSet(),
                    this._oldOrganisation.getPrivilegesSet());
            Set<PrivilegeEnum> addPrivileges = this.privilegeDiff(this._oldOrganisation.getPrivilegesSet(),
                    this._organisation.getPrivilegesSet());
            if (!removePrivileges.isEmpty() || !addPrivileges.isEmpty()) {
                vChange = true;
                for (PrivilegeEnum p : removePrivileges) {
                    ThreadSinglePrivilegeDelete threadSinglePrivilegeDelete = new ThreadSinglePrivilegeDelete(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeDelete.call();
                }
                for (PrivilegeEnum p : addPrivileges) {
                    ThreadSinglePrivilegeCreate threadSinglePrivilegeCreate = new ThreadSinglePrivilegeCreate(p,
                            this._organisation, this._performer);
                    threadSinglePrivilegeCreate.call();
                }
            }
        }

        Attributes orgAttributes = new BasicAttributes(true);
        Attributes orgRemoveAttributes = new BasicAttributes(true);

        if (vChange = this.convertOrganizationToLdapOrgAttrsForUpdate(this._organisation, this._oldOrganisation,
                orgAttributes, orgRemoveAttributes, getPerformer())) {

            // -- If any changes, the status is set to 'revised'
            //    but not if status will be explicitly changed or by a update operation on Licenses directory
            if (!isChangeOfStatus() && !isUpdatingOfLicensedOrgs()) {
                if ((ConstEnumOrgStatus.approved.equals(this._organisation.getStatus()))) {
                    // -- ...then go retrospectively into "revised" status:
                    this._organisation.setStatus(ConstEnumOrgStatus.revised);

                    orgAttributes.put(Constants.ldap_ddbOrg_Status,
                            String.valueOf(this._organisation.getStatus().name()));
                }
            }
        }
        // ---------------------------------------------------------------------
        if (vChange) {

            // -- Save changes to the corresponding directory:
            StringBuilder vOrgEntryDN = (isUpdatingOfLicensedOrgs()
                    ? this.getLicensedOrgsDN(this._organisation.getOIDs())
                    : this.getOrgDN(this._organisation.getOIDs()));
            LOG.log(Level.INFO, "DEBUG-Info: destination OrgEntryDN = '" + vOrgEntryDN + "'");

            vCtx = LDAPConnector.getSingletonInstance().takeCtx();
            if (orgRemoveAttributes.size() > 0) {
                vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REMOVE_ATTRIBUTE, orgRemoveAttributes);
            }
            vCtx.modifyAttributes(vOrgEntryDN.toString(), DirContext.REPLACE_ATTRIBUTE, orgAttributes);
        } else {
            throw new AttributeModificationException(
                    "Not modified: oid = '" + this._organisation.getOIDs() + "'");
        }

    } catch (RejectedExecutionException ex) {
        LOG.log(Level.SEVERE, "RejectedExecutionException\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error\n{0}", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NameNotFoundException ex) {
        LOG.log(Level.WARNING, null, ex);
        throw ex;
    } catch (AttributeModificationException ex) {
        LOG.log(Level.WARNING, "AttributeModificationException\n{0}", ex.getMessage());
        // !!!!AttributeModificationException extends NamingExeption:
        //throw ex;
        throw new AttributeModificationException(ex.getMessage());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "NamingException\n{0}", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (vCtx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(vCtx);
            } catch (Exception ex) {
                LOG.log(Level.SEVERE, "Exception", ex);
            }
        }
    }

}

From source file:org.apache.archiva.redback.common.ldap.role.DefaultLdapRoleMapper.java

public boolean removeUserRole(String roleName, String username, DirContext context) throws MappingException {
    String groupName = findGroupName(roleName);

    if (groupName == null) {
        log.warn("no group found for role '{}", roleName);
        return false;
    }//from  w  w w.j  ava 2s.co m

    NamingEnumeration<SearchResult> namingEnumeration = null;
    try {

        SearchControls searchControls = new SearchControls();

        searchControls.setDerefLinkFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String filter = "objectClass=" + getLdapGroupClass();

        namingEnumeration = context.search("cn=" + groupName + "," + getGroupsDn(), filter, searchControls);

        while (namingEnumeration.hasMore()) {
            SearchResult searchResult = namingEnumeration.next();
            Attribute attribute = searchResult.getAttributes().get(getLdapGroupMember());
            if (attribute != null) {
                BasicAttribute basicAttribute = new BasicAttribute(getLdapGroupMember());
                basicAttribute.add(this.userIdAttribute + "=" + username + "," + getGroupsDn());
                context.modifyAttributes("cn=" + groupName + "," + getGroupsDn(), new ModificationItem[] {
                        new ModificationItem(DirContext.REMOVE_ATTRIBUTE, basicAttribute) });
            }
            return true;
        }

        return false;
    } catch (LdapException e) {
        throw new MappingException(e.getMessage(), e);
    } catch (NamingException e) {
        throw new MappingException(e.getMessage(), e);
    }

    finally {
        if (namingEnumeration != null) {
            try {
                namingEnumeration.close();
            } catch (NamingException e) {
                log.warn("failed to close search results", e);
            }
        }
    }
}

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;
}