Example usage for javax.naming.directory BasicAttributes put

List of usage examples for javax.naming.directory BasicAttributes put

Introduction

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

Prototype

public Attribute put(Attribute attr) 

Source Link

Usage

From source file:org.nuxeo.ecm.directory.ldap.MockLdapServer.java

private void initConfiguration() throws NamingException {
    // Create the partition for the tests
    MutablePartitionConfiguration testPartition = new MutablePartitionConfiguration();
    testPartition.setId("NuxeoTestLdapServer");
    testPartition.setSuffix(BASE_DN);/* w  w w.ja  va2  s.c  o m*/

    BasicAttributes attributes = new BasicAttributes();
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("domain");
    objectClass.add("extensibleObject");
    attributes.put(objectClass);
    testPartition.setContextEntry(attributes);

    Set<Object> indexedAttrs = new HashSet<Object>();
    indexedAttrs.add("objectClass");
    indexedAttrs.add("uid");
    indexedAttrs.add("cn");
    indexedAttrs.add("ou");
    indexedAttrs.add("uniqueMember");

    // POSIX RFC-2307 schema.
    indexedAttrs.add("gidNumber");
    indexedAttrs.add("uidNumber");

    testPartition.setIndexedAttributes(indexedAttrs);

    Set<MutablePartitionConfiguration> partitions = new HashSet<MutablePartitionConfiguration>();
    partitions.add(testPartition);

    cfg.setPartitionConfigurations(partitions);
}

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);/* w ww. j av a2 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;
}

From source file:org.springframework.ldap.support.LdapUtilsTest.java

@Test
public void testCollectAttributeValues() {
    String expectedAttributeName = "someAttribute";
    BasicAttribute expectedAttribute = new BasicAttribute(expectedAttributeName);
    expectedAttribute.add("value1");
    expectedAttribute.add("value2");

    BasicAttributes attributes = new BasicAttributes();
    attributes.put(expectedAttribute);

    LinkedList list = new LinkedList();
    LdapUtils.collectAttributeValues(attributes, expectedAttributeName, list);

    assertThat(list).hasSize(2);//from   w w  w  .  j a v a 2s .  co m
    assertThat(list.get(0)).isEqualTo("value1");
    assertThat(list.get(1)).isEqualTo("value2");
}

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

private void constructBasicAttributes(BasicAttributes basicAttributes, String id, String principleName,
        Object credential, String commonName, String surName) throws DirectoryServerManagerException {

    // set the objectClass type for schema
    BasicAttribute objectClass = new BasicAttribute(LDAPServerManagerConstants.LDAP_OBJECT_CLASS);
    objectClass.add(LDAPServerManagerConstants.LDAP_INTET_ORG_PERSON);
    objectClass.add(LDAPServerManagerConstants.LDAP_ORG_PERSON);
    objectClass.add(LDAPServerManagerConstants.LDAP_PERSON);
    objectClass.add(LDAPServerManagerConstants.LDAP_TOP);

    // Add Kerberos specific object classes
    objectClass.add(LDAPServerManagerConstants.LDAP_KRB5_PRINCIPLE);
    objectClass.add(LDAPServerManagerConstants.LDAP_KRB5_KDC);
    objectClass.add(LDAPServerManagerConstants.LDAP_SUB_SCHEMA);

    basicAttributes.put(objectClass);

    BasicAttribute uid = new BasicAttribute(LDAPServerManagerConstants.LDAP_UID);
    uid.add(id);/*from w  w w.  ja  v  a 2 s .co m*/
    basicAttributes.put(uid);

    String principal = getFullyQualifiedPrincipalName(principleName);

    BasicAttribute principalAttribute = new BasicAttribute(
            LDAPServerManagerConstants.KRB5_PRINCIPAL_NAME_ATTRIBUTE);
    principalAttribute.add(principal);
    basicAttributes.put(principalAttribute);

    BasicAttribute versionNumberAttribute = new BasicAttribute(
            LDAPServerManagerConstants.KRB5_KEY_VERSION_NUMBER_ATTRIBUTE);
    versionNumberAttribute.add("0");
    basicAttributes.put(versionNumberAttribute);

    BasicAttribute userPassword = new BasicAttribute(LDAPServerManagerConstants.LDAP_PASSWORD);

    //Since we are using the KDC, we will always use plain text password.
    //KDC does not support other types of passwords
    String password = getPasswordToStore((String) credential,
            LDAPServerManagerConstants.PASSWORD_HASH_METHOD_PLAIN_TEXT);

    userPassword.add(password.getBytes());
    basicAttributes.put(userPassword);

    if (commonName == null || commonName.isEmpty()) {
        commonName = principleName + " Service";
    }

    BasicAttribute cn = new BasicAttribute(LDAPServerManagerConstants.LDAP_COMMON_NAME);
    cn.add(commonName);
    basicAttributes.put(cn);

    BasicAttribute sn = new BasicAttribute(LDAPServerManagerConstants.SERVER_PRINCIPAL_ATTRIBUTE_NAME);
    sn.add(surName);
    basicAttributes.put(sn);
}

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

public void updateServicePrinciplePassword(String serverName, Object oldCredential, Object newCredentials)
        throws DirectoryServerManagerException {

    DirContext dirContext;//from w  w w  .  j a  v  a  2 s. c  o m

    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    //first search the existing user entry.
    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);
    String searchFilter = getServicePrincipleFilter(serverName);

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

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);
        // here we assume only one user
        while (namingEnumeration.hasMore()) {

            BasicAttributes basicAttributes = new BasicAttributes(true);

            SearchResult searchResult = namingEnumeration.next();
            Attributes attributes = searchResult.getAttributes();

            Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD);
            Attribute newPasswordAttribute = getChangePasswordAttribute(userPassword, oldCredential,
                    newCredentials);
            basicAttributes.put(newPasswordAttribute);

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

            dirContext.modifyAttributes(dnName, DirContext.REPLACE_ATTRIBUTE, basicAttributes);
        }

    } catch (NamingException e) {
        log.error("Unable to update server principle password details. Server name - " + serverName);
        throw new DirectoryServerManagerException("Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}

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

/**
 *
 *///  ww  w. j  a va 2s .  c o m
public void doAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims,
        String profileName, boolean requirePasswordChange) throws UserStoreException {

    boolean isUserBinded = false;

    /* getting search base directory context */
    DirContext dirContext = getSearchBaseDirectoryContext();

    /* getting add user basic attributes */
    BasicAttributes basicAttributes = getAddUserBasicAttributes(userName);

    if (!isADLDSRole) {
        // creating a disabled user account in AD DS
        BasicAttribute userAccountControl = new BasicAttribute(
                LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL);
        userAccountControl.add(LDAPConstants.ACTIVE_DIRECTORY_DISABLED_NORMAL_ACCOUNT);
        basicAttributes.put(userAccountControl);
    }

    /* setting claims */
    setUserClaims(claims, basicAttributes, userName);

    Name compoundName = null;
    try {
        NameParser ldapParser = dirContext.getNameParser("");
        compoundName = ldapParser.parse("cn=" + escapeSpecialCharactersForDN(userName));

        /* bind the user. A disabled user account with no password */
        dirContext.bind(compoundName, null, basicAttributes);
        isUserBinded = true;

        /* update the user roles */
        doUpdateRoleListOfUser(userName, null, roleList);

        /* reset the password and enable the account */
        if (!isSSLConnection) {
            logger.warn("Unsecured connection is being used. Enabling user account operation will fail");
        }

        ModificationItem[] mods = new ModificationItem[2];
        mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_UNICODE_PASSWORD_ATTRIBUTE,
                        createUnicodePassword((String) credential)));
        if (isADLDSRole) {
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
                    new BasicAttribute(LDAPConstants.ACTIVE_DIRECTORY_MSDS_USER_ACCOUNT_DISSABLED, "FALSE"));
        } else {
            mods[1] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(
                    LDAPConstants.ACTIVE_DIRECTORY_USER_ACCOUNT_CONTROL, userAccountControl));
        }
        dirContext.modifyAttributes(compoundName, mods);

    } catch (NamingException e) {
        String errorMessage = "Error while adding the user to the Active Directory for user : " + userName;
        if (isUserBinded) {
            try {
                dirContext.unbind(compoundName);
            } catch (NamingException e1) {
                errorMessage = "Error while accessing the Active Directory for user : " + userName;
                throw new UserStoreException(errorMessage, e);
            }
            errorMessage = "Error while enabling the user account. Please check password policy at DC for user : "
                    + userName;
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(dirContext);
    }
}

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

/**
 * Sets the set of claims provided at adding users
 *
 * @param claims//from  w  ww  .  jav  a  2  s  . c  o  m
 * @param basicAttributes
 * @throws UserStoreException
 */
protected void setUserClaims(Map<String, String> claims, BasicAttributes basicAttributes, String userName)
        throws UserStoreException {
    if (claims != null) {
        BasicAttribute claim;

        for (Map.Entry<String, String> entry : claims.entrySet()) {
            // avoid attributes with empty values
            if (EMPTY_ATTRIBUTE_STRING.equals(entry.getValue())) {
                continue;
            }
            // needs to get attribute name from claim mapping
            String claimURI = entry.getKey();

            // skipping profile configuration attribute
            if (claimURI.equals(UserCoreConstants.PROFILE_CONFIGURATION)) {
                continue;
            }

            String attributeName = null;
            try {
                attributeName = getClaimAtrribute(claimURI, userName, null);
            } catch (org.wso2.carbon.user.api.UserStoreException e) {
                String errorMessage = "Error in obtaining claim mapping.";
                throw new UserStoreException(errorMessage, e);
            }

            claim = new BasicAttribute(attributeName);
            claim.add(claims.get(entry.getKey()));
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "AttributeName: " + attributeName + " AttributeValue: " + claims.get(entry.getKey()));
            }
            basicAttributes.put(claim);
        }
    }
}

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

@Override
public void doAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims,
        String profileName, boolean requirePasswordChange) throws UserStoreException {

    /* getting search base directory context */
    DirContext dirContext = getSearchBaseDirectoryContext();

    /* getting add user basic attributes */
    BasicAttributes basicAttributes = getAddUserBasicAttributes(escapeSpecialCharactersForDN(userName));

    BasicAttribute userPassword = new BasicAttribute("userPassword");
    userPassword.add(UserCoreUtil.getPasswordToStore((String) credential,
            this.realmConfig.getUserStoreProperty(PASSWORD_HASH_METHOD), kdcEnabled));
    basicAttributes.put(userPassword);

    /* setting claims */
    setUserClaims(claims, basicAttributes, userName);

    try {//from  w w w  .ja v a 2s . c o m

        NameParser ldapParser = dirContext.getNameParser("");
        Name compoundName = ldapParser.parse(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE)
                + "=" + escapeSpecialCharactersForDN(userName));

        if (log.isDebugEnabled()) {
            log.debug("Binding user: " + compoundName);
        }
        dirContext.bind(compoundName, null, basicAttributes);
    } catch (NamingException e) {
        String errorMessage = "Cannot access the directory context or "
                + "user already exists in the system for user :" + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeContext(dirContext);
    }

    try {
        /* update the user roles */
        doUpdateRoleListOfUser(userName, null, roleList);
        if (log.isDebugEnabled()) {
            log.debug("Roles are added for user  : " + userName + " successfully.");
        }
    } catch (UserStoreException e) {
        String errorMessage = "User is added. But error while updating role list of user : " + userName;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
}

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

/**
 * Returns a BasicAttributes object with basic required attributes
 *
 * @param userName/*from w w  w .  java2  s .c om*/
 * @return
 */
protected BasicAttributes getAddUserBasicAttributes(String userName) {
    BasicAttributes basicAttributes = new BasicAttributes(true);
    String userEntryObjectClassProperty = realmConfig
            .getUserStoreProperty(LDAPConstants.USER_ENTRY_OBJECT_CLASS);
    BasicAttribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
    String[] objectClassHierarchy = userEntryObjectClassProperty.split("/");
    for (String userObjectClass : objectClassHierarchy) {
        if (userObjectClass != null && !userObjectClass.trim().equals("")) {
            objectClass.add(userObjectClass.trim());
        }
    }
    // If KDC is enabled we have to set KDC specific object classes also
    if (kdcEnabled) {
        // Add Kerberos specific object classes
        objectClass.add("krb5principal");
        objectClass.add("krb5kdcentry");
        objectClass.add("subschema");
    }
    basicAttributes.put(objectClass);
    BasicAttribute userNameAttribute = new BasicAttribute(
            realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE));
    userNameAttribute.add(userName);
    basicAttributes.put(userNameAttribute);

    if (kdcEnabled) {
        CarbonContext cc = CarbonContext.getThreadLocalCarbonContext();
        if (cc != null) {
            String tenantDomainName = cc.getTenantDomain();
            if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomainName)) {
                userName = userName + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR + tenantDomainName;
            } else {
                userName = userName + UserCoreConstants.PRINCIPAL_USERNAME_SEPARATOR
                        + MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
            }
        }

        String principal = userName + "@" + this.getRealmName();

        BasicAttribute principalAttribute = new BasicAttribute(KRB5_PRINCIPAL_NAME_ATTRIBUTE);
        principalAttribute.add(principal);
        basicAttributes.put(principalAttribute);

        BasicAttribute versionNumberAttribute = new BasicAttribute(KRB5_KEY_VERSION_NUMBER_ATTRIBUTE);
        versionNumberAttribute.add("0");
        basicAttributes.put(versionNumberAttribute);
    }
    return basicAttributes;
}

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

/**
 * Sets the set of claims provided at adding users
 *
 * @param claims/*  w  w  w.  j  av a 2  s  . c o m*/
 * @param basicAttributes
 * @throws UserStoreException
 */
protected void setUserClaims(Map<String, String> claims, BasicAttributes basicAttributes, String userName)
        throws UserStoreException {
    BasicAttribute claim;
    boolean debug = log.isDebugEnabled();

    log.debug("Processing user claims");
    /*
     * we keep boolean values to know whether compulsory attributes 'sn' and 'cn' are set during
     * setting claims.
     */
    boolean isSNExists = false;
    boolean isCNExists = false;

    if (claims != null) {
        for (Map.Entry<String, String> entry : claims.entrySet()) {
            /*
             * LDAP does not allow for empty values. If an attribute has a value its stored
             * with the entry, otherwise it is not. Hence needs to check for empty values before
             * storing the attribute.
             */
            if (EMPTY_ATTRIBUTE_STRING.equals(entry.getValue())) {
                continue;
            }
            // needs to get attribute name from claim mapping
            String claimURI = entry.getKey();

            if (debug) {
                log.debug("Claim URI: " + claimURI);
            }

            String attributeName = null;
            try {
                attributeName = getClaimAtrribute(claimURI, userName, null);
            } catch (org.wso2.carbon.user.api.UserStoreException e) {
                String errorMessage = "Error in obtaining claim mapping.";
                throw new UserStoreException(errorMessage, e);
            }

            if (ATTR_NAME_CN.equals(attributeName)) {
                isCNExists = true;
            } else if (ATTR_NAME_SN.equals(attributeName)) {
                isSNExists = true;
            }

            if (debug) {
                log.debug("Mapped attribute: " + attributeName);
                log.debug("Attribute value: " + claims.get(entry.getKey()));
            }
            claim = new BasicAttribute(attributeName);
            claim.add(claims.get(entry.getKey()));
            basicAttributes.put(claim);
        }
    }

    // If required attributes cn, sn are not set during claim mapping,
    // set them as user names

    if (!isCNExists) {
        BasicAttribute cn = new BasicAttribute("cn");
        cn.add(escapeSpecialCharactersForDNWithStar(userName));
        basicAttributes.put(cn);
    }

    if (!isSNExists) {
        BasicAttribute sn = new BasicAttribute("sn");
        sn.add(escapeSpecialCharactersForDNWithStar(userName));
        basicAttributes.put(sn);
    }
}