Example usage for javax.naming NamingEnumeration next

List of usage examples for javax.naming NamingEnumeration next

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration next.

Prototype

public T next() throws NamingException;

Source Link

Document

Retrieves the next element in the enumeration.

Usage

From source file:com.wfp.utils.LDAPUtils.java

public static Map<String, String> parseAsMap(NamingEnumeration searchResults, String keyAttribute,
        String valueAttribute) {/*from   ww  w  . ja  va 2  s .  co m*/
    Logger.debug("# START parseAsMap : Formatting the data as MAP", LDAPUtils.class);
    //System.out.println("# START parseAsMap : Formatting the data as MAP: "+searchResults );
    Map<String, String> resultMap = new HashMap<String, String>();
    if (searchResults == null) {
        return null;
    }
    // Loop through the search results
    while (searchResults.hasMoreElements()) {
        SearchResult sr = null;
        List<String> strList = new ArrayList<String>();
        try {
            sr = (SearchResult) searchResults.next();

        } catch (NamingException e1) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
        }
        if (sr == null) {
            Logger.error("No Search results on LDAP ", LDAPUtils.class);
            return null;
        }
        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();

                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); e.next())
                        ;

                    //System.out.println(" attrs : "+attrs.get(keyAttribute) + ": "+ attrs.get(valueAttribute));
                    //if(attrs.get(keyAttribute)!=null && attrs.get(keyAttribute)!=null)
                    resultMap.put(attrs.get(keyAttribute).toString(), attrs.get(valueAttribute).toString());
                }
            } catch (NamingException ne) {
                ne.printStackTrace();
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }
    //Logger.debug("# END parseAsMap : Formatting the data as MAP", LDAPUtils.class );
    return resultMap;
}

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

protected Collection<Object> mapAttribute(final Attribute attribute) throws NamingException {
    Collection<Object> values;
    if (attribute.isOrdered()) {
        values = new ArrayList<>();
    } else {/*www.ja va  2 s  .c  o m*/
        values = new HashSet<>();
    }
    final NamingEnumeration<?> allAttributeValues = attribute.getAll();
    while (allAttributeValues.hasMore()) {
        final Object next = allAttributeValues.next();
        final Object mappedValue = this.mapAttributeValue(attribute.getID(), next);
        values.add(mappedValue);
    }

    LOGGER.debug("Mapped value of {} to {}", attribute, values);

    return values;
}

From source file:org.apache.manifoldcf.authorities.authorities.sharepoint.SharePointADAuthority.java

/** Get the AD-derived access tokens for a user and domain */
protected List<String> getADTokens(String userPart, String domainPart, String userName)
        throws NameNotFoundException, NamingException, ManifoldCFException {
    // Now, look through the rules for the matching domain controller
    String domainController = null;
    for (DCRule rule : dCRules) {
        String suffix = rule.getSuffix();
        if (suffix.length() == 0
                || domainPart.toLowerCase(Locale.ROOT).endsWith(suffix.toLowerCase(Locale.ROOT))
                        && (suffix.length() == domainPart.length()
                                || domainPart.charAt((domainPart.length() - suffix.length()) - 1) == '.')) {
            domainController = rule.getDomainControllerName();
            break;
        }//  w w w. jav a 2s.co  m
    }

    if (domainController == null)
        // No AD user
        return null;

    // Look up connection parameters
    DCConnectionParameters dcParams = dCConnectionParameters.get(domainController);
    if (dcParams == null)
        // No AD user
        return null;

    // Use the complete fqn if the field is the "userPrincipalName"
    String userBase;
    String userACLsUsername = dcParams.getUserACLsUsername();
    if (userACLsUsername != null && userACLsUsername.equals("userPrincipalName")) {
        userBase = userName;
    } else {
        userBase = userPart;
    }

    //Build the DN searchBase from domain part
    StringBuilder domainsb = new StringBuilder();
    int j = 0;
    while (true) {
        if (j > 0)
            domainsb.append(",");

        int k = domainPart.indexOf(".", j);
        if (k == -1) {
            domainsb.append("DC=").append(ldapEscape(domainPart.substring(j)));
            break;
        }
        domainsb.append("DC=").append(ldapEscape(domainPart.substring(j, k)));
        j = k + 1;
    }

    // Establish a session with the selected domain controller
    LdapContext ctx = createDCSession(domainController);

    //Get DistinguishedName (for this method we are using DomainPart as a searchBase ie: DC=qa-ad-76,DC=metacarta,DC=com")
    String searchBase = getDistinguishedName(ctx, userBase, domainsb.toString(), userACLsUsername);
    if (searchBase == null)
        return null;

    //specify the LDAP search filter
    String searchFilter = "(objectClass=user)";

    //Create the search controls for finding the access tokens   
    SearchControls searchCtls = new SearchControls();

    //Specify the search scope, must be base level search for tokenGroups
    searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE);

    //Specify the attributes to return
    String returnedAtts[] = { "tokenGroups", "objectSid" };
    searchCtls.setReturningAttributes(returnedAtts);

    //Search for tokens.  Since every user *must* have a SID, the "no user" detection should be safe.
    NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);

    List<String> theGroups = new ArrayList<String>();
    String userToken = userTokenFromLoginName(domainPart + "\\" + userPart);
    if (userToken != null)
        theGroups.add(userToken);

    //Loop through the search results
    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        //the sr.GetName should be null, as it is relative to the base object

        Attributes attrs = sr.getAttributes();
        if (attrs != null) {
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                        String sid = sid2String((byte[]) e.next());
                        String token = attr.getID().equals("objectSid") ? userTokenFromSID(sid)
                                : groupTokenFromSID(sid);
                        theGroups.add(token);
                    }
                }
            } catch (NamingException e) {
                throw new ManifoldCFException(e.getMessage(), e);
            }
        }
    }

    if (theGroups.size() == 0)
        return null;

    // User is in AD, so add the 'everyone' group
    theGroups.add(everyoneGroup());
    return theGroups;
}

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

protected <T> Collection<T> mapAttribute(final Attribute attribute, final Class<T> expectedValueClass)
        throws NamingException {
    Collection<T> values;//from   w w  w .j  av a 2 s  . c  o m
    if (attribute.isOrdered()) {
        values = new ArrayList<>();
    } else {
        values = new HashSet<>();
    }
    final NamingEnumeration<?> allAttributeValues = attribute.getAll();
    while (allAttributeValues.hasMore()) {
        final Object next = allAttributeValues.next();
        final Object mappedValue = this.mapAttributeValue(attribute.getID(), next);
        final T value = DefaultTypeConverter.INSTANCE.convert(expectedValueClass, mappedValue);
        values.add(value);
    }

    LOGGER.debug("Mapped value of {} to {}", attribute, values);

    return values;
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * /*from  ww  w  .j  av a2s  .co m*/
 * Creates list of all OLAT Users which have been deleted out of the LDAP
 * directory but still exits in OLAT
 * 
 * Configuration: Required Attributes = ldapContext.xml (property=reqAttrs)
 * LDAP Base = ldapContext.xml (property=ldapBase)
 * 
 * @param syncTime The time to search in LDAP for changes since this time.
 *          SyncTime has to formatted: JJJJMMddHHmm
 * @param ctx The LDAP system connection, if NULL or closed NamingExecpiton is
 *          thrown
 * 
 * @return Returns list of Identity from the user which have been deleted in
 *         LDAP
 * 
 * @throws NamingException
 */
public List<Identity> getIdentitysDeletedInLdap(LdapContext ctx) {
    if (ctx == null)
        return null;
    // Find all LDAP Users
    String userID = syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER);
    String userFilter = syncConfiguration.getLdapUserFilter();
    final List<String> ldapList = new ArrayList<String>();

    ldapDao.searchInLdap(new LDAPVisitor() {
        @Override
        public void visit(SearchResult result) throws NamingException {
            Attributes attrs = result.getAttributes();
            NamingEnumeration<? extends Attribute> aEnum = attrs.getAll();
            while (aEnum.hasMore()) {
                Attribute attr = aEnum.next();
                // use lowercase username
                ldapList.add(attr.get().toString().toLowerCase());
            }
        }
    }, (userFilter == null ? "" : userFilter), new String[] { userID }, ctx);

    if (ldapList.isEmpty()) {
        log.warn("No users in LDAP found, can't create deletionList!!", null);
        return null;
    }

    // Find all User in OLAT, members of LDAPSecurityGroup
    SecurityGroup ldapGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    if (ldapGroup == null) {
        log.error("Error getting users from OLAT security group '" + LDAPConstants.SECURITY_GROUP_LDAP
                + "' : group does not exist", null);
        return null;
    }

    List<Identity> identityListToDelete = new ArrayList<Identity>();
    List<Identity> olatListIdentity = securityManager.getIdentitiesOfSecurityGroup(ldapGroup);
    for (Identity ida : olatListIdentity) {
        // compare usernames with lowercase
        if (!ldapList.contains(ida.getName().toLowerCase())) {
            identityListToDelete.add(ida);
        }
    }
    return identityListToDelete;
}

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

/**
 * Retrieve the elements referenced by the filter/BaseDN/Scope request.
 *
 * @param attributes Attributes of the referencer element
 * @param directoryDn Dn of the Directory
 * @param linkDn Dn specified in the parent
 * @param filter Filter expression specified in the parent
 * @param scope scope for the search//  w  ww .j ava2  s.  c  om
 * @return The list of the referenced elements.
 * @throws DirectoryException
 * @throws NamingException
 */
private Set<String> getReferencedElements(Attributes attributes, String directoryDn, String linkDn,
        String filter, int scope) throws DirectoryException, NamingException {

    Set<String> targetIds = new TreeSet<>();

    LDAPDirectoryDescriptor targetDirconfig = getTargetDirectoryDescriptor();
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession();

    // use the most specific scope between the one specified in the
    // Directory and the specified in the Parent
    String dn = directoryDn.endsWith(linkDn) && directoryDn.length() > linkDn.length() ? directoryDn : linkDn;

    // combine the ldapUrl search query with target
    // directory own constraints
    SearchControls scts = new SearchControls();

    // use the most specific scope
    scts.setSearchScope(Math.min(scope, targetDirconfig.getSearchScope()));

    // only fetch the ids of the targets
    scts.setReturningAttributes(new String[] { targetSession.idAttribute });

    // combine the filter of the target directory with the
    // provided filter if any
    String targetFilter = targetDirconfig.getSearchFilter();
    if (filter == null || filter.length() == 0) {
        filter = targetFilter;
    } else if (targetFilter != null && targetFilter.length() > 0) {
        filter = String.format("(&(%s)(%s))", targetFilter, filter);
    }

    // perform the request and collect the ids
    if (log.isDebugEnabled()) {
        log.debug(String.format(
                "LDAPReference.getLdapTargetIds(%s): LDAP search dn='%s' " + " filter='%s' scope='%s' [%s]",
                attributes, dn, dn, scts.getSearchScope(), this));
    }

    Name name = new CompositeName().add(dn);
    NamingEnumeration<SearchResult> results = targetSession.dirContext.search(name, filter, scts);
    try {
        while (results.hasMore()) {
            // NXP-2461: check that id field is filled
            Attribute attr = results.next().getAttributes().get(targetSession.idAttribute);
            if (attr != null) {
                String collectedId = attr.get().toString();
                if (collectedId != null) {
                    targetIds.add(collectedId);
                }
            }

        }
    } finally {
        results.close();
    }

    return targetIds;
}

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

/**
 * Does a case-insensitive search for the given value in an attribute.
 *
 * @param attribute/*from w w w.  ja v a2s  .  c o m*/
 *            the attribute
 * @param value
 *            the value to search for
 * @return <code>true</code>, if the value was found
 * @throws NamingException
 *             if there is a problem accessing the attribute values
 */
protected boolean hasAttributeValue(final Attribute attribute, final String value) throws NamingException {
    if (attribute != null) {
        final NamingEnumeration<?> values = attribute.getAll();
        while (values.hasMore()) {
            final Object mappedValue = this.mapAttributeValue(attribute.getID(), values.next());
            if (mappedValue instanceof String && value.equalsIgnoreCase((String) mappedValue)) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.olat.ldap.manager.LDAPLoginManagerImpl.java

/**
 * Checks if LDAP properties are different then OLAT properties of a User. If
 * they are different a Map (OlatPropertyName,LDAPValue) is returned.
 * /*from   ww  w  . ja  v  a  2s  .c om*/
 * @param attributes Set of LDAP Attribute of Identity
 * @param identity Identity to compare
 * 
 * @return Map(OlatPropertyName,LDAPValue) of properties Identity, where
 *         property has changed. NULL is returned it no attributes have to be synced
 */
@SuppressWarnings("unchecked")
public Map<String, String> prepareUserPropertyForSync(Attributes attributes, Identity identity) {
    Map<String, String> olatPropertyMap = new HashMap<String, String>();
    User user = identity.getUser();
    NamingEnumeration<Attribute> neAttrs = (NamingEnumeration<Attribute>) attributes.getAll();
    try {
        while (neAttrs.hasMore()) {
            Attribute attr = neAttrs.next();
            String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (olatProperty == null) {
                continue;
            }
            String ldapValue = getAttributeValue(attr);
            String olatValue = user.getProperty(olatProperty, null);
            if (olatValue == null) {
                // new property or user ID (will always be null, pseudo property)
                olatPropertyMap.put(olatProperty, ldapValue);
            } else {
                if (ldapValue.compareTo(olatValue) != 0) {
                    olatPropertyMap.put(olatProperty, ldapValue);
                }
            }
        }
        if (olatPropertyMap.size() == 1 && olatPropertyMap.get(LDAPConstants.LDAP_USER_IDENTIFYER) != null) {
            log.debug("propertymap for identity " + identity.getName()
                    + " contains only userID, NOTHING TO SYNC!");
            return null;
        } else {
            log.debug("propertymap for identity " + identity.getName() + " contains " + olatPropertyMap.size()
                    + " items (" + olatPropertyMap.keySet() + ") to be synced later on");
            return olatPropertyMap;
        }

    } catch (NamingException e) {
        log.error("NamingException when trying to prepare user properties for LDAP sync", e);
        return null;
    }
}

From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java

public String searchQueryLDAP() {
    NamingEnumeration results = null;
    ObjectMapper mapper = new ObjectMapper();
    Response response;/*  www. j  ava2 s. c o m*/
    String resultOutput = new String();
    List<Map<String, String>> attributesList = new LinkedList<>();

    String[] attributesToReturn = splitAttributes(allLDAPClientParameters.get(ARG_SELECTED_ATTRIBUTES));
    try {
        ldapConnection = LDAPConnectionUtility.connect(allLDAPClientParameters.get(ARG_URL),
                allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_USERNAME),
                allLDAPClientParameters.get(ARG_PASSWORD));
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (attributesToReturn.length > 0) {
            controls.setReturningAttributes(attributesToReturn);
        }
        results = ldapConnection.search(
                getFullLdapSearchBase(allLDAPClientParameters.get(ARG_DN_BASE),
                        allLDAPClientParameters.get(ARG_SEARCH_BASE)),
                allLDAPClientParameters.get(ARG_SEARCH_FILTER), controls);

        // Iterate through all attributes in the result of search query
        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();

            if (attributes != null && attributes.size() > 0) {
                NamingEnumeration ae = attributes.getAll();
                Map<String, String> attributesMap = new HashMap<>();
                while (ae.hasMore()) {
                    Attribute attribute = (Attribute) ae.next();
                    attributesMap.put(attribute.getID(), attribute.get().toString());
                }
                attributesList.add(attributesMap);
            }
        }
        response = new LDAPResponse("Ok", attributesList);
    } catch (Exception e) {
        response = new ErrorResponse("Error", e.toString());
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (ldapConnection != null) {
            try {
                ldapConnection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        resultOutput = mapper.writeValueAsString(response);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return resultOutput;
}

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 {/* w  w w  .java 2s .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;
}