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.springframework.ldap.demo.dao.PersonDaoImpl.java

private Attributes getAttributesToBind(Person person) {
    Attributes attrs = new BasicAttributes();
    BasicAttribute ocattr = new BasicAttribute("objectclass");
    ocattr.add("top");
    ocattr.add("person");
    attrs.put(ocattr);//  w w w  . ja  v a 2 s  .co  m
    attrs.put("cn", person.getFullName());
    attrs.put("sn", person.getLastName());
    attrs.put("description", person.getDescription());
    attrs.put("telephoneNumber", person.getPhone());
    return attrs;
}

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

/**
 * Sets the set of claims provided at adding users
 *
 * @param claims/* w  ww.j  a va 2  s. co 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:edu.internet2.middleware.psp.ldap.LdapSpmlTarget.java

/** {@inheritDoc} */
public void execute(AddRequest addRequest, AddResponse addResponse) {

    try {//w ww.  ja va  2  s .c  o m
        handleEmptyReferences(addRequest);
    } catch (DSMLProfileException e) {
        fail(addResponse, ErrorCode.CUSTOM_ERROR, e);
        return;
    } catch (PspException e) {
        fail(addResponse, ErrorCode.CUSTOM_ERROR, e);
        return;
    }

    Ldap ldap = null;
    try {
        SortedLdapBeanFactory ldapBeanFactory = new SortedLdapBeanFactory();
        LdapAttributes ldapAttributes = ldapBeanFactory.newLdapAttributes();

        Extensible data = addRequest.getData();

        // data
        Map<String, DSMLAttr> dsmlAttrs = PSPUtil.getDSMLAttrMap(data);
        for (DSMLAttr dsmlAttr : dsmlAttrs.values()) {
            BasicAttribute basicAttribute = new BasicAttribute(dsmlAttr.getName());
            for (DSMLValue dsmlValue : dsmlAttr.getValues()) {
                basicAttribute.add(dsmlValue.getValue());
            }
            LdapAttribute ldapAttribute = ldapBeanFactory.newLdapAttribute();
            ldapAttribute.setAttribute(basicAttribute);
            ldapAttributes.addAttribute(ldapAttribute);
        }

        // references
        Map<String, List<Reference>> references = PSPUtil.getReferences(addRequest.getCapabilityData());
        for (String typeOfReference : references.keySet()) {
            BasicAttribute basicAttribute = new BasicAttribute(typeOfReference);
            for (Reference reference : references.get(typeOfReference)) {
                if (reference.getToPsoID().getTargetID().equals(getId())) {
                    String id = reference.getToPsoID().getID();
                    // fake empty string since the spml toolkit ignores an empty string psoID
                    if (id == null) {
                        id = "";
                    }
                    basicAttribute.add(id);
                }
            }
            LdapAttribute ldapAttribute = ldapBeanFactory.newLdapAttribute();
            ldapAttribute.setAttribute(basicAttribute);
            ldapAttributes.addAttribute(ldapAttribute);
        }

        // create
        // assume the psoID is a DN
        String dn = addRequest.getPsoID().getID();
        String escapedDn = LdapSpmlTarget.escapeForwardSlash(dn);

        ldap = ldapPool.checkOut();

        LOG.debug("Target '{}' - Create '{}'", getId(), PSPUtil.toString(addRequest));
        LOG.debug("Target '{}' - Create DN '{}'", getId(), escapedDn);
        ldap.create(escapedDn, ldapAttributes.toAttributes());
        LOG.info("Target '{}' - Created '{}'", getId(), PSPUtil.toString(addRequest));

        if (this.isLogLdif()) {
            LdapEntry ldapEntry = ldapBeanFactory.newLdapEntry();
            ldapEntry.setDn(dn);
            ldapEntry.setLdapAttributes(ldapAttributes);
            LdapResult result = ldapBeanFactory.newLdapResult();
            result.addEntry(ldapEntry);
            Ldif ldif = new Ldif();
            LOG.info("Target '{}' - LDIF\n{}", getId(), ldif.createLdif(result));
        }

        // response PSO
        if (addRequest.getReturnData().equals(ReturnData.IDENTIFIER)) {
            PSO responsePSO = new PSO();
            responsePSO.setPsoID(addRequest.getPsoID());
            addResponse.setPso(responsePSO);
        } else {
            LookupRequest lookupRequest = new LookupRequest();
            lookupRequest.setPsoID(addRequest.getPsoID());
            lookupRequest.setReturnData(addRequest.getReturnData());

            LookupResponse lookupResponse = this.execute(lookupRequest);
            if (lookupResponse.getStatus() == StatusCode.SUCCESS) {
                addResponse.setPso(lookupResponse.getPso());
            } else {
                fail(addResponse, lookupResponse.getError(), "Unable to lookup object after create.");
            }
        }

    } catch (LdapPoolException e) {
        fail(addResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (NameAlreadyBoundException e) {
        fail(addResponse, ErrorCode.ALREADY_EXISTS, e);
    } catch (NamingException e) {
        fail(addResponse, ErrorCode.CUSTOM_ERROR, e);
    } catch (PspException e) {
        // from PSO.getReferences, an unhandled capability data
        fail(addResponse, ErrorCode.CUSTOM_ERROR, e);
    } finally {
        ldapPool.checkIn(ldap);
    }
}

From source file:org.wso2.carbon.user.core.tenant.CommonHybridLDAPTenantManager.java

/**
 * Create main context corresponding to tenant.
 *
 * @param rootDN            Root domain name.
 * @param orgName           Organization name
 * @param initialDirContext The directory connection.
 * @throws UserStoreException If an error occurred while creating context.
 *///from w w  w. j  av  a2 s.  c  o m
protected void createOrganizationalContext(String rootDN, String orgName, DirContext initialDirContext)
        throws UserStoreException {

    DirContext subContext = null;
    DirContext organizationalContext = null;
    try {

        //get the connection context for rootDN
        subContext = (DirContext) initialDirContext.lookup(rootDN);

        Attributes contextAttributes = new BasicAttributes(true);
        //create organizational object class attribute
        Attribute objectClass = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
        objectClass.add(tenantMgtConfig.getTenantStoreProperties()
                .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_OBJECT_CLASS));
        contextAttributes.put(objectClass);
        //create organizational name attribute
        String organizationalNameAttribute = tenantMgtConfig.getTenantStoreProperties()
                .get(UserCoreConstants.TenantMgtConfig.PROPERTY_ORGANIZATIONAL_ATTRIBUTE);
        Attribute organization = new BasicAttribute(organizationalNameAttribute);
        organization.add(orgName);
        contextAttributes.put(organization);
        //construct organization rdn.
        String rdnOfOrganizationalContext = organizationalNameAttribute + "=" + orgName;
        if (logger.isDebugEnabled()) {
            logger.debug("Adding sub context: " + rdnOfOrganizationalContext + " under " + rootDN + " ...");
        }
        //create organization sub context
        organizationalContext = subContext.createSubcontext(rdnOfOrganizationalContext, contextAttributes);
        if (logger.isDebugEnabled()) {
            logger.debug("Sub context: " + rdnOfOrganizationalContext + " was added under " + rootDN
                    + " successfully.");
        }

    } catch (NamingException e) {
        String errorMsg = "Error occurred while adding the organizational unit " + "sub context.";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMsg, e);
        }
        throw new UserStoreException(errorMsg, e);
    } finally {
        closeContext(organizationalContext);
        closeContext(subContext);
    }
}

From source file:openscim.restful.server.resources.user.ldap.LdapUserResource.java

@Override
public Response createUser(UriInfo uriInfo, User user) {
    // check the ldap template has been setup correctly
    if (ldapTemplate != null) {
        // create the mapper if it doesn't already exists
        if (mapper == null)
            mapper = new UserAttributesMapper(properties);

        // build the user dn
        String dn = user.getId();
        if (properties
                .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                        UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
            // utilise ldap formated dn
            dn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + user.getId() + ","
                    + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN,
                            UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN);
        }/*from w w  w . j  a  v a  2s .c o  m*/

        try {
            try {
                // create the mapper if it doesn't already exists
                if (mapper == null)
                    mapper = new UserAttributesMapper(properties);

                // retrieve the user
                User lookedUser = (User) ldapTemplate.lookup(dn, mapper);

                // check if the user was found
                if (lookedUser != null) {
                    // user already exists            
                    return ResourceUtilities.buildErrorResponse(HttpStatus.CONFLICT,
                            HttpStatus.CONFLICT.getMessage() + ": Resource " + user.getId()
                                    + " already exists");
                }
            } catch (Exception nException) {
                // user not found, do nothing
            }

            Attributes userAttributes = new BasicAttributes();

            // get the objectclasses
            String objectclasses = properties.getProperty(UserAttributesMapper.ACCOUNT_OBJECTCLASS_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_ACCOUNT_OBJECTCLASS_ATTRIBUTE);

            // set the objectclass of the user
            /*
            Attribute objectclassAttribute = new BasicAttribute("objectclass");
            Scanner scanner = new Scanner(objectclasses);            
            scanner.useDelimiter(",");
            while(scanner.hasNext())
            {
               objectclassAttribute.add(scanner.next());
            }
            */

            BasicAttribute objectclassAttribute = new BasicAttribute("objectclass");
            objectclassAttribute.add("inetOrgPerson");
            objectclassAttribute.add("organizationalPerson");
            objectclassAttribute.add("person");
            objectclassAttribute.add("top");
            userAttributes.put(objectclassAttribute);

            // get the uid attribute name
            String uidAtttributeName = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_UID_ATTRIBUTE);

            // set the uid
            userAttributes.put(uidAtttributeName, user.getId());

            // get the display name attribute name
            String displayAtttributeName = properties.getProperty(UserAttributesMapper.DISPLAYNAME_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_DISPLAYNAME_ATTRIBUTE);

            // set the display name
            if (user.getDisplayName() != null)
                userAttributes.put(displayAtttributeName, user.getDisplayName());

            // get the surname attribute name
            String surnameAtttributeName = properties.getProperty(UserAttributesMapper.FAMILYNAME_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_FAMILYNAME_ATTRIBUTE);

            // get the given name attribute name
            String givenAtttributeName = properties.getProperty(UserAttributesMapper.GIVENNAME_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_GIVENNAME_ATTRIBUTE);

            // set the names
            if (user.getName() != null) {
                if (user.getName().getFamilyName() != null)
                    userAttributes.put(surnameAtttributeName, user.getName().getFamilyName());
                if (user.getName().getGivenName() != null)
                    userAttributes.put(givenAtttributeName, user.getName().getGivenName());
            }

            // get the email attribute name
            String mailAtttributeName = properties.getProperty(UserAttributesMapper.MAIL_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_MAIL_ATTRIBUTE);

            // set the emails
            if (user.getEmails() != null) {
                Attribute attribute = new BasicAttribute(mailAtttributeName);
                List<PluralAttribute> emails = user.getEmails().getEmail();
                for (PluralAttribute email : emails) {
                    attribute.add(email.getValue());
                }
                userAttributes.put(attribute);
            }

            // get the telephone attribute name
            String telephoneAtttributeName = properties.getProperty(UserAttributesMapper.TELEPHONE_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_TELEPHONE_ATTRIBUTE);

            // set the telephones
            if (user.getPhoneNumbers() != null) {
                Attribute attribute = new BasicAttribute(telephoneAtttributeName);
                List<PluralAttribute> telephones = user.getPhoneNumbers().getPhoneNumber();
                for (PluralAttribute telephone : telephones) {
                    attribute.add(telephone.getValue());
                }
                userAttributes.put(attribute);
            }

            // get the password attribute name
            String passwordAtttributeName = properties.getProperty(UserAttributesMapper.PASSWORD_ATTRIBUTE,
                    UserAttributesMapper.DEFAULT_PASSWORD_ATTRIBUTE);

            // set the password
            if (user.getPassword() != null)
                userAttributes.put(passwordAtttributeName, user.getPassword());

            // create the user
            ldapTemplate.bind(dn, null, userAttributes);

            // determine the url of the new resource
            URI location = new URI("/User/" + dn);
            if (properties
                    .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                            UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                    .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
                location = new URI("/User/" + user.getId());
            }

            // set the internal id to the dn
            user.setId(dn);
            if (properties
                    .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                            UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                    .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
                user.setId(user.getId());
            }

            // user stored successfully, return the user            
            return Response.created(location).entity(user).build();
        } catch (URISyntaxException usException) {
            // problem generating entity location
            logger.error("problem generating entity location");
            usException.printStackTrace(System.out);

            // return a server error
            return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                    HttpStatus.NOT_IMPLEMENTED.getMessage()
                            + ": Service Provider problem generating entity location");
        } catch (Exception nException) {
            // problem creating user
            logger.error("problem creating user");
            nException.printStackTrace(System.out);

            // return a server error
            return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                    HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider problem creating user");
        }
    } else {
        // ldap not configured
        logger.error("ldap not configured");

        // return a server error
        return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                HttpStatus.NOT_IMPLEMENTED.getMessage()
                        + ": Service Provider user ldap repository not configured");
    }
}

From source file:org.apache.archiva.redback.users.ldap.ctl.DefaultLdapController.java

private void bindUserObject(DirContext context, User user) throws NamingException {
    Attributes attributes = new BasicAttributes(true);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("inetOrgPerson");
    objectClass.add("person");
    objectClass.add("organizationalperson");
    attributes.put(objectClass);//w  w w.  j  a va  2s.  com
    attributes.put("cn", user.getUsername());
    attributes.put("sn", "foo");
    if (StringUtils.isNotEmpty(user.getEmail())) {
        attributes.put("mail", user.getEmail());
    }

    if (userConf.getBoolean(UserConfigurationKeys.LDAP_BIND_AUTHENTICATOR_ALLOW_EMPTY_PASSWORDS, false)
            && StringUtils.isNotEmpty(user.getPassword())) {
        attributes.put("userPassword", passwordEncoder.encodePassword(user.getPassword()));
    }
    attributes.put("givenName", "foo");
    context.createSubcontext("cn=" + user.getUsername() + "," + this.getBaseDn(), attributes);
}

From source file:openscim.restful.server.resources.group.ldap.LdapGroupResource.java

@Override
public Response createGroup(UriInfo uriInfo, Group group) {
    // check the ldap template has been setup correctly
    if (ldapTemplate != null) {
        // create the mapper if it doesn't already exists
        if (mapper == null)
            mapper = new GroupAttributesMapper(properties);

        // build the group dn
        String dn = group.getId();
        if (properties
                .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS,
                        GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)
                .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) {
            // utilise ldap formated dn
            dn = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE) + "=" + group.getId() + ","
                    + properties.getProperty(GroupAttributesMapper.GROUP_BASEDN,
                            GroupAttributesMapper.DEFAULT_GROUP_BASEDN);
        }//from w ww.  jav  a  2  s  .co m

        try {
            try {
                // retrieve the group
                Group lookedGroup = (Group) ldapTemplate.lookup(dn, mapper);

                // check if the group was found
                if (lookedGroup != null) {
                    // user already exists            
                    return ResourceUtilities.buildErrorResponse(HttpStatus.CONFLICT,
                            HttpStatus.CONFLICT.getMessage() + ": Resource " + dn + " already exists");
                }
            } catch (Exception nException) {
                // group not found, do nothing
            }

            Attributes groupAttributes = new BasicAttributes();

            // get the objectclasses
            String objectclasses = properties.getProperty(GroupAttributesMapper.GROUP_OBJECTCLASS_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_GROUP_OBJECTCLASS_ATTRIBUTE);

            // set the objectclass of the group
            Scanner scanner = new Scanner(objectclasses);
            scanner.useDelimiter(",");
            while (scanner.hasNext()) {
                groupAttributes.put("objectclass", scanner.next());
            }

            // set the gid
            String gidAtttributeName = properties.getProperty(GroupAttributesMapper.GID_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_GID_ATTRIBUTE);
            groupAttributes.put(gidAtttributeName, group.getId());

            // get the member attribute name
            String memberAtttributeName = properties.getProperty(GroupAttributesMapper.MEMBER_ATTRIBUTE,
                    GroupAttributesMapper.DEFAULT_MEMBER_ATTRIBUTE);

            // set the members
            Attribute memberAttribute = new BasicAttribute(memberAtttributeName);
            if (group.getAny() instanceof List) {
                List members = (List) group.getAny();
                for (Object object : members) {
                    if (object instanceof PluralAttribute) {
                        PluralAttribute member = (PluralAttribute) object;
                        String uid = member.getValue();

                        // build the user dn
                        String userdn = uid;
                        if (properties.getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS, "true")
                                .equalsIgnoreCase("true")) {
                            // utilise ldap formated dn
                            userdn = properties.getProperty(UserAttributesMapper.UID_ATTRIBUTE,
                                    UserAttributesMapper.DEFAULT_UID_ATTRIBUTE) + "=" + uid + ","
                                    + properties.getProperty(UserAttributesMapper.ACCOUNT_BASEDN,
                                            UserAttributesMapper.DEFAULT_ACCOUNT_BASEDN);
                        }

                        memberAttribute.add(userdn);
                    }
                }
            }
            groupAttributes.put(memberAttribute);

            // create the group
            ldapTemplate.bind(dn, null, groupAttributes);

            // determine the url of the new resource
            URI location = new URI("/Group/" + dn);
            if (properties
                    .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS,
                            GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)
                    .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) {
                location = new URI("/User/" + group.getId());
            }

            // group stored successfully, return the group            
            return Response.created(location).entity(group).build();
        } catch (URISyntaxException usException) {
            // problem generating entity location
            logger.error("problem generating entity location");

            // return a server error
            return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                    HttpStatus.NOT_IMPLEMENTED.getMessage()
                            + ": Service Provider problem generating entity location");
        } catch (Exception nException) {
            // problem creating group
            logger.error("problem creating group");

            // return a server error
            return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                    HttpStatus.NOT_IMPLEMENTED.getMessage() + ": Service Provider problem creating group");
        }
    } else {
        // ldap not configured
        logger.error("ldap not configured");

        // return a server error
        return ResourceUtilities.buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR,
                HttpStatus.NOT_IMPLEMENTED.getMessage()
                        + ": Service Provider group ldap repository not configured");
    }
}

From source file:org.apache.directory.server.operations.bind.MiscBindIT.java

/**
 * Reproduces the problem with//from   w ww  .  jav  a  2 s  .  co m
 * <a href="http://issues.apache.org/jira/browse/DIREVE-239">DIREVE-239</a>.
 *
 * @throws Exception if anything goes wrong
 */
@Test
public void testAdminAccessBug() throws Exception {
    getLdapServer().getDirectoryService().setAllowAnonymousAccess(true);

    // Use the SUN JNDI provider to hit server port and bind as anonymous

    final Hashtable<String, Object> env = new Hashtable<String, Object>();

    env.put(Context.PROVIDER_URL, Network.ldapLoopbackUrl(getLdapServer().getPort()));
    env.put("java.naming.ldap.version", "3");
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    Attributes attributes = new BasicAttributes(true);
    Attribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("top");
    objectClass.add("organizationalUnit");
    attributes.put(objectClass);
    attributes.put("ou", "blah");
    InitialDirContext ctx = new InitialDirContext(env);
    ctx.createSubcontext("ou=blah,ou=system", attributes);
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.OBJECT_SCOPE);
    controls.setReturningAttributes(new String[] { "+" });
    NamingEnumeration<SearchResult> list = ctx.search("ou=blah,ou=system", "(objectClass=*)", controls);
    SearchResult result = list.next();
    list.close();
    Attribute creatorsName = result.getAttributes().get("creatorsName");
    assertEquals("", creatorsName.get());
    ctx.destroySubcontext("ou=blah,ou=system");
}

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);// ww w  .j a v  a 2  s .  com

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

    try {

        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:nl.knaw.dans.common.ldap.repo.LdapMapper.java

private void loadAttribute(Attributes attrs, String attrID, Object value, boolean oneWayEncrypted,
        boolean forUpdate, String encrypted, LdapAttributeValueTranslator translator)
        throws LdapMappingException {
    if (value instanceof Collection) {
        Collection<?> collection = (Collection<?>) value;
        for (Object colValue : collection) {
            loadSingleAttribute(attrs, attrID, colValue, oneWayEncrypted, forUpdate, encrypted, translator);
        }//from  w  w  w .j av  a 2s .co  m
        if (forUpdate && collection.isEmpty()) {
            attrs.put(new BasicAttribute(attrID));
        }
    } else {
        loadSingleAttribute(attrs, attrID, value, oneWayEncrypted, forUpdate, encrypted, translator);
    }
}