Example usage for javax.naming.directory BasicAttributes BasicAttributes

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

Introduction

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

Prototype

public BasicAttributes(boolean ignoreCase) 

Source Link

Document

Constructs a new instance of Attributes.

Usage

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

private final ByteBuffer processRequest(LdapMessage request, boolean utf8) throws Exception {
    if (log.isDebugEnabled()) {
        try {/*from w ww  . j  ava 2  s  .  c  om*/
            String command = request.getMessageTypeName();
            if (command != null) {
                command = command.toLowerCase().replace('_', ' ');
            }
            log.debug("Processing " + command + "...");
        } catch (Exception ignored) {
            log.warn("Processing unknown LDAP request...");
        }
    }
    LinkedList list = new LinkedList();
    switch (request.getMessageType()) {
    case LdapConstants.BIND_REQUEST:

        // Bind response
        BindResponse bind = new BindResponse();
        bind.setMessageId(request.getMessageId());
        LdapResult result = new LdapResult();
        result.setResultCode(0);
        bind.setLdapResult(result);
        list.addLast(bind);
        break;

    case LdapConstants.UNBIND_REQUEST:

        // Unbind response
        LdapResponse unbind = new LdapResponse();
        unbind.setMessageId(request.getMessageId());
        result = new LdapResult();
        result.setResultCode(0);
        unbind.setLdapResult(result);
        list.addLast(unbind);
        break;

    case LdapConstants.SEARCH_REQUEST:

        // Switch back encoding
        if (nativeCharsetLocked) {
            utf8 = false;
        }

        // Get search string
        SearchRequest search = request.getSearchRequest();
        Filter filter = search.getTerminalFilter();
        String key = null;
        if (filter == null) {
            filter = search.getFilter();
            if (filter == null) {
                filter = search.getCurrentFilter();
            }
        }
        if (filter != null) {
            if (filter instanceof SubstringFilter) {
                SubstringFilter substringFilter = (SubstringFilter) filter;
                ArrayList substrings = substringFilter.getAnySubstrings();
                if (substrings != null && substrings.size() != 0) {
                    key = (String) substrings.get(0);
                }
            }
            if (key == null) {
                key = filter.toString();
                if (key != null) {
                    if (key.charAt(0) == '*') {
                        key = key.substring(1);
                    }
                    if (key.charAt(key.length() - 1) == '*') {
                        key = key.substring(0, key.length() - 1);
                    }
                    if (key.indexOf('=') != -1) {
                        key = key.substring(key.indexOf('=') + 1);
                    }
                }
            }
            if (key != null) {
                if (key.length() == 0) {
                    key = null;
                } else {

                    // Decode UTF8 chars
                    try {
                        byte[] bytes = key.getBytes(PLATFORM_ENCODING);
                        key = StringUtils.decodeToString(bytes, StringUtils.UTF_8);
                        if (utf8) {
                            bytes = key.getBytes(PLATFORM_ENCODING);
                            key = StringUtils.decodeToString(bytes, StringUtils.UTF_8);
                        }
                    } catch (Exception ignored) {
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("LDAP search filter (" + key + ") readed.");
                    }
                    key = key.toLowerCase();

                    // All contacts requested
                    if (key.equals("@")) {
                        key = null;
                    }
                }
            }
        }

        // Handle native charset lock
        if (key != null && !utf8) {
            nativeCharsetLocked = true;
        }

        // Find entry
        GmailContact[] contacts = loader.getContacts();
        if (contacts != null) {
            GmailContact contact;
            for (int n = 0; n < contacts.length; n++) {
                contact = contacts[n];
                if (key != null && contact.name.toLowerCase().indexOf(key) == -1) {
                    continue;
                }

                // Add search entry
                SearchResultEntry entry = new SearchResultEntry();
                entry.setMessageId(request.getMessageId());
                LdapDN name;
                try {
                    name = new LdapDN("CN=" + encode(contact.name, utf8));
                } catch (Exception badDN) {
                    log.debug(badDN);
                    continue;
                }
                entry.setObjectName(name);

                BasicAttributes partialAttributeList = new BasicAttributes(true);
                partialAttributeList.put(new BasicAttribute("cn", encode(contact.name, utf8)));
                if (contact.email.length() != 0) {

                    // first email
                    partialAttributeList.put(new BasicAttribute("mail", encode(contact.email, utf8)));
                }
                if (contact.notes.length() != 0) {

                    // notes
                    partialAttributeList.put(new BasicAttribute("comment", encode(contact.notes, utf8)));
                    partialAttributeList.put(new BasicAttribute("description", encode(contact.notes, utf8)));
                }
                String mobile = contact.mobile;
                if (mobile.length() == 0) {
                    mobile = contact.phone;
                }
                if (mobile.length() != 0) {

                    // mobile phone
                    partialAttributeList.put(new BasicAttribute("telephonenumber", encode(mobile, utf8)));
                }
                if (contact.phone.length() != 0) {

                    // homePhone
                    partialAttributeList.put(new BasicAttribute("homePhone", encode(contact.phone, utf8)));
                }
                if (contact.mail.length() != 0) {

                    // second email
                    partialAttributeList
                            .put(new BasicAttribute("mozillaSecondEmail", encode(contact.mail, utf8)));
                    partialAttributeList
                            .put(new BasicAttribute("mailAlternateAddress", encode(contact.mail, utf8)));
                }
                if (contact.address.length() != 0) {

                    // postal address
                    partialAttributeList
                            .put(new BasicAttribute("postalAddress", encode(contact.address, utf8)));
                    partialAttributeList
                            .put(new BasicAttribute("homePostalAddress", encode(contact.address, utf8)));
                    partialAttributeList.put(new BasicAttribute("homeStreet", encode(contact.address, utf8)));
                }
                if (contact.pager.length() != 0) {

                    // pager
                    partialAttributeList.put(new BasicAttribute("pager", encode(contact.pager, utf8)));
                }
                if (contact.fax.length() != 0) {

                    // fax
                    partialAttributeList
                            .put(new BasicAttribute("facsimileTelephoneNumber", encode(contact.fax, utf8)));
                    if (contact.pager.length() == 0) {
                        partialAttributeList.put(new BasicAttribute("pager", encode(contact.fax, utf8)));
                    }
                }
                if (contact.title.length() != 0) {

                    // title
                    partialAttributeList.put(new BasicAttribute("title", encode(contact.title, utf8)));
                }
                if (contact.company.length() != 0) {

                    // company
                    partialAttributeList.put(new BasicAttribute("company", encode(contact.company, utf8)));
                    partialAttributeList.put(new BasicAttribute("o", encode(contact.company, utf8)));
                }
                entry.setPartialAttributeList(partialAttributeList);
                list.addLast(entry);
            }
        }

        // Search done
        if (log.isDebugEnabled()) {
            log.debug("Found " + list.size() + " contacts.");
        }
        SearchResultDone done = new SearchResultDone();
        done.setMessageId(request.getMessageId());
        result = new LdapResult();
        result.setResultCode(0);
        done.setLdapResult(result);
        list.addLast(done);
        break;

    case LdapConstants.ABANDON_REQUEST:

        // Abandon command
        result = new LdapResult();
        result.setResultCode(0);
        LdapResponse response = new LdapResponse();
        response.setLdapResult(result);
        list.addLast(response);
        break;

    default:

        // Unsupported command
        log.debug("Unsupported LDAP command!");
        result = new LdapResult();
        result.setErrorMessage("Unsupported LDAP command!");
        response = new LdapResponse();
        response.setLdapResult(result);
        list.addLast(response);
    }
    log.debug("LDAP request processed.");
    if (!list.isEmpty()) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Iterator responses = list.iterator();
        while (responses.hasNext()) {
            LdapMessage response = (LdapMessage) responses.next();
            response.setMessageId(request.getMessageId());

            // Append LDAP response
            LdapMessage message = new LdapMessage();
            message.setProtocolOP(response);
            message.setMessageId(request.getMessageId());
            ByteBuffer bb = message.encode(null);
            byte[] a = bb.array();
            out.write(a);
        }
        byte[] bytes = out.toByteArray();
        return ByteBuffer.wrap(bytes);
    }
    return null;
}

From source file:org.gldapdaemon.core.ldap.LDAPListener.java

private final ByteBuffer processRequest(LdapMessage request, boolean utf8) throws Exception {
    if (log.isDebugEnabled()) {
        try {// w  ww.  ja  v  a2s .  co m
            String command = request.getMessageTypeName();
            if (command != null) {
                command = command.toLowerCase().replace('_', ' ');
            }
            log.debug("Processing " + command + "...");
        } catch (Exception ignored) {
            log.warn("Processing unknown LDAP request...");
        }
    }
    LinkedList list = new LinkedList();
    switch (request.getMessageType()) {
    case LdapConstants.BIND_REQUEST:

        // Bind response
        BindResponse bind = new BindResponse();
        bind.setMessageId(request.getMessageId());
        LdapResult result = new LdapResult();
        result.setResultCode(0);
        bind.setLdapResult(result);
        list.addLast(bind);
        break;

    case LdapConstants.UNBIND_REQUEST:

        // Unbind response
        LdapResponse unbind = new LdapResponse();
        unbind.setMessageId(request.getMessageId());
        result = new LdapResult();
        result.setResultCode(0);
        unbind.setLdapResult(result);
        list.addLast(unbind);
        break;

    case LdapConstants.SEARCH_REQUEST:

        // Switch back encoding
        if (nativeCharsetLocked) {
            utf8 = false;
        }

        // Get search string
        SearchRequest search = request.getSearchRequest();
        Filter filter = search.getTerminalFilter();
        String key = null;
        if (filter == null) {
            filter = search.getFilter();
            if (filter == null) {
                filter = search.getCurrentFilter();
            }
        }
        if (filter != null) {
            if (filter instanceof SubstringFilter) {
                SubstringFilter substringFilter = (SubstringFilter) filter;
                ArrayList substrings = substringFilter.getAnySubstrings();
                if (substrings != null && substrings.size() != 0) {
                    key = (String) substrings.get(0);
                }
            }
            if (key == null) {
                key = filter.toString();
                if (key != null) {
                    if (key.charAt(0) == '*') {
                        key = key.substring(1);
                    }
                    if (key.charAt(key.length() - 1) == '*') {
                        key = key.substring(0, key.length() - 1);
                    }
                    if (key.indexOf('=') != -1) {
                        key = key.substring(key.indexOf('=') + 1);
                    }
                }
            }
            if (key != null) {
                if (key.length() == 0) {
                    key = null;
                } else {

                    // Decode UTF8 chars
                    try {
                        byte[] bytes = key.getBytes(PLATFORM_ENCODING);
                        key = StringUtils.decodeToString(bytes, StringUtils.UTF_8);
                        if (utf8) {
                            bytes = key.getBytes(PLATFORM_ENCODING);
                            key = StringUtils.decodeToString(bytes, StringUtils.UTF_8);
                        }
                    } catch (Exception ignored) {
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("LDAP search filter (" + key + ") received.");
                    }
                    key = key.toLowerCase();

                    // All contacts requested
                    if (key.equals("@")) {
                        key = null;
                    }
                }
            }
        }

        // Handle native charset lock
        if (key != null && !utf8) {
            nativeCharsetLocked = true;
        }

        // Find entry
        ArrayList<GmailContact> contacts = loader.getContacts();
        if (contacts != null) {
            GmailContact contact;
            for (int n = 0; n < contacts.size(); n++) {
                contact = contacts.get(n);
                String value = null;
                if (contact.name.toLowerCase().indexOf(key) >= 0
                        || contact.company.toLowerCase().indexOf(key) >= 0) {
                    value = contact.name.length() > 0 ? contact.name : contact.company;
                } else if (key != null) {
                    continue;
                }

                // Add search entry
                SearchResultEntry entry = new SearchResultEntry();
                entry.setMessageId(request.getMessageId());
                LdapDN name;
                try {
                    name = new LdapDN("CN=" + encode(value, utf8));
                } catch (Exception badDN) {
                    log.debug(badDN);
                    continue;
                }
                entry.setObjectName(name);

                BasicAttributes partialAttributeList = new BasicAttributes(true);
                partialAttributeList.put(new BasicAttribute("cn", encode(value, utf8)));
                if (contact.email.length() != 0) {
                    // first email
                    partialAttributeList.put(new BasicAttribute("mail", encode(contact.email, utf8)));
                }
                if (contact.notes.length() != 0) {
                    // notes
                    partialAttributeList.put(new BasicAttribute("comment", encode(contact.notes, utf8)));
                    partialAttributeList.put(new BasicAttribute("description", encode(contact.notes, utf8)));
                }
                String mobile = contact.mobile;
                if (mobile.length() == 0) {
                    mobile = contact.phone;
                }
                if (mobile.length() != 0) {
                    // mobile phone
                    partialAttributeList.put(new BasicAttribute("telephonenumber", encode(mobile, utf8)));
                }
                if (contact.phone.length() != 0) {

                    // homePhone
                    partialAttributeList.put(new BasicAttribute("homePhone", encode(contact.phone, utf8)));
                }
                if (contact.mail.length() != 0) {

                    // second email
                    partialAttributeList
                            .put(new BasicAttribute("mozillaSecondEmail", encode(contact.mail, utf8)));
                    partialAttributeList
                            .put(new BasicAttribute("mailAlternateAddress", encode(contact.mail, utf8)));
                }
                if (contact.address.length() != 0) {

                    // postal address
                    partialAttributeList
                            .put(new BasicAttribute("postalAddress", encode(contact.address, utf8)));
                    partialAttributeList
                            .put(new BasicAttribute("homePostalAddress", encode(contact.address, utf8)));
                    partialAttributeList.put(new BasicAttribute("homeStreet", encode(contact.address, utf8)));
                }
                if (contact.pager.length() != 0) {

                    // pager
                    partialAttributeList.put(new BasicAttribute("pager", encode(contact.pager, utf8)));
                }
                if (contact.fax.length() != 0) {

                    // fax
                    partialAttributeList
                            .put(new BasicAttribute("facsimileTelephoneNumber", encode(contact.fax, utf8)));
                    if (contact.pager.length() == 0) {
                        partialAttributeList.put(new BasicAttribute("pager", encode(contact.fax, utf8)));
                    }
                }
                if (contact.title.length() != 0) {

                    // title
                    partialAttributeList.put(new BasicAttribute("title", encode(contact.title, utf8)));
                }
                if (contact.company.length() != 0) {

                    // company
                    partialAttributeList.put(new BasicAttribute("company", encode(contact.company, utf8)));
                    partialAttributeList.put(new BasicAttribute("o", encode(contact.company, utf8)));
                }
                entry.setPartialAttributeList(partialAttributeList);
                list.addLast(entry);
            }
        }

        // Search done
        if (log.isDebugEnabled()) {
            log.debug("Found " + list.size() + " contacts.");
        }
        SearchResultDone done = new SearchResultDone();
        done.setMessageId(request.getMessageId());
        result = new LdapResult();
        result.setResultCode(0);
        done.setLdapResult(result);
        list.addLast(done);
        break;

    case LdapConstants.ABANDON_REQUEST:

        // Abandon command
        result = new LdapResult();
        result.setResultCode(0);
        LdapResponse response = new LdapResponse();
        response.setLdapResult(result);
        list.addLast(response);
        break;

    default:

        // Unsupported command
        log.debug("Unsupported LDAP command!");
        result = new LdapResult();
        result.setErrorMessage("Unsupported LDAP command!");
        response = new LdapResponse();
        response.setLdapResult(result);
        list.addLast(response);
    }
    log.debug("LDAP request processed.");
    if (!list.isEmpty()) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Iterator responses = list.iterator();
        while (responses.hasNext()) {
            LdapMessage response = (LdapMessage) responses.next();
            response.setMessageId(request.getMessageId());

            // Append LDAP response
            LdapMessage message = new LdapMessage();
            message.setProtocolOP(response);
            message.setMessageId(request.getMessageId());
            ByteBuffer bb = message.encode(null);
            byte[] a = bb.array();
            out.write(a);
        }
        byte[] bytes = out.toByteArray();
        return ByteBuffer.wrap(bytes);
    }
    return null;
}

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

@Deprecated
protected void createAdminGroup(String dnOfGroupContext, String adminUserDN, DirContext initialDirContext)
        throws UserStoreException {
    //create set of attributes required to create admin group
    Attributes adminGroupAttributes = new BasicAttributes(true);
    //admin entry object class
    Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
    objectClassAttribute.add(realmConfig.getUserStoreProperty(LDAPConstants.GROUP_ENTRY_OBJECT_CLASS));
    adminGroupAttributes.put(objectClassAttribute);

    //group name attribute
    String groupNameAttributeName = realmConfig.getUserStoreProperty(LDAPConstants.GROUP_NAME_ATTRIBUTE);
    Attribute groupNameAttribute = new BasicAttribute(groupNameAttributeName);
    String adminRoleName = realmConfig.getAdminRoleName();
    groupNameAttribute.add(UserCoreUtil.removeDomainFromName(adminRoleName));
    adminGroupAttributes.put(groupNameAttribute);

    //membership attribute
    Attribute membershipAttribute = new BasicAttribute(
            realmConfig.getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE));
    membershipAttribute.add(adminUserDN);
    adminGroupAttributes.put(membershipAttribute);

    DirContext groupContext = null;
    try {/*from   w  w  w . j  av a 2  s . c  om*/
        groupContext = (DirContext) initialDirContext.lookup(dnOfGroupContext);
        String rdnOfAdminGroup = groupNameAttributeName + "="
                + UserCoreUtil.removeDomainFromName(adminRoleName);
        groupContext.bind(rdnOfAdminGroup, null, adminGroupAttributes);

    } catch (NamingException e) {
        String errorMessage = "Error occurred while creating the admin group.";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        closeContext(groupContext);
    }
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get the LDAP DN for a user./*w  w  w  . ja  v a 2s  . c  om*/
 * @param searchUser
 * @param searchPassword
 * @param userName
 * @return
 */
@SuppressWarnings("unchecked")
private static String getDN(String searchUser, String searchPassword, String userName) {
    // The resultant DN
    String result;

    // Set up environment for creating initial context
    Hashtable env = new Hashtable(11);
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL);

    // Use admin credencials for search// Authenticate
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser);
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword);

    DirContext ctx = null;
    try {
        // Create initial context
        ctx = new InitialDirContext(env);
        //MetaDbHelper.note("Created LDAP context");

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName));
        //MetaDbHelper.note("Created attributes");

        // look up attributes
        try {
            //MetaDbHelper.note("Setting up query");

            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(Global.LDAP_SCOPE);

            NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT,
                    "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls);

            //MetaDbHelper.note("NamingEnumeration retrieved");

            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) {
                    result = sr.getName();
                } else {
                    result = (sr.getName() + "," + Global.LDAP_CONTEXT);
                }

                //MetaDbHelper.note("Got DN: "+result);

                return result;
            }
        } catch (NamingException e) {
            MetaDbHelper.logEvent(e);
            //MetaDbHelper.note("LDAP Error: Failed Search");
        }
    } catch (NamingException e) {
        MetaDbHelper.logEvent(e);
        //MetaDbHelper.note("LDAP Error: Failed authentication");
    } finally {
        // Close the context when we're done
        try {
            if (ctx != null)
                ctx.close();
        } catch (NamingException e) {
        }
    }
    // No DN match found
    return null;
}

From source file:org.apache.jmeter.protocol.ldap.sampler.LDAPExtSampler.java

/***************************************************************************
 * Collect all the values from the table (Arguments), using this create the
 * Attributes, this will create the Attributes for the User
 * defined TestCase for Add Test/*from ww  w.ja  v  a2s .  c o m*/
 *
 * @return The Attributes
 **************************************************************************/
private Attributes getUserAttributes() {
    Attributes attrs = new BasicAttributes(true);
    Attribute attr;

    for (JMeterProperty jMeterProperty : getArguments()) {
        Argument item = (Argument) jMeterProperty.getObjectValue();
        attr = attrs.get(item.getName());
        if (attr == null) {
            attr = getBasicAttribute(item.getName(), item.getValue());
        } else {
            attr.add(item.getValue());
        }
        attrs.put(attr);
    }
    return attrs;
}

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

public void addSharedGroupForTenant(Tenant tenant, DirContext mainDirContext) throws UserStoreException {

    if (!isSharedGroupEnabled()) {
        return;/*w  w  w  .j  a  v  a 2s  . c  o  m*/
    }
    Attributes groupAttributes = new BasicAttributes(true);

    String domainName = tenant.getDomain();
    // create ou attribute
    String groupNameAttributeName = realmConfig
            .getUserStoreProperty(LDAPConstants.SHARED_TENANT_NAME_ATTRIBUTE);

    // create group entry's object class attribute
    Attribute objectClassAttribute = new BasicAttribute(LDAPConstants.OBJECT_CLASS_NAME);
    objectClassAttribute.add(realmConfig.getUserStoreProperty(LDAPConstants.SHARED_TENANT_OBJECT_CLASS));
    groupAttributes.put(objectClassAttribute);

    DirContext groupContext = null;

    String searchBase = realmConfig.getUserStoreProperties().get(LDAPConstants.SHARED_GROUP_SEARCH_BASE);

    try {
        groupContext = (DirContext) mainDirContext.lookup(searchBase);
        NameParser ldapParser = groupContext.getNameParser("");
        Name compoundGroupName = ldapParser.parse(groupNameAttributeName + "=" + domainName);
        groupContext.bind(compoundGroupName, null, groupAttributes);

    } catch (Exception e) {
        String errorMsg = "Shared tenant: " + domainName + "could not be added.";
        if (logger.isDebugEnabled()) {
            logger.debug(errorMsg, e);
        }
        throw new UserStoreException(errorMsg, e);
    } finally {
        JNDIUtil.closeContext(groupContext);
    }

}

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 v  a2s .  c  o m
 * @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:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

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

    DirContext dirContext;/*  w  ww. 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.mule.module.ldap.api.jndi.LDAPJNDIConnection.java

/**
 * @param attrs/*ww w .jav  a 2  s. c o m*/
 * @return
 * @throws LDAPException
 */
private Attributes buildAttributes(LDAPEntryAttributes attrs) throws LDAPException {
    Attributes attributes = new BasicAttributes(IGNORE_CASE);

    for (Iterator<LDAPEntryAttribute> it = attrs.attributes(); it.hasNext();) {
        attributes.put(buildBasicAttribute((LDAPEntryAttribute) it.next()));
    }

    return attributes;
}

From source file:org.springframework.ldap.core.DirContextAdapter.java

public void update() {
    NamingEnumeration attributesEnumeration = null;

    try {/*from  ww  w.j  a v a 2 s  . co  m*/
        attributesEnumeration = updatedAttrs.getAll();

        // find what to update
        while (attributesEnumeration.hasMore()) {
            Attribute a = (Attribute) attributesEnumeration.next();

            // if it does not exist it should be added
            if (isEmptyAttribute(a)) {
                originalAttrs.remove(a.getID());
            } else {
                // Otherwise it should be set.
                originalAttrs.put(a);
            }
        }
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        closeNamingEnumeration(attributesEnumeration);
    }

    // Reset the attributes to be updated
    updatedAttrs = new BasicAttributes(true);
}