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:ldap.Entry.java

/**
 * Utility method - useful for creating a multi valued attributes for the Entry constructor,
 * esp when chained with a bunch of 'makeAtt()' calls.
 * @param vals//from  w w w  .  j av a  2  s  .  co m
 * @return a newly created set of attributes
 */
public static BasicAttributes makeAtts(Attribute[] vals) {
    BasicAttributes atts = new BasicAttributes();
    for (Attribute val : vals)
        atts.put(val);
    return atts;
}

From source file:com.springsource.insight.plugin.ldap.TestLdapContext.java

public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException {
    for (ModificationItem item : mods) {
        BasicAttributes attrs = new BasicAttributes();
        attrs.put(item.getAttribute());
        modifyAttributes(name, item.getModificationOp(), attrs);
    }/* w w  w .j a  va  2s . c o  m*/
}

From source file:net.e2.bw.servicereg.ldap.ServiceInstanceLdapService.java

/** {@inheritDoc} */
@Override/*from   w  ww  .ja v  a2 s .  co m*/
public ServiceInstance createServiceInstance(ServiceInstance service) {
    Objects.requireNonNull(service, "Invalid service instance");
    Objects.requireNonNull(service.getServiceInstanceId(), "Service instance ID must be specified");
    Objects.requireNonNull(service.getOrganizationId(), "Organization ID must be specified");
    Objects.requireNonNull(service.getSpecificationId(), "Service specification ID must be specified");
    Objects.requireNonNull(service.getName(), "Service instance name must be specified");

    CachedServiceInstance existingSpec = getCachedServiceInstance(service.getServiceInstanceId());
    if (existingSpec != null) {
        throw new RuntimeException(
                "A service instance already exists with the ID " + service.getServiceInstanceId());
    }

    BasicAttributes attrs = new BasicAttributes();
    attrs.put(createAttribute("objectClass", getConfig().getServiceInstanceObjectClasses().split(",")));
    attrs.put(createAttribute("cn", service.getName()));
    attrs.put(createAttribute("uid", service.getServiceInstanceId()));
    attrs.put(createAttribute("serviceOrganization", getGroupDN(service.getOrganizationId())));
    attrs.put(createAttribute("serviceSpecification", getServiceSpecificationDN(service.getSpecificationId())));
    if (service.getSummary() != null) {
        attrs.put(createAttribute("description", service.getSummary()));
    }
    byte[] coverage = compressCoverage(service.getCoverage());
    if (coverage != null) {
        attrs.put(createBinaryAttribute("serviceCoverage", coverage));
    }
    if (service.getEndpoints() != null && service.getEndpoints().size() > 0) {
        String[] endpoints = toEndpointArray(service.getEndpoints());
        attrs.put(createAttribute("serviceEndpoint", endpoints));
    }

    // Create the service instance in LDAP
    String serviceDN = getServiceInstanceDN(service.getServiceInstanceId());
    try {
        ldapServerService.addEntry(serviceDN, attrs);
    } catch (NamingException e) {
        log.error("Failed creating service instance " + service.getServiceInstanceId(), e);
        throw new RuntimeException("Failed creating service instance " + service.getServiceInstanceId(), e);
    }

    // Return (and cache) the newly created service instance.
    return getServiceInstance(service.getServiceInstanceId());
}

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

/**
 * Asks the identity provider to provision a new user with the given profile and password.
 *
 * @param user the user to be provisioned
 * @param password the password for the user
 * @throws PortalServiceException for any errors encountered
 */// ww w .j  a v a  2 s  . c om
public void provisionUser(CMSUser user, String password) throws PortalServiceException {
    DirContext ctx = null;
    try {
        ctx = new InitialDirContext(env);
        List<Attribute> profileAttributes = mapAttributes(user);

        // set type
        Attribute oc = new BasicAttribute("objectClass");
        oc.add("top");
        oc.add("person");
        oc.add("organizationalPerson");
        oc.add("inetOrgPerson");

        // build the entry
        BasicAttributes entry = new BasicAttributes();
        for (Attribute attribute : profileAttributes) {
            entry.put(attribute);
        }

        // initial password
        entry.put(new BasicAttribute("userPassword", hash(password)));
        entry.put(oc);

        ctx.createSubcontext(MessageFormat.format(userDNPattern, user.getUsername()), entry);
        synchRoles(user.getUsername(), user.getRole());
    } catch (NamingException e) {
        throw new PortalServiceException("Error while provisioning user.", e);
    } finally {
        closeContext(ctx);
    }
}

From source file:com.globalsight.everest.usermgr.UserLdapHelper.java

/**
 * Convert a User object to an Attributes object
 * /*from ww  w  .j av a  2  s.  co  m*/
 * @param user
 *            The ldap user info.
 * @param needEncodePwd
 *            If user password need to be encoded, set this to true.
 * 
 * @return a Attributes
 */
static Attributes convertUserToLDAPEntry(User user, boolean needEncodePwd) {

    BasicAttributes attrSet = new BasicAttributes();
    Attribute objClass = new BasicAttribute(LDAP_ATTR_OBJECT_CLASS);
    objClass.add(LDAP_USER_OBJECT_CLASSES[0]);
    objClass.add(LDAP_USER_OBJECT_CLASSES[1]);
    objClass.add(LDAP_USER_OBJECT_CLASSES[2]);
    objClass.add(LDAP_USER_OBJECT_CLASSES[3]);
    objClass.add(LDAP_USER_OBJECT_CLASSES[4]);
    // add each LDAP attribute
    attrSet.put(objClass);
    if (isStringValid(user.getUserId())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_USERID, user.getUserId()));
    }
    if (isStringValid(user.getUserName())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_USER_NAME, user.getUserName()));
    }
    if (isStringValid(user.getTitle())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_TITLE, user.getTitle()));
    }
    if (isStringValid(user.getLastName())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_LAST_NAME, user.getLastName()));
    }
    if (isStringValid(user.getFirstName())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_FIRST_NAME, user.getFirstName()));
    }

    String status = getStateAsString(user.getState());
    attrSet.put(generateLDAPAttribute(LDAP_ATTR_STATUS, status));

    if (isStringValid(user.getPassword())) {
        if (needEncodePwd) {
            attrSet.put(generateLDAPAttribute(LDAP_ATTR_PASSWORD, encyptMD5Password(user.getPassword())));
        } else {
            attrSet.put(generateLDAPAttribute(LDAP_ATTR_PASSWORD, user.getPassword()));
        }
    }

    if (isStringValid(user.getEmail())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_EMAIL, user.getEmail()));
    }
    if (isStringValid(user.getCCEmail())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_CC_EMAIL, user.getCCEmail()));
    }
    if (isStringValid(user.getBCCEmail())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_BCC_EMAIL, user.getBCCEmail()));
    }
    if (isStringValid(user.getHomePhoneNumber())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_HOME_PHONE, user.getHomePhoneNumber()));
    }
    if (isStringValid(user.getOfficePhoneNumber())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_OFFICE_PHONE, user.getOfficePhoneNumber()));
    }
    if (isStringValid(user.getFaxPhoneNumber())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_FAX_NUMBER, user.getFaxPhoneNumber()));
    }
    if (isStringValid(user.getCellPhoneNumber())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_CELL_NUMBER, user.getCellPhoneNumber()));
    }
    if (isStringValid(user.getDefaultUILocale())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_DEFAULT_UI_LOCALE, user.getDefaultUILocale()));
    }
    if (isStringValid(user.getAddress()))
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_ADDRESS, user.getAddress()));
    if (isStringValid(user.getCompanyName())) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_COMPANY, user.getCompanyName()));
    }
    // vonverts 'boolean' to corresponding 'String' because openldap
    // 'Attribute' need string parameter.
    attrSet.put(generateLDAPAttribute(LDAP_ATTR_INALLPROJECTS, user.isInAllProjects()));
    // if anonymous then write it out - otherwise just leave NULL
    if (user.getType() == User.UserType.ANONYMOUS) {
        attrSet.put(generateLDAPAttribute(LDAP_ATTR_TYPE, LDAP_ANONYMOUS_USER_TYPE));
    }

    return attrSet;
}

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

/**
 * set attributes of given resource./*from   w w w .j av  a  2s.  c  o m*/
 * 
 * @param scope
 *            scope
 * @param id
 *            id of resource
 * @param attributeNames
 *            attribute-names and values to set
 * 
 * @throws NamingException
 * @throws IllegalAccessException
 */
public void setResourceAttributes(Scope scope, String entryDn, Map<String, String> attributes)
        throws NamingException, IllegalAccessException {
    InitialLdapContext ctx = null;
    try {
        ctx = LDAPConnector.getSingletonInstance().takeCtx();
        BasicAttributes saveAttributes = new BasicAttributes(true);
        for (Entry<String, String> entry : attributes.entrySet()) {
            saveAttributes.put(new BasicAttribute(entry.getKey(), entry.getValue()));
        }
        ctx.modifyAttributes(entryDn, DirContext.REPLACE_ATTRIBUTE, saveAttributes);
    } finally {
        if (ctx != null) {
            try {
                LDAPConnector.getSingletonInstance().putCtx(ctx);
            } catch (IllegalAccessException ex) {
                LOG.log(Level.SEVERE, null, ex);
            }
        }
    }
}

From source file:ldap.ActiveLoginImpl.java

/**
 * This does a light copy of an attributes list (such as a UserAccount, if we need to modify it but
 * want to keep the original userAccount)
 * @param oldAtts/*from  w  w w .j  a  v a2  s.c om*/
 * @return a light copy of the original attributes list.
 */
public Attributes copyAttributes(Attributes oldAtts) {
    BasicAttributes atts = new BasicAttributes();
    NamingEnumeration attList = oldAtts.getAll();
    while (attList.hasMoreElements()) // shouldn't throw an exception, so use normal enumeration methods
    {
        Attribute att = (Attribute) attList.nextElement();
        atts.put(att);
    }
    return atts;
}

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  a  v a  2s  .  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 + ") 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 {/*from w  w  w. j a v a  2 s. c o 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.jamwiki.ldap.LdapUserHandler.java

/**
 *
 *//*from  w ww.  ja va 2  s.c  o m*/
public WikiUserInfo lookupWikiUserInfo(String username) throws Exception {
    InitialDirContext ctx = null;
    try {
        ctx = getContext(Environment.getValue(Environment.PROP_LDAP_LOGIN),
                Encryption.getEncryptedProperty(Environment.PROP_LDAP_PASSWORD, null));
        BasicAttributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Environment.getValue(Environment.PROP_LDAP_FIELD_USERID), username));
        NamingEnumeration answer = ctx.search(Environment.getValue(Environment.PROP_LDAP_CONTEXT), matchAttrs,
                SEARCH_ATTRIBUTES);
        return (!answer.hasMore()) ? null : this.initWikiUserInfo(answer);
    } finally {
        try {
            ctx.close();
        } catch (Exception e) {
        }
    }
}