Example usage for javax.naming.directory BasicAttribute BasicAttribute

List of usage examples for javax.naming.directory BasicAttribute BasicAttribute

Introduction

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

Prototype

public BasicAttribute(String id) 

Source Link

Document

Constructs a new instance of an unordered attribute with no value.

Usage

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

private Attribute getChangePasswordAttribute(Attribute oldPasswordAttribute, Object oldCredential,
        Object newPassword) throws DirectoryServerManagerException {

    String passwordHashMethod = null;
    // when admin changes other user passwords he do not have to provide
    // the old password.
    if (oldCredential != null) {
        // here it is only possible to have one password, if there are more
        // every one should match with the given old password

        try {/*from w w  w .  jav a  2  s  .  c  o m*/
            NamingEnumeration passwords = oldPasswordAttribute.getAll();

            if (passwords.hasMore()) {
                byte[] byteArray = (byte[]) passwords.next();
                String password = new String(byteArray, StandardCharsets.UTF_8);

                if (password.startsWith("{")) {
                    passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}"));
                }

                if (!password.equals(getPasswordToStore((String) oldCredential, passwordHashMethod))) {
                    throw new DirectoryServerManagerException("Old password does not match");
                }
            }
        } catch (NamingException e) {
            log.error("Unable to retrieve old password details.", e);
            throw new DirectoryServerManagerException("Could not find old password details");
        }
    }

    Attribute passwordAttribute = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD);
    passwordAttribute.add(getPasswordToStore((String) newPassword, passwordHashMethod));

    return passwordAttribute;

}

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//  w ww .  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.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;
    }/* www  .  ja  v a 2 s.c  o 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:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

/**
 * Checks attribute-set if it has to be written to LDAP or removed from LDAP if attribute = 0, its like not set.
 * //from w  w w . j  a v  a  2 s .c  om
 * @param pOrganisationAtt
 * @param pOldOrganisationAtt
 * @param ldapAttributeName
 * @param vOrgAttributes
 * @param vOrgRemoveAttributes
 * @param isUpdate
 */
private boolean checkAttribute(List<String> pOrganisationAtt, List<String> pOldOrganisationAtt,
        String ldapAttributeName, Attributes vOrgAttributes, Attributes vOrgRemoveAttributes,
        boolean isUpdate) {
    boolean hasChanged = false;
    if (!isUpdate) {
        // is create
        if ((pOrganisationAtt != null) && (!pOrganisationAtt.isEmpty())) {
            Attribute vAttr = new BasicAttribute(ldapAttributeName);
            for (String url : pOrganisationAtt) {
                if ((url != null) && (url.trim().length() > 0)) {
                    vAttr.add(url);
                }
            }
            if (vAttr.size() > 0) {
                vOrgAttributes.put(vAttr);
            }
        }
    } else {
        if ((pOrganisationAtt != null) && (!pOrganisationAtt.isEmpty())) {
            Attribute vAttr = new BasicAttribute(ldapAttributeName);
            if (pOrganisationAtt.size() == 1 && pOrganisationAtt.contains("") && pOldOrganisationAtt != null
                    && !pOldOrganisationAtt.isEmpty()) {
                vOrgRemoveAttributes.put(vAttr);
                hasChanged = true;
            } else {
                for (String url : pOrganisationAtt) {
                    if ((url != null) && (url.trim().length() > 0)) {
                        vAttr.add(url);
                    }
                }
                if (vAttr.size() > 0) {
                    vOrgAttributes.put(vAttr);
                    hasChanged = true;
                }
            }
        } else if ((pOrganisationAtt == null || pOrganisationAtt.isEmpty())
                && (pOldOrganisationAtt != null && !pOldOrganisationAtt.isEmpty())) {
            vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
            hasChanged = true;
        }
    }
    return hasChanged;
}

From source file:org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager.java

/**
 * This method overwrites the method in LDAPUserStoreManager. This implements the functionality
 * of updating user's profile information in LDAP user store.
 *
 * @param userName//from   w ww.  j a va2 s  . c om
 * @param claims
 * @param profileName
 * @throws org.wso2.carbon.user.core.UserStoreException
 */
@Override
public void doSetUserClaimValues(String userName, Map<String, String> claims, String profileName)
        throws UserStoreException {
    // get the LDAP Directory context
    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // search the relevant user entry by user name
    String userSearchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String userSearchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    // if user name contains domain name, remove domain name
    String[] userNames = userName.split(CarbonConstants.DOMAIN_SEPARATOR);
    if (userNames.length > 1) {
        userName = userNames[1];
    }
    userSearchFilter = userSearchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(null);

    NamingEnumeration<SearchResult> returnedResultList = null;
    String returnedUserEntry = null;

    boolean cnModified = false;
    String cnValue = null;

    try {

        returnedResultList = dirContext.search(escapeDNForSearch(userSearchBase), userSearchFilter,
                searchControls);
        // assume only one user is returned from the search
        // TODO:what if more than one user is returned
        returnedUserEntry = returnedResultList.next().getName();

    } catch (NamingException e) {
        String errorMessage = "Results could not be retrieved from the directory context for user : "
                + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(returnedResultList);
    }

    if (profileName == null) {
        profileName = UserCoreConstants.DEFAULT_PROFILE;
    }

    if (claims.get(UserCoreConstants.PROFILE_CONFIGURATION) == null) {
        claims.put(UserCoreConstants.PROFILE_CONFIGURATION, UserCoreConstants.DEFAULT_PROFILE_CONFIGURATION);
    }

    try {
        Attributes updatedAttributes = new BasicAttributes(true);

        String domainName = userName.indexOf(UserCoreConstants.DOMAIN_SEPARATOR) > -1
                ? userName.split(UserCoreConstants.DOMAIN_SEPARATOR)[0]
                : realmConfig.getUserStoreProperty(UserStoreConfigConstants.DOMAIN_NAME);
        for (Map.Entry<String, String> claimEntry : claims.entrySet()) {
            String claimURI = claimEntry.getKey();
            // if there is no attribute for profile configuration in LDAP,
            // skip updating it.
            if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) {
                continue;
            }
            // get the claimMapping related to this claimURI
            String attributeName = getClaimAtrribute(claimURI, userName, null);
            //remove user DN from cache if changing username attribute
            if (realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE).equals(attributeName)) {
                userCache.remove(userName);
            }
            // if mapped attribute is CN, then skip treating as a modified
            // attribute -
            // it should be an object rename
            if ("CN".toLowerCase().equals(attributeName.toLowerCase())) {
                cnModified = true;
                cnValue = claimEntry.getValue();
                continue;
            }
            Attribute currentUpdatedAttribute = new BasicAttribute(attributeName);
            /* if updated attribute value is null, remove its values. */
            if (EMPTY_ATTRIBUTE_STRING.equals(claimEntry.getValue())) {
                currentUpdatedAttribute.clear();
            } else {
                if (claimEntry.getValue() != null) {
                    String claimSeparator = realmConfig.getUserStoreProperty(MULTI_ATTRIBUTE_SEPARATOR);
                    if (claimSeparator != null && !claimSeparator.trim().isEmpty()) {
                        userAttributeSeparator = claimSeparator;
                    }
                    if (claimEntry.getValue().contains(userAttributeSeparator)) {
                        StringTokenizer st = new StringTokenizer(claimEntry.getValue(), userAttributeSeparator);
                        while (st.hasMoreElements()) {
                            String newVal = st.nextElement().toString();
                            if (newVal != null && newVal.trim().length() > 0) {
                                currentUpdatedAttribute.add(newVal.trim());
                            }
                        }
                    } else {
                        currentUpdatedAttribute.add(claimEntry.getValue());
                    }
                } else {
                    currentUpdatedAttribute.add(claimEntry.getValue());
                }
            }
            updatedAttributes.put(currentUpdatedAttribute);
        }
        // update the attributes in the relevant entry of the directory
        // store

        subDirContext = (DirContext) dirContext.lookup(userSearchBase);
        subDirContext.modifyAttributes(returnedUserEntry, DirContext.REPLACE_ATTRIBUTE, updatedAttributes);

        if (cnModified && cnValue != null) {
            subDirContext.rename(returnedUserEntry, "CN=" + escapeSpecialCharactersForDN(cnValue));
        }

    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String errorMessage = "Error in obtaining claim mapping for user : " + userName;
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } catch (NamingException e) {
        handleException(e, userName);
    } finally {
        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }

}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtilityOrganisation.java

private boolean checkAttributeEnum(
        //List<Enum<?>> pOrgAtt, List<Enum<?>> pOldOrgAtt, String ldapAttributeName,
        List<ConstEnumOrgSubSector> pOrgAtt, List<ConstEnumOrgSubSector> pOldOrgAtt, String ldapAttributeName,
        Attributes vOrgAttributes, Attributes vOrgRemoveAttributes, boolean isUpdate) {
    boolean hasChanged = false;
    if (!isUpdate) {
        // is create
        if ((pOrgAtt != null) && (!pOrgAtt.isEmpty())) {
            Attribute vAttr = new BasicAttribute(ldapAttributeName);
            for (Enum<?> iterEnum : pOrgAtt) {
                if (iterEnum != null) {
                    vAttr.add(iterEnum.name());
                }/*ww  w .j ava2s.  com*/
            }
            if (vAttr.size() > 0) {
                vOrgAttributes.put(vAttr);
            }
        }
    } else {
        if ((pOrgAtt != null) && (!pOrgAtt.isEmpty())) {
            Attribute vAttr = new BasicAttribute(ldapAttributeName);
            if ((pOrgAtt.isEmpty()) && (pOldOrgAtt != null) && (!pOldOrgAtt.isEmpty())) {
                vOrgRemoveAttributes.put(vAttr);
                hasChanged = true;
            } else {
                for (Enum<?> iterEnum : pOrgAtt) {
                    if (iterEnum != null) {
                        vAttr.add(iterEnum.name());
                    }
                }
                if (vAttr.size() > 0) {
                    vOrgAttributes.put(vAttr);
                    hasChanged = true;
                }
            }
        } else if ((pOrgAtt == null || pOrgAtt.isEmpty()) && (pOldOrgAtt != null && !pOldOrgAtt.isEmpty())) {
            vOrgRemoveAttributes.put(new BasicAttribute(ldapAttributeName));
            hasChanged = true;
        }
    }
    return hasChanged;
}

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

/**
 * @param attribute//w  w w .j  av a2s. c  o m
 * @return
 * @throws LDAPException
 */
private BasicAttribute buildBasicAttribute(LDAPEntryAttribute attribute) throws LDAPException {
    if (attribute != null) {
        if (attribute.isMultiValued()) {
            BasicAttribute basicAttribute = new BasicAttribute(attribute.getName());
            for (Iterator<Object> it = attribute.getValues().iterator(); it.hasNext();) {
                basicAttribute.add(it.next());
            }
            return basicAttribute;
        } else {
            return new BasicAttribute(attribute.getName(), attribute.getValue());
        }
    } else {
        return null;
    }
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

@SuppressWarnings("rawtypes")
@Override//  w w w.j  a v  a 2s  .  c o  m
public void doUpdateCredential(String userName, Object newCredential, Object oldCredential)
        throws UserStoreException {

    DirContext dirContext = this.connectionSource.getContext();
    DirContext subDirContext = null;
    // first search the existing user entry.
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_SEARCH_FILTER);
    searchFilter = searchFilter.replace("?", escapeSpecialCharactersForFilter(userName));

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "userPassword" });

    NamingEnumeration<SearchResult> namingEnumeration = null;
    NamingEnumeration passwords = null;

    try {
        namingEnumeration = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchControls);
        // here we assume only one user
        // TODO: what to do if there are more than one user
        SearchResult searchResult = null;
        String passwordHashMethod = realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD);
        while (namingEnumeration.hasMore()) {
            searchResult = namingEnumeration.next();

            String dnName = searchResult.getName();
            subDirContext = (DirContext) dirContext.lookup(searchBase);

            Attribute passwordAttribute = new BasicAttribute("userPassword");
            passwordAttribute.add(
                    UserCoreUtil.getPasswordToStore((String) newCredential, passwordHashMethod, kdcEnabled));
            BasicAttributes basicAttributes = new BasicAttributes(true);
            basicAttributes.put(passwordAttribute);
            subDirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }
        // we check whether both carbon admin entry and ldap connection
        // entry are the same
        if (searchResult.getNameInNamespace()
                .equals(realmConfig.getUserStoreProperty(LDAPConstants.CONNECTION_NAME))) {
            this.connectionSource.updateCredential((String) newCredential);
        }

    } catch (NamingException e) {
        String errorMessage = "Can not access the directory service for user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(passwords);
        JNDIUtil.closeNamingEnumeration(namingEnumeration);

        JNDIUtil.closeContext(subDirContext);
        JNDIUtil.closeContext(dirContext);
    }
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static boolean addOrganisation(LDAPUser lus, Organization org) {
    boolean registration = false;
    DirContext ctx = null;/*from www  .  j a  v a  2 s.c  o  m*/
    try {
        ctx = getAuthContext(lus.getUsername(), lus.getPassword());

        Attributes attrsBag = new BasicAttributes();

        Attribute oc = new BasicAttribute("objectClass");
        oc.add("organization");
        oc.add("top");
        attrsBag.put(oc);

        Attribute o = new BasicAttribute("o", org.getKey());
        attrsBag.put(o);

        Attribute description = new BasicAttribute("description", org.getDescription());
        attrsBag.put(description);

        if (org.getReference() != null && !org.getReference().isEmpty()) {
            Attribute registeredAddr = new BasicAttribute("registeredAddress", org.getReference());
            attrsBag.put(registeredAddr);
        }

        ResourceBundle rb = ResourceBundle.getBundle("ldap");
        ctx.createSubcontext(
                "o=" + org.getKey() + ",c=" + org.getCountryCode() + "," + rb.getString("organisationsRoot"),
                attrsBag);

        registration = true;
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return registration;

}

From source file:org.openiam.spml2.spi.example.ShellConnectorImpl.java

private BasicAttributes getBasicAttributes(List<ExtensibleObject> requestAttribute, String idField) {
    BasicAttributes attrs = new BasicAttributes();

    // add the object class
    Attribute oc = new BasicAttribute("objectclass");
    oc.add("top");

    // add the ou for this record
    Attribute ouSet = new BasicAttribute("ou");
    String ou = getOU(requestAttribute);
    log.debug("GetAttributes() - ou=" + ou);
    if (ou != null && ou.length() > 0) {
        ouSet.add(ou);//from   w ww .  jav  a  2 s.  c  om
    }

    // add the structural classes
    attrs.put(oc);
    attrs.put(ouSet);

    // add the identifier

    // add the attributes
    for (ExtensibleObject obj : requestAttribute) {
        List<ExtensibleAttribute> attrList = obj.getAttributes();
        for (ExtensibleAttribute att : attrList) {

            log.debug("Attr Name=" + att.getName() + " " + att.getValue());

            if (att.getName() != idField) {
                attrs.put(att.getName(), att.getValue());
            }
        }
    }

    return attrs;
}