Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

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

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

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

protected boolean licensedOganizationExists(String orgId) throws ExecutionException {
    NamingEnumeration<SearchResult> searchResults = null;
    try {//from   w  w  w .jav a2  s  . co m
        searchResults = this.query(LDAPConnector.getSingletonInstance().getLicensedInstitutionsBaseDN(),
                new StringBuilder("(& (objectclass=").append(Constants.ldap_ddbOrg_ObjectClass).append(") (")
                        .append(Constants.ldap_ddbOrg_Id).append("=").append(orgId).append("))").toString(),
                new String[] { Constants.ldap_ddbOrg_Id, "+" }, SearchControls.SUBTREE_SCOPE);
        if (searchResults.hasMore()) {
            return true;
        } else {
            return false;
        }
    } catch (IllegalAccessException ex) {
        LOG.log(Level.SEVERE, "Connection-Error", ex);
        throw new ExecutionException(ex.getMessage(), ex.getCause());
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, "something went wrong while checking if userId exists", ne);
        throw new ExecutionException(ne.getMessage(), ne.getCause());
    } finally {
        if (searchResults != null) {
            try {
                searchResults.close();
            } catch (NamingException e) {
            }
        }
    }
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Does a subtree search for an element given a pattern. Only the first
 * element found is considered, and all references are searched in order
 * until either a match is found or no more references are left to search.
 * @param ldap//from   w w w  .j  a  va  2s . c  om
 *            A prepared LDAP context.
 * @param pattern
 *            The search pattern. Must not include the character '*' or the
 *            substring '\2a' to prevent possible LDAP exploits.
 * @return The element's relative DN, or <code>null</code> if none was
 *         found. <code>null</code> is also returned if the search pattern
 *         contains an illegal character or substring.
 * @throws BackendException
 *             If there was a problem accessing the backend. Typical causes
 *             include timeouts.
 */
private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException {

    // Check pattern for illegal content.
    String[] illegals = { "*", "\\2a" };
    for (int i = 0; i < illegals.length; i++) {
        if (pattern.indexOf(illegals[i]) > -1)
            return null;
    }

    // The context provider URL, for later logging.
    String url = "unknown backend";

    // Start counting the (milli)seconds and prepare for timeouts.
    long searchStart = System.currentTimeMillis();
    JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket);
    NamingEnumeration results;
    try {

        // Remember the URL, for later logging.
        url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
        interruptTask.setURL(url);

        // Start timeout interruptor and perform the search.
        Timer interruptTimer = new Timer();
        interruptTimer.schedule(interruptTask, (1000 * myTimeout));
        results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout,
                new String[] {}, false, false));
        interruptTimer.cancel();
        if (!results.hasMore())
            return null;

    } catch (TimeLimitExceededException e) {

        // The search timed out.
        log.logWarn("Search on " + url + " for " + pattern + " timed out after ~"
                + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket);
        return null;

    } catch (SizeLimitExceededException e) {

        // The search returned too many results.
        log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket);
        return null;

    } catch (NameNotFoundException e) {

        // Element not found. Possibly non-existing reference.
        log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary?
        return null;

    } catch (AuthenticationException e) {

        // Search failed authentication; check non-anonymous search config.
        try {
            final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL);
            final String errorMessage;
            if ((searchUser == null) || searchUser.equals(""))
                errorMessage = "Anonymous search failed authentication on " + url;
            else
                errorMessage = "Could not authenticate search user " + searchUser + " on " + url;
            log.logDebug(errorMessage, mySessionTicket);
            throw new BackendException(errorMessage, e);
        } catch (NamingException f) {

            // Should not happen!
            log.logCritical("Unable to read LDAP environment", mySessionTicket, f);
            throw new BackendException("Unable to read LDAP environment", f);

        }

    } catch (NamingException e) {

        // Did we interrupt the search ourselves?
        if (interruptTask.finished()) {
            final long elapsed = System.currentTimeMillis() - searchStart;
            log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms",
                    mySessionTicket);
            throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed
                    + "ms; connection terminated");
        }

        // All other exceptions.
        log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e);
        return null;

    }

    // We just found at least one element. Did we get an ambigious result?
    SearchResult entry = null;
    try {
        entry = (SearchResult) results.next();
        String buffer = new String();
        while (results.hasMoreElements())
            buffer = buffer + ", " + ((SearchResult) results.next()).getName();
        if (!buffer.equals(""))
            log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName()
                    + buffer + "]", mySessionTicket);
        // TODO: Throw BackendException, or a subclass, or just (as now)
        // pick the first and hope for the best?
        buffer = null;
    } catch (NamingException e) {
        throw new BackendException("Unable to read search results", e);
    }
    return entry.getName(); // Relative DN (to the reference).

}

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   w  ww  .j  a  v  a2  s .c o m
 * @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.springframework.ldap.core.DirContextAdapter.java

public void update() {
    NamingEnumeration attributesEnumeration = null;

    try {//w ww  .  j  a va  2 s.  c o 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);
}

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  ww  .  jav a  2s.com*/
            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.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Obtains the roles for the given user.
 *
 * @param username the user name to fetch user data.
 * @return the list of roles to which the user is associated to.
 * @throws NamingException LDAP error obtaining roles fro the given user
 *///from   www. j  av a  2s .  c  om
protected String[] selectRolesByUsername(String username) throws NamingException, NoSuchUserException {
    List userRoles = new ArrayList();

    InitialLdapContext ctx = createLdapInitialContext();

    String rolesCtxDN = getRolesCtxDN();

    // Search for any roles associated with the user
    if (rolesCtxDN != null) {

        // The attribute where user DN is stored in roles :
        String uidAttributeID = getUidAttributeID();
        if (uidAttributeID == null)
            uidAttributeID = "uniquemember";

        // The attribute that identifies the role name 
        String roleAttrName = getRoleAttributeID();
        if (roleAttrName == null)
            roleAttrName = "roles";

        String userDN;
        if ("UID".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = username;
        } else if ("PRINCIPAL".equals(getRoleMatchingMode())) {
            // Use User ID to match the role
            userDN = _principalUidAttributeID + "=" + username;
        } else {
            // Default behaviour: Match the role using the User DN, not just the username :
            userDN = selectUserDN(username);
        }

        if (logger.isDebugEnabled())
            logger.debug(
                    "Searching Roles for user '" + userDN + "' in Uid attribute name '" + uidAttributeID + "'");

        if (userDN == null)
            throw new NoSuchUserException(username);

        try {
            if (userDN.contains("\\")) {
                logger.debug("Escaping '\\' character");
                userDN = userDN.replace("\\", "\\\\\\");
            }

            NamingEnumeration answer = ctx.search(rolesCtxDN, "(&(" + uidAttributeID + "=" + userDN + "))",
                    getSearchControls());

            if (logger.isDebugEnabled())
                logger.debug("Search Name:  " + rolesCtxDN);

            if (logger.isDebugEnabled())
                logger.debug("Search Filter:  (&(" + uidAttributeID + "=" + userDN + "))");

            if (!answer.hasMore())
                logger.info("No roles found for user " + username);

            while (answer.hasMore()) {
                SearchResult sr = (SearchResult) answer.next();
                Attributes attrs = sr.getAttributes();
                Attribute roles = attrs.get(roleAttrName);
                for (int r = 0; r < roles.size(); r++) {
                    Object value = roles.get(r);
                    String roleName = null;
                    // The role attribute value is the role name
                    roleName = value.toString();

                    if (roleName != null) {
                        if (logger.isDebugEnabled())
                            logger.debug("Saving role '" + roleName + "' for user '" + username + "'");
                        userRoles.add(roleName);
                    }
                }
            }
        } catch (NamingException e) {
            if (logger.isDebugEnabled())
                logger.debug("Failed to locate roles", e);
        }
    }
    // Close the context to release the connection
    ctx.close();
    return (String[]) userRoles.toArray(new String[userRoles.size()]);
}

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

/**
 * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes
 * have to be checked before this method.
 * /*www .j av a2s  . co m*/
 * @param userAttributes Set of LDAP Attribute of User to be created
 */
@Override
public Identity createAndPersistUser(Attributes userAttributes) {
    // Get and Check Config
    String[] reqAttrs = syncConfiguration.checkRequestAttributes(userAttributes);
    if (reqAttrs != null) {
        log.warn("Can not create and persist user, the following attributes are missing::"
                + ArrayUtils.toString(reqAttrs), null);
        return null;
    }

    String uid = getAttributeValue(userAttributes
            .get(syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER)));
    String email = getAttributeValue(
            userAttributes.get(syncConfiguration.getOlatPropertyToLdapAttribute(UserConstants.EMAIL)));
    // Lookup user
    if (securityManager.findIdentityByName(uid) != null) {
        log.error("Can't create user with username='" + uid
                + "', this username does already exist in OLAT database", null);
        return null;
    }
    if (!MailHelper.isValidEmailAddress(email)) {
        // needed to prevent possibly an AssertException in findIdentityByEmail breaking the sync!
        log.error("Cannot try to lookup user " + uid + " by email with an invalid email::" + email, null);
        return null;
    }
    if (userManager.userExist(email)) {
        log.error("Can't create user with email='" + email
                + "', a user with that email does already exist in OLAT database", null);
        return null;
    }

    // Create User (first and lastname is added in next step)
    User user = userManager.createUser(null, null, email);
    // Set User Property's (Iterates over Attributes and gets OLAT Property out
    // of olatexconfig.xml)
    NamingEnumeration<? extends Attribute> neAttr = userAttributes.getAll();
    try {
        while (neAttr.hasMore()) {
            Attribute attr = neAttr.next();
            String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (!attr.getID().equalsIgnoreCase(
                    syncConfiguration.getOlatPropertyToLdapAttribute(LDAPConstants.LDAP_USER_IDENTIFYER))) {
                String ldapValue = getAttributeValue(attr);
                if (olatProperty == null || ldapValue == null)
                    continue;
                user.setProperty(olatProperty, ldapValue);
            }
        }
        // Add static user properties from the configuration
        Map<String, String> staticProperties = syncConfiguration.getStaticUserProperties();
        if (staticProperties != null && staticProperties.size() > 0) {
            for (Entry<String, String> staticProperty : staticProperties.entrySet()) {
                user.setProperty(staticProperty.getKey(), staticProperty.getValue());
            }
        }
    } catch (NamingException e) {
        log.error("NamingException when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    } catch (Exception e) {
        // catch any exception here to properly log error
        log.error("Unknown exception when trying to create and persist LDAP user with username::" + uid, e);
        return null;
    }

    // Create Identity
    Identity identity = securityManager.createAndPersistIdentityAndUser(uid, null, user,
            LDAPAuthenticationController.PROVIDER_LDAP, uid);
    // Add to SecurityGroup LDAP
    SecurityGroup secGroup = securityManager.findSecurityGroupByName(LDAPConstants.SECURITY_GROUP_LDAP);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    // Add to SecurityGroup OLATUSERS
    secGroup = securityManager.findSecurityGroupByName(Constants.GROUP_OLATUSERS);
    securityManager.addIdentityToSecurityGroup(identity, secGroup);
    log.info("Created LDAP user username::" + uid);
    return identity;
}

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

/**
 * Remove existing statically defined links for the given source id (dynamic references remain unaltered)
 *
 * @see org.nuxeo.ecm.directory.Reference#removeLinksForSource(String)
 *//*w w w  .  j a v a2  s.co m*/
@Override
public void removeLinksForSource(String sourceId) throws DirectoryException {
    LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory();
    LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory();
    String attributeId = getStaticAttributeId();
    try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession();
            LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession()) {
        if (sourceSession.isReadOnly() || attributeId == null) {
            // do not try to do anything on a read only server or to a
            // purely dynamic reference
            return;
        }
        // get the dn of the entry that matches sourceId
        SearchResult sourceLdapEntry = sourceSession.getLdapEntry(sourceId);
        if (sourceLdapEntry == null) {
            throw new DirectoryException(
                    String.format("cannot edit the links hold by missing entry '%s' in directory '%s'",
                            sourceId, ldapSourceDirectory.getName()));
        }
        String sourceDn = pseudoNormalizeDn(sourceLdapEntry.getNameInNamespace());

        Attribute oldAttr = sourceLdapEntry.getAttributes().get(attributeId);
        if (oldAttr == null) {
            // consider it as an empty attribute to simplify the following
            // code
            oldAttr = new BasicAttribute(attributeId);
        }
        Attribute attrToRemove = new BasicAttribute(attributeId);

        NamingEnumeration<?> oldAttrs = oldAttr.getAll();
        String targetBaseDn = pseudoNormalizeDn(ldapTargetDirectory.getDescriptor().getSearchBaseDn());
        try {
            while (oldAttrs.hasMore()) {
                String targetKeyAttr = oldAttrs.next().toString();

                if (staticAttributeIdIsDn) {
                    String dn = pseudoNormalizeDn(targetKeyAttr);
                    if (forceDnConsistencyCheck) {
                        String id = getIdForDn(targetSession, dn);
                        if (id != null && targetSession.hasEntry(id)) {
                            // this is an entry managed by the current
                            // reference
                            attrToRemove.add(dn);
                        }
                    } else if (dn.endsWith(targetBaseDn)) {
                        // this is an entry managed by the current
                        // reference
                        attrToRemove.add(dn);
                    }
                } else {
                    attrToRemove.add(targetKeyAttr);
                }
            }
        } finally {
            oldAttrs.close();
        }
        try {
            if (attrToRemove.size() == oldAttr.size()) {
                // use the empty ref marker to avoid empty attr
                String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker();
                Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker);
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes key='%s' "
                                    + " mod_op='REPLACE_ATTRIBUTE' attrs='%s' [%s]",
                            sourceId, sourceDn, emptyAttribute, this));
                }
                sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REPLACE_ATTRIBUTE,
                        emptyAttribute);
            } else if (attrToRemove.size() > 0) {
                // remove the attribute managed by the current reference
                Attributes attrsToRemove = new BasicAttributes();
                attrsToRemove.put(attrToRemove);
                if (log.isDebugEnabled()) {
                    log.debug(String.format(
                            "LDAPReference.removeLinksForSource(%s): LDAP modifyAttributes dn='%s' "
                                    + " mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]",
                            sourceId, sourceDn, attrsToRemove, this));
                }
                sourceSession.dirContext.modifyAttributes(sourceDn, DirContext.REMOVE_ATTRIBUTE, attrsToRemove);
            }
        } catch (SchemaViolationException e) {
            if (isDynamic()) {
                // we are editing an entry that has no static part
                log.warn(String.format("cannot remove dynamic reference in field %s for source %s",
                        getFieldName(), sourceId));
            } else {
                // this is a real schma configuration problem, wrapup the
                // exception
                throw new DirectoryException(e);
            }
        }
    } catch (NamingException e) {
        throw new DirectoryException("removeLinksForSource failed: " + e.getMessage(), e);
    }
}

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

public ModificationItem[] getModificationItems() {
    if (!updateMode) {
        return new ModificationItem[0];
    }/*from w w  w.  j a  va2  s.  c om*/

    List tmpList = new LinkedList();
    NamingEnumeration attributesEnumeration = null;
    try {
        attributesEnumeration = updatedAttrs.getAll();

        // find attributes that have been changed, removed or added
        while (attributesEnumeration.hasMore()) {
            Attribute oneAttr = (Attribute) attributesEnumeration.next();

            collectModifications(oneAttr, tmpList);
        }
    } catch (NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        closeNamingEnumeration(attributesEnumeration);
    }

    if (log.isDebugEnabled()) {
        log.debug("Number of modifications:" + tmpList.size());
    }

    return (ModificationItem[]) tmpList.toArray(new ModificationItem[tmpList.size()]);
}

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

/**
 * Gets the values of a repeating attribute that may have range restriction options. If an attribute is range
 * restricted, it will appear in the attribute set with a ";range=i-j" option, where i and j indicate the start and
 * end index, and j is '*' if it is at the end.
 *
 * @param attributes/*  ww  w . j ava2  s  .  c om*/
 *            the attributes
 * @param attributeName
 *            the attribute name
 * @return the range restricted attribute
 * @throws NamingException
 *             the naming exception
 */
protected Attribute getRangeRestrictedAttribute(final Attributes attributes, final String attributeName)
        throws NamingException {
    final Attribute unrestricted = attributes.get(attributeName);
    if (unrestricted != null) {
        return unrestricted;
    }
    final NamingEnumeration<? extends Attribute> i = attributes.getAll();
    final String searchString = attributeName.toLowerCase(Locale.ENGLISH) + ';';
    while (i.hasMore()) {
        final Attribute attribute = i.next();
        if (attribute.getID().toLowerCase(Locale.ENGLISH).startsWith(searchString)) {
            return attribute;
        }
    }
    return null;
}