Example usage for javax.naming.directory Attribute get

List of usage examples for javax.naming.directory Attribute get

Introduction

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

Prototype

Object get() throws NamingException;

Source Link

Document

Retrieves one of this attribute's values.

Usage

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void getGroups(UserGroupSink sink) throws Throwable {
    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    long highestdeltaSyncGroupTime = deltaSyncGroupTime;
    try {//  w w  w . j ava 2 s  .co m
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        extendedGroupSearchFilter = "(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            extendedGroupSearchFilter = extendedGroupSearchFilter + customFilter;
        }

        extendedAllGroupsSearchFilter = "(&" + extendedGroupSearchFilter + "(|(uSNChanged>="
                + deltaSyncGroupTime + ")(modifyTimestamp>=" + deltaSyncGroupTimeStamp + "Z)))";

        LOG.info("extendedAllGroupsSearchFilter = " + extendedAllGroupsSearchFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                int paged = 0;
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou],
                            extendedAllGroupsSearchFilter, groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry "
                                        + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        String gName = (String) groupNameAttr.get();
                        String transformGroupName = groupNameTransform(gName);
                        // If group based search is enabled, then
                        // update the group name to ranger admin
                        // check for group members and populate userInfo object with user's full name and group mapping
                        if (groupSearchFirstEnabled) {
                            LOG.debug("Update Ranger admin with " + transformGroupName);
                            sink.addOrUpdateGroup(transformGroupName);
                        }
                        Attribute timeStampAttr = groupEntry.getAttributes().get("uSNChanged");
                        if (timeStampAttr != null) {
                            String uSNChangedVal = (String) timeStampAttr.get();
                            long currentDeltaSyncTime = Long.parseLong(uSNChangedVal);
                            if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                highestdeltaSyncGroupTime = currentDeltaSyncTime;
                            }
                        } else {
                            timeStampAttr = groupEntry.getAttributes().get("modifytimestamp");
                            if (timeStampAttr != null) {
                                String timeStampVal = (String) timeStampAttr.get();
                                Date parseDate = dateFormat.parse(timeStampVal);
                                long currentDeltaSyncTime = parseDate.getTime();
                                LOG.info("timeStampVal = " + timeStampVal + "and currentDeltaSyncTime = "
                                        + currentDeltaSyncTime);
                                if (currentDeltaSyncTime > highestdeltaSyncGroupTime) {
                                    highestdeltaSyncGroupTime = currentDeltaSyncTime;
                                    deltaSyncGroupTimeStamp = timeStampVal;
                                }
                            }
                        }
                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }

                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            String userName = getShortUserName(originalUserFullName);
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (groupSearchFirstEnabled && !userSearchEnabled) {
                                String transformUserName = userNameTransform(userName);
                                try {
                                    sink.addOrUpdateUser(transformUserName);
                                } catch (Throwable t) {
                                    LOG.error("sink.addOrUpdateUser failed with exception: " + t.getMessage()
                                            + ", for user: " + transformUserName);
                                }
                                userNameMap.put(originalUserFullName, transformUserName);
                            }
                            //System.out.println("Adding " + userNameMap.get(originalUserFullName) + " and fullname = " + originalUserFullName + " to " + gName);
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName,
                                        userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        LOG.debug(String.format("Fetched paged results round: %s", ++paged));
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() completed with group count: " + counter);
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.getGroups() failed with exception: " + t);
                LOG.info("LdapDeltaUserGroupBuilder.getGroups() group count: " + counter);
            }
        }

    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }

    if (groupHierarchyLevels > 0) {
        LOG.debug("deltaSyncGroupTime = " + deltaSyncGroupTime);
        if (deltaSyncGroupTime > 0) {
            LOG.info(
                    "LdapDeltaUserGroupBuilder.getGroups(): Going through group hierarchy for nested group evaluation for deltasync");
            goUpGroupHierarchyLdap(groupNameMap.keySet(), groupHierarchyLevels - 1);
        }
    }

    if (deltaSyncGroupTime < highestdeltaSyncGroupTime) {
        // Incrementing highestdeltaSyncGroupTime (for AD) in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTime = highestdeltaSyncGroupTime + 1;
        // Incrementing the highest timestamp value (for OpenLdap) with 1min in order to avoid search record repetition for next sync cycle.
        deltaSyncGroupTimeStamp = dateFormat.format(new Date(highestdeltaSyncGroupTime + 60000l));
    }
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java

protected UidNodeDescription mapToNode(final SearchResult searchResult, final String idAttributeName,
        final Map<String, String> attributeMapping, final Map<String, String> attributeDefaults)
        throws NamingException {
    final Attributes attributes = searchResult.getAttributes();
    final Collection<String> uidValues = this.mapAttribute(attributes.get(idAttributeName), String.class);
    final String uid = uidValues.iterator().next();

    final UidNodeDescription nodeDescription = new UidNodeDescription(searchResult.getNameInNamespace(), uid);

    final Attribute modifyTimestamp = attributes.get(this.modifyTimestampAttributeName);
    if (modifyTimestamp != null) {
        try {/*ww  w  .  j ava2s  .com*/
            nodeDescription.setLastModified(this.timestampFormat.parse(modifyTimestamp.get().toString()));
            LOGGER.debug("Setting last modified of node {} to {}", uid, nodeDescription.getLastModified());
        } catch (final ParseException e) {
            throw new AlfrescoRuntimeException("Failed to parse timestamp.", e);
        }
    }

    final PropertyMap properties = nodeDescription.getProperties();
    for (final String key : attributeMapping.keySet()) {
        final QName keyQName = QName.createQName(key, this.namespaceService);

        final String attributeName = attributeMapping.get(key);
        if (attributeName != null) {
            final Attribute attribute = attributes.get(attributeName);
            final String defaultAttribute = attributeDefaults.get(key);

            if (attribute != null) {
                final Collection<Object> mappedAttributeValue = this.mapAttribute(attribute);
                if (mappedAttributeValue.size() == 1) {
                    final Object singleValue = mappedAttributeValue.iterator().next();
                    if (singleValue instanceof Serializable) {
                        properties.put(keyQName, (Serializable) singleValue);
                    } else {
                        properties.put(keyQName,
                                DefaultTypeConverter.INSTANCE.convert(String.class, singleValue));
                    }
                } else if (!mappedAttributeValue.isEmpty()) {
                    final ArrayList<Serializable> values = new ArrayList<>();
                    mappedAttributeValue.forEach((x) -> {
                        if (x instanceof Serializable) {
                            values.add((Serializable) x);
                        } else {
                            values.add(DefaultTypeConverter.INSTANCE.convert(String.class, x));
                        }
                    });
                    properties.put(keyQName, values);
                } else if (defaultAttribute != null) {
                    properties.put(keyQName, defaultAttribute);
                } else {
                    // Make sure that a 2nd sync, updates deleted ldap attributes (MNT-14026)
                    properties.put(keyQName, null);
                }
            } else if (defaultAttribute != null) {
                LOGGER.debug("Node {} does not provide attriute {} - using default value", uid, attributeName);
                properties.put(keyQName, defaultAttribute);
            } else {
                LOGGER.debug("Node {} does not provide attriute {} - setting to null", uid, attributeName);
                // Make sure that a 2nd sync, updates deleted ldap attributes (MNT-14026)
                properties.put(keyQName, null);
            }
        } else {
            LOGGER.debug("No attribute name has been configured for property {}", keyQName);
            final String defaultValue = attributeDefaults.get(key);
            if (defaultValue != null) {
                LOGGER.debug("Using default value for {} on node {}", keyQName, uid);
                properties.put(keyQName, defaultValue);
            }
        }
    }

    return nodeDescription;
}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

protected XmlBuilder attributesToXml(Attributes atts) throws NamingException {
    XmlBuilder attributesElem = new XmlBuilder("attributes");

    NamingEnumeration all = atts.getAll();
    while (all.hasMore()) {
        Attribute attribute = (Attribute) all.next();
        XmlBuilder attributeElem = new XmlBuilder("attribute");
        attributeElem.addAttribute("name", attribute.getID());
        if (attribute.size() == 1 && attribute.get() != null) {
            attributeElem.addAttribute("value", attribute.get().toString());
        } else {//from w  w w .ja v a2 s  . c  o m
            NamingEnumeration values = attribute.getAll();
            while (values.hasMore()) {
                Object value = values.next();
                XmlBuilder itemElem = new XmlBuilder("item");
                itemElem.addAttribute("value", value.toString());
                attributeElem.addSubElement(itemElem);
            }
        }
        attributesElem.addSubElement(attributeElem);
    }
    return attributesElem;
}

From source file:org.apache.ranger.ldapusersync.process.LdapDeltaUserGroupBuilder.java

private void goUpGroupHierarchyLdap(Set<String> groupDNs, int groupHierarchyLevels) throws Throwable {
    if (groupHierarchyLevels <= 0 || groupDNs.isEmpty()) {
        return;//www  .jav a  2s  .  com
    }
    Set<String> nextLevelGroups = new HashSet<String>();

    NamingEnumeration<SearchResult> groupSearchResultEnum = null;
    try {
        createLdapContext();
        int total;
        // Activate paged results
        if (pagedResultsEnabled) {
            ldapContext.setRequestControls(
                    new Control[] { new PagedResultsControl(pagedResultsSize, Control.NONCRITICAL) });
        }
        String groupFilter = "(&(objectclass=" + groupObjectClass + ")";
        if (groupSearchFilter != null && !groupSearchFilter.trim().isEmpty()) {
            String customFilter = groupSearchFilter.trim();
            if (!customFilter.startsWith("(")) {
                customFilter = "(" + customFilter + ")";
            }
            groupFilter += customFilter + "(|";
        }
        StringBuilder filter = new StringBuilder();

        for (String groupDN : groupDNs) {
            filter.append("(").append(groupMemberAttributeName).append("=").append(groupDN).append(")");
        }
        filter.append("))");
        groupFilter += filter;

        LOG.info("extendedAllGroupsSearchFilter = " + groupFilter);
        for (int ou = 0; ou < groupSearchBase.length; ou++) {
            byte[] cookie = null;
            int counter = 0;
            try {
                do {
                    groupSearchResultEnum = ldapContext.search(groupSearchBase[ou], groupFilter,
                            groupSearchControls);
                    while (groupSearchResultEnum.hasMore()) {
                        final SearchResult groupEntry = groupSearchResultEnum.next();
                        if (groupEntry == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info("groupEntry null, skipping sync for the entry");
                            }
                            continue;
                        }
                        counter++;
                        Attribute groupNameAttr = groupEntry.getAttributes().get(groupNameAttribute);
                        if (groupNameAttr == null) {
                            if (LOG.isInfoEnabled()) {
                                LOG.info(groupNameAttribute + " empty for entry "
                                        + groupEntry.getNameInNamespace() + ", skipping sync");
                            }
                            continue;
                        }
                        nextLevelGroups.add(groupEntry.getNameInNamespace());
                        String gName = (String) groupNameAttr.get();

                        Attribute groupMemberAttr = groupEntry.getAttributes().get(groupMemberAttributeName);
                        int userCount = 0;
                        if (groupMemberAttr == null || groupMemberAttr.size() <= 0) {
                            LOG.info("No members available for " + gName);
                            continue;
                        }

                        NamingEnumeration<?> userEnum = groupMemberAttr.getAll();
                        while (userEnum.hasMore()) {
                            String originalUserFullName = (String) userEnum.next();
                            if (originalUserFullName == null || originalUserFullName.trim().isEmpty()) {
                                continue;
                            }
                            userCount++;
                            originalUserFullName = originalUserFullName.toLowerCase();
                            if (userNameMap.get(originalUserFullName) != null) {
                                groupUserTable.put(gName, originalUserFullName,
                                        userNameMap.get(originalUserFullName));
                            } else {
                                groupUserTable.put(gName, originalUserFullName, originalUserFullName);
                            }
                            groupNameMap.put(groupEntry.getNameInNamespace().toLowerCase(), gName);
                        }
                        LOG.info("No. of members in the group " + gName + " = " + userCount);
                    }
                    // Examine the paged results control response
                    Control[] controls = ldapContext.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOG.debug("END-OF-PAGE total : " + total);
                                } else {
                                    LOG.debug("END-OF-PAGE total : unknown");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOG.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    if (pagedResultsEnabled) {
                        ldapContext.setRequestControls(new Control[] {
                                new PagedResultsControl(pagedResultsSize, cookie, Control.CRITICAL) });
                    }
                } while (cookie != null);
                LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() completed with group count: "
                        + counter);
            } catch (RuntimeException re) {
                LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with runtime exception: ",
                        re);
                throw re;
            } catch (Exception t) {
                LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", t);
                LOG.info("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() group count: " + counter);
            }
        }

    } catch (RuntimeException re) {
        LOG.error("LdapDeltaUserGroupBuilder.goUpGroupHierarchyLdap() failed with exception: ", re);
        throw re;
    } finally {
        if (groupSearchResultEnum != null) {
            groupSearchResultEnum.close();
        }
        closeLdapContext();
    }
    goUpGroupHierarchyLdap(nextLevelGroups, groupHierarchyLevels - 1);
}

From source file:org.opentravel.schemacompiler.security.impl.JNDIAuthenticationProvider.java

/**
 * Returns the specified attribute value from the list of attributes provided. If multiple
 * values are assigned to the requested attribute, only the first available value will be
 * returned./*from   ww  w . j av  a 2s. c o  m*/
 * 
 * @param attributes
 *            the list of attributes from which to return a value
 * @param attributeName
 *            the name of the attribute whose value is to be returned
 * @return String
 * @throws NamingException
 *             thrown if an error occurs while scanning the attributes
 */
private String getAttributeValue(Attributes attributes, String attributeName) throws NamingException {
    Attribute attribute = (attributes == null) ? null : attributes.get(attributeName);
    String attributeValue = null;

    if (attribute != null) {
        Object attrValue = attribute.get();

        if (attrValue != null) {
            if (attrValue instanceof byte[]) {
                attributeValue = new String((byte[]) attrValue);

            } else {
                attributeValue = attrValue.toString();
            }
        }
    }
    return attributeValue;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetches the supplied user./*from   www .j  a va2  s . c om*/
 *
 * @param attrValue the user id
 * @return the user id for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 * @throws IOException 
 */
protected String selectUser(String attrId, String attrValue) throws NamingException, IOException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    BasicAttributes matchAttrs = new BasicAttributes(true);

    String uidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    matchAttrs.put(attrId, attrValue);

    // String[] principalAttr = {attrId};

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(uidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'");
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + attrValue + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return uidValue;
}

From source file:org.lsc.jndi.JndiServices.java

/**
 * Return the LDAP schema.//from ww  w .  j av a 2  s.co m
 *
 * @param attrsToReturn
 *                list of attribute names to return (or null for all
 *                'standard' attributes)
 * @return the map of name => attribute
 * @throws NamingException
 *                 thrown if something goes wrong (bad
 */
@SuppressWarnings("unchecked")
public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException {
    Map<String, List<String>> attrsResult = new HashMap<String, List<String>>();

    // connect to directory
    Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment();
    String baseUrl = (String) props.get(Context.PROVIDER_URL);
    baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/'));
    props.put(Context.PROVIDER_URL, baseUrl);
    DirContext schemaCtx = new InitialLdapContext(props, null);

    // find schema entry
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    sc.setReturningAttributes(new String[] { "subschemaSubentry" });

    NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc);

    SearchResult sr = null;
    Attribute subschemaSubentry = null;
    String subschemaSubentryDN = null;

    if (schemaDnSR.hasMore()) {
        sr = schemaDnSR.next();
    }
    if (sr != null) {
        subschemaSubentry = sr.getAttributes().get("subschemaSubentry");
    }
    if (subschemaSubentry != null && subschemaSubentry.size() > 0) {
        subschemaSubentryDN = (String) subschemaSubentry.get();
    }

    if (subschemaSubentryDN != null) {
        // get schema attributes from subschemaSubentryDN
        Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN,
                attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" });

        if (schemaAttrs != null) {
            for (String attr : attrsToReturn) {
                Attribute schemaAttr = schemaAttrs.get(attr);
                if (schemaAttr != null) {
                    attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll()));
                }
            }
        }
    }

    return attrsResult;
}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Fetches the supplied user DN.//  w ww. ja va 2  s  .c o m
 *
 * @param uid the user id
 * @return the user DN for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 * @throws IOException 
 */
protected String selectUserDN(String uid) throws NamingException, IOException {

    String dn = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :

        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(principalUidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'");
                continue;
            }

            String uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                dn = sr.getName() + "," + usersCtxDN;
                if (logger.isDebugEnabled())
                    logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid
                            + "' DN=" + dn);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + uid + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return dn;

}

From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java

/**
 * Get user UID attribute for the given certificate.
 *
 * @param lookupValue value used for credentials lookup
 * @param certificate user certificate/*from   w w w .j a  v a2s.  c o  m*/
 * @param cp credential provider
 * @return user UID
 * @throws NamingException LDAP error obtaining user UID.
 * @throws IOException 
 */
protected String loadUID(String lookupValue, X509Certificate certificate, CredentialProvider cp)
        throws NamingException, IOException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext(false);

    StartTlsResponse tls = null;
    if (getEnableStartTls()) {
        tls = startTls(ctx);
    }

    String schemeName = null;
    if (cp instanceof AuthenticationScheme) {
        schemeName = ((AuthenticationScheme) cp).getName();
    }

    String principalLookupAttrName = this.getPrincipalLookupAttributeID();
    if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("")
            || !"strong-authentication".equals(schemeName)) {
        principalLookupAttrName = this.getPrincipalUidAttributeID();
    }

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String certificateAttrName = this.getUserCertificateAtrributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :

        NamingEnumeration answer = ctx.search(usersCtxDN,
                "(&(" + principalLookupAttrName + "={0})(" + certificateAttrName + "={1}))",
                new Object[] { lookupValue, certificate.getEncoded() }, getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(principalUidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug("Found user " + principalUidAttrName + "=" + uidValue);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for certificate '"
                            + certificate.getSubjectX500Principal().getName() + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } catch (CertificateEncodingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Certificate encoding exception", e);
    } finally {
        // Close the context to release the connection
        if (tls != null) {
            tls.close();
        }
        ctx.close();
    }

    return uidValue;
}