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

@SuppressWarnings("unchecked")
public static Map<String, String> parseDataAsMap(NamingEnumeration searchResults) {
    Map<String, String> resultAttrMap = null;
    int totalResultLogger = 0;
    if (searchResults == null) {
        return null;
    }//from ww w .  ja v a 2  s  .  c  o m
    // Loop through the search results
    while (searchResults.hasMoreElements()) {

        SearchResult sr = null;
        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) {
            if (resultAttrMap == null) {
                resultAttrMap = new HashMap<String, String>();
            }
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) {
                        String attrValue = (String) e.next();

                        resultAttrMap.put(attr.getID(), attrValue);
                    }
                }
            } catch (NamingException e) {
                Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e);
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }

    return resultAttrMap;
}

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

private void searchInLdap(final LdapVisitor visitor, final String filter, final String[] returningAttrs,
        final LdapContext ctx) {
    final SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setReturningAttributes(returningAttrs);
    ctls.setCountLimit(0); // set no limits

    final boolean paging = isPagedResultControlSupported(ctx);
    for (final String ldapBase : LDAPLoginModule.getLdapBases()) {
        int counter = 0;
        try {/*from   ww  w  .  j  a v  a  2 s  .c o  m*/
            if (paging) {
                byte[] cookie = null;
                ctx.setRequestControls(
                        new Control[] { new PagedResultsControl(PAGE_SIZE, Control.NONCRITICAL) });
                do {
                    final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
                    while (enm.hasMore()) {
                        visitor.visit(enm.next());
                    }
                    cookie = getCookie(ctx);
                } while (cookie != null);
            } else {
                final NamingEnumeration<SearchResult> enm = ctx.search(ldapBase, filter, ctls);
                while (enm.hasMore()) {
                    visitor.visit(enm.next());
                }
                counter++;
            }
        } catch (final SizeLimitExceededException e) {
            logError("SizeLimitExceededException after " + counter
                    + " records when getting all users from LDAP, reconfigure your LDAP server, hints: http://www.ldapbrowser.com/forum/viewtopic.php?t=14",
                    null);
        } catch (final NamingException e) {
            logError("NamingException when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase
                    + " on row::" + counter, e);
        } catch (final Exception e) {
            logError("Exception when trying to fetch deleted users from LDAP using ldapBase::" + ldapBase
                    + " on row::" + counter, e);
        }
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public <T> List<T> searchIndirections(Class<T> clazz, String filter) {
    if (null == filter) {
        return null;
    }/*from w w  w .  j  av  a 2s  .  c om*/

    LogUtils.debug(LOG, String.format("search %s with filter=%s", clazz.getName(), filter));

    OneMetaData oneMetaData = IndirectionsMetaData.get(clazz).getOne();

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(new String[] { oneMetaData.getIdAttr(), oneMetaData.getIndirectionAttr() });

    try {
        List<T> retVal = new ArrayList<T>();
        NamingEnumeration<SearchResult> results = ctx.search(oneMetaData.getContext(), filter, ctrl);
        while (results.hasMore()) {
            SearchResult result = results.next();
            retVal.add(fromAttributesToIndirections(clazz, result.getAttributes()));
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

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

/**
 * Checks if LDAP properties are different then OLAT properties of a User. If they are different a Map (OlatPropertyName,LDAPValue) is returned.
 * //  w ww  . j  av a 2 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(final Attributes attributes, final Identity identity) {
    final Map<String, String> olatPropertyMap = new HashMap<String, String>();
    final User user = identity.getUser();
    final NamingEnumeration<Attribute> neAttrs = (NamingEnumeration<Attribute>) attributes.getAll();
    try {
        while (neAttrs.hasMore()) {
            final Attribute attr = neAttrs.next();
            final String olatProperty = mapLdapAttributeToOlatProperty(attr.getID());
            if (olatProperty == null) {
                continue;
            }
            final String ldapValue = getAttributeValue(attr);
            final 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) {
            return null;
        }
        return olatPropertyMap;

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

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public List<Map<String, Object>> search(String context, String filter, String[] returningAttrs) {
    if (null == filter) {
        return null;
    }/*from  w ww.  j  a  v  a2 s  .  com*/

    LogUtils.debug(LOG, String.format("search %s with filter=%s, returningAttrs=%s", context, filter,
            Arrays.toString(returningAttrs)));

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(returningAttrs);

    try {
        List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>();
        NamingEnumeration<SearchResult> results = ctx.search(context, filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                retVal.add(fromAttributesToMap(result.getAttributes()));
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the map", e);
            }
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

From source file:org.nuxeo.wizard.RouterServlet.java

public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Context ctx = Context.instance(req);
    ParamCollector collector = ctx.getCollector();

    String refreshParam = req.getParameter("refresh");
    String directoryType = collector.getConfigurationParam("nuxeo.directory.type");

    if ("true".equals(refreshParam)) {
        currentPage.dispatchToJSP(req, resp);
        return;/*from w w  w  .  ja  v a  2 s .c om*/
    }

    if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam)
            || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) {
        try {
            if ("checkNetwork".equals(refreshParam)) {
                bindLdapConnection(collector, false);
                ctx.trackInfo("nuxeo.ldap.url", "info.host.found");
            } else if ("checkAuth".equals(refreshParam)) {
                bindLdapConnection(collector, true);
                ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success");
            } else {
                DirContext dirContext = new InitialDirContext(getContextEnv(collector, true));
                String searchScope;
                String searchBaseDn;
                String searchClass;
                String searchFilter;
                if ("checkUserLdapParam".equals(refreshParam)) {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope");
                    searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter");
                } else {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter");
                    searchClass = "";
                }

                SearchControls scts = new SearchControls();
                if ("onelevel".equals(searchScope)) {
                    scts.setSearchScope(SearchControls.ONELEVEL_SCOPE);
                } else {
                    scts.setSearchScope(SearchControls.SUBTREE_SCOPE);
                }
                String filter = String.format("(&(%s)(objectClass=%s))",
                        searchFilter.isEmpty() ? "objectClass=*" : searchFilter,
                        searchClass.isEmpty() ? "*" : searchClass);
                NamingEnumeration<SearchResult> results;
                try {
                    results = dirContext.search(searchBaseDn, filter, scts);
                    if (!results.hasMore()) {
                        ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult");
                    } else {
                        SearchResult result = results.next();
                        if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) {
                            // try not to display the root of the search
                            // base DN
                            result = results.next();
                        }
                        ctx.trackInfo("dn", result.getNameInNamespace());
                        Attributes attributes = result.getAttributes();
                        NamingEnumeration<String> ids = attributes.getIDs();
                        String id;
                        StringBuilder sb;
                        while (ids.hasMore()) {
                            id = ids.next();
                            NamingEnumeration<?> values = attributes.get(id).getAll();
                            sb = new StringBuilder();
                            while (values.hasMore()) {
                                sb.append(values.next()).append(" , ");
                            }
                            ctx.trackInfo(id, sb.substring(0, sb.length() - 3));
                        }
                    }
                } catch (NameNotFoundException e) {
                    ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn");
                    log.warn(e);
                }
                dirContext.close();
            }
        } catch (AuthenticationException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.auth.failed");
            log.warn(e);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.url", "error.host.not.found");
            log.warn(e);
        }
    }

    // Form submit
    if (!"default".equals(directoryType) && refreshParam.isEmpty()) {
        // first check bind to LDAP server
        try {
            bindLdapConnection(collector, true);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed");
            log.warn(e);
        }

        // then check mandatory fields
        if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required");
        }
        String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage");
        if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) {
            if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required");
            }
        }
        if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) {
            if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required");
            }
            if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required");
            }
        }
    }

    if (ctx.hasErrors() || ctx.hasInfos()) {
        currentPage.dispatchToJSP(req, resp);
    } else {
        currentPage.next().dispatchToJSP(req, resp, true);
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public List<Map<String, Object>> search(Class<?> clazz, String filter, String[] returningAttrs) {
    if (null == filter) {
        return null;
    }/*w  w  w.  j  ava 2s .  co  m*/

    LogUtils.debug(LOG, String.format("search %s with filter=%s, returningAttrs=%s", clazz.getName(), filter,
            Arrays.toString(returningAttrs)));

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(returningAttrs);

    try {
        List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>();
        NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                retVal.add(fromAttributesToMap(clazz, result.getAttributes()));
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the map", e);
            }
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public <T> List<T> search(Class<T> clazz, String filter) {
    if (null == filter) {
        return null;
    }//from  w  ww  . ja  va  2  s  .c  o  m

    LogUtils.debug(LOG, "search " + clazz.getName() + " with filter=" + filter);

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(EntityMetaData.getDefinedAttrNames(clazz));

    List<T> retVal = new ArrayList<T>();
    try {
        NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                T entity = null;
                if (sessionCache.containsKey(result.getNameInNamespace())) {
                    // guarantee the reference integrity for one search result
                    entity = (T) sessionCache.get(result.getNameInNamespace());
                } else {
                    entity = fromAttributesToEntity(clazz, result.getAttributes());
                    sessionCache.put(result.getNameInNamespace(), entity);
                }
                retVal.add(entity);
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the entity", e);
            }
        }
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
    return retVal;
}

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

/**
 * Creates User in OLAT and ads user to LDAP securityGroup Required Attributes have to be checked before this method.
 * /*from   ww w . j a v a  2s  .co m*/
 * @param userAttributes Set of LDAP Attribute of User to be created
 */
@SuppressWarnings("unchecked")
public void createAndPersistUser(final Attributes userAttributes) {
    // Get and Check Config
    final String[] reqAttrs = LDAPLoginModule.checkReqAttr(userAttributes);
    if (reqAttrs != null) {
        logWarn("Can not create and persist user, the following attributes are missing::"
                + ArrayUtils.toString(reqAttrs), null);
        return;
    }

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

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

    // Create Identity
    final Identity identity = securityManager.createAndPersistIdentityAndUser(uid, user,
            LDAPAuthenticationController.PROVIDER_LDAP, uid, null);
    // 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);
    logInfo("Created LDAP user username::" + uid);

}

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

@SuppressWarnings("unchecked")
public static List parseDataAsList(NamingEnumeration searchResults) {
    //Logger.info("Formatting the data as List", LDAPUtils.class   );
    List<String> resultAttr = null;
    int totalResultLogger = 0;
    if (searchResults == null) {
        return null;
    }//from ww  w .  j  av a  2  s.  co  m
    // Loop through the search results
    while (searchResults.hasMoreElements()) {

        SearchResult sr = null;
        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) {
            if (resultAttr == null) {
                resultAttr = new ArrayList();
            }
            try {
                for (NamingEnumeration ae = attrs.getAll(); ae.hasMore();) {
                    Attribute attr = (Attribute) ae.next();
                    for (NamingEnumeration e = attr.getAll(); e.hasMore(); totalResultLogger++) {
                        String attrValue = (String) e.next();

                        resultAttr.add(attrValue);
                    }
                }
            } catch (NamingException e) {
                Logger.error("Error ocuring while reading the attributes ", LDAPUtils.class, e);
            }

        } else {
            Logger.info("No attributes found on LDAP", LDAPUtils.class);
        }
    }

    return resultAttr;
}