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.ritchey.naming.InitialContextFactory.java

/**
 * Get Context that has access to default Namespace. This method won't be
 * called if a name URL beginning with java: is passed to an InitialContext.
 *
 * @see org.mortbay.naming.java.javaURLContextFactory
 * @param env a <code>Hashtable</code> value
 * @return a <code>Context</code> value
 *///from  w  w w.  j  av a  2  s .c om
public Context getInitialContext(Hashtable env) {
    Log.debug("InitialContext loaded");
    Context ctx = new localContextRoot(env);

    Properties properties = new Properties();
    try {
        properties.load(new FileInputStream("build.properties"));
    } catch (Exception e1) {
        e1.printStackTrace();
    }

    Context jdbc = null;
    try {
        jdbc = ctx.createSubcontext("jdbc");
    } catch (NamingException e) {
        try {
            jdbc = (Context) ctx.lookup("jdbc");
        } catch (NamingException e1) {
            e1.printStackTrace();
        }
    }
    Context ldap = null;
    try {
        ldap = ctx.createSubcontext("ldap");
    } catch (NamingException e) {
        try {
            ldap = (Context) ctx.lookup("ldap");
        } catch (NamingException e1) {
            e1.printStackTrace();
        }
    }

    Log.debug("getInitialContext");

    String databaseNames = properties.getProperty("database.jndi.names");
    if (databaseNames == null) {
        Log.warn(new RuntimeException("database.jndi.names is not defined"
                + " in build.properties as a comma separated list in " + "build.properties"));
        return ctx;
    }

    for (String database : databaseNames.split(" *, *")) {
        Log.debug("create " + database);
        try {
            createDs(database, properties, jdbc);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }

    try {
        createLdapStrings(properties, ldap);
    } catch (NamingException e1) {
        e1.printStackTrace();
    }

    String url = getValue(false, "picture", null, properties);
    try {
        ctx.bind("picture", url);
    } catch (NamingException ex) {
        Logger.getLogger(InitialContextFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    try {
        Log.debug("jdbc initial context = " + ctx.listBindings("jdbc"));
        NamingEnumeration<Binding> ldapBindings = ctx.listBindings("ldap");
        Log.debug("ldap initial context = " + ctx.listBindings("ldap"));
        while (ldapBindings.hasMore()) {
            Binding binding = ldapBindings.next();
            Log.debug("binding: " + binding.getName());
        }
    } catch (NamingException e) {
        e.printStackTrace();
    }
    return ctx;
}

From source file:eu.uqasar.util.ldap.LdapManager.java

private <T extends LdapEntity> List<T> getLdapEntities(int maximum, final String baseDN,
        final String preferredFilter, Class<T> clazz, Comparator<T> comparator) throws NamingException {
    if (maximum <= 0) {
        return Collections.emptyList();
    }//from  ww  w  . ja  va2 s .  c o m
    List<T> entities = new ArrayList<>();
    NamingEnumeration<SearchResult> results = searchLDAP(baseDN, preferredFilter);
    while (results.hasMoreElements() && entities.size() < maximum) {
        try {
            SearchResult group = results.next();
            Constructor<T> constructor = clazz.getConstructor(Attributes.class, LdapSettings.class);
            T entity = constructor.newInstance(group.getAttributes(), settings);
            entities.add(entity);
        } catch (LdapReferralException ex) {
            logger.warn(ex.getMessage(), ex);
        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
                | IllegalArgumentException | InvocationTargetException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
    Collections.sort(entities, comparator);
    return entities;
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves a list of all groups the user is a member of.
 * @param dirContext a DirContext/* w w w.  java  2s .  c  om*/
 * @param ldapUser the LdapUser to retrieve group membership for
 * @return A list of Strings representing the fully qualified DN of each group
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public List<String> getGroups(DirContext dirContext, LdapUser ldapUser) throws NamingException {
    final List<String> groupDns = new ArrayList<>();
    final String searchFilter = variableSubstitution(USER_GROUPS_FILTER, ldapUser);
    final SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, searchFilter, sc);
    while (hasMoreEnum(ne)) {
        final SearchResult result = ne.next();
        groupDns.add(result.getNameInNamespace());
    }
    closeQuietly(ne);
    return groupDns;
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves a list of all the groups in the directory.
 * @param dirContext a DirContext//from  w ww . j av  a  2s .c  om
 * @return A list of Strings representing the fully qualified DN of each group
 * @throws NamingException if an exception if thrown
 * @since 1.4.0
 */
public List<String> getGroups(DirContext dirContext) throws NamingException {
    final List<String> groupDns = new ArrayList<>();
    final SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final NamingEnumeration<SearchResult> ne = dirContext.search(BASE_DN, GROUPS_FILTER, sc);
    while (hasMoreEnum(ne)) {
        final SearchResult result = ne.next();
        groupDns.add(result.getNameInNamespace());
    }
    closeQuietly(ne);
    return groupDns;
}

From source file:edu.vt.middleware.ldap.ssl.DefaultHostnameVerifier.java

/**
 * Returns the CNs from the supplied certificate.
 *
 * @param  cert  to get CNs from/*from  ww  w  . j  a  v  a  2 s  .  c o  m*/
 *
 * @return  CNs
 */
private String[] getCNs(final X509Certificate cert) {
    final List<String> names = new ArrayList<String>();
    final String subjectPrincipal = cert.getSubjectX500Principal().toString();
    if (subjectPrincipal != null) {
        try {
            final LdapName subjectDn = new LdapName(subjectPrincipal);
            for (Rdn rdn : subjectDn.getRdns()) {
                final Attributes attrs = rdn.toAttributes();
                final NamingEnumeration<String> ids = attrs.getIDs();
                while (ids.hasMore()) {
                    final String id = ids.next();
                    if (id.toLowerCase().equals("cn") || id.toLowerCase().equals("commonname")
                            || id.toLowerCase().equals("2.5.4.3")) {
                        final Object value = attrs.get(id).get();
                        if (value != null) {
                            if (value instanceof String) {
                                names.add((String) value);
                            } else if (value instanceof Attribute) {
                                // for multi value RDNs the first value is used
                                final Object multiValue = ((Attribute) value).get();
                                if (multiValue != null && multiValue instanceof String) {
                                    names.add((String) multiValue);
                                }
                            }
                        }
                    }
                }
            }
        } catch (NamingException e) {
            if (this.logger.isWarnEnabled()) {
                this.logger.warn("Could not get distinguished name from subject " + subjectPrincipal, e);
            }
        }
    }
    return names.toArray(new String[names.size()]);
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Gets the LDAP users//w  ww .j a  v a 2  s  .c o m
 * 
 * @param ctx
 * @param loginAttributeName
 * @param searchStrs
 * @return
 */
static List<TPersonBean> getLdapUsers(LdapContext ctx, String loginAttributeName, List<String> searchStrs) {
    List<TPersonBean> personBeans = new LinkedList<TPersonBean>();
    if (ldapMap == null || ldapMap.isEmpty()) {
        LOGGER.error("There is no LDAP mapping in quartz-jobs.xml. Please provide!");
        return personBeans;
    }
    String firstNameAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.FIRST_NAME);
    String lastNameAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.LAST_NAME);
    String emailAttributeName = ldapMap.get(LdapUtil.LDAP_CONFIG.EMAIL);
    String phoneAttributName = ldapMap.get(LdapUtil.LDAP_CONFIG.PHONE);
    for (String searchStr : searchStrs) {
        LOGGER.debug("Searching by filter " + searchStr);
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        try {
            NamingEnumeration<SearchResult> results = ctx.search("", searchStr, ctls);
            while (results != null && results.hasMore()) {
                SearchResult sr = (SearchResult) results.next();
                TPersonBean personBean = getPersonBean(sr, loginAttributeName, firstNameAttributeName,
                        lastNameAttributName, emailAttributeName, phoneAttributName);
                if (personBean != null) {
                    LOGGER.debug("Search successful " + searchStr);
                    personBeans.add(personBean);
                }
            }
        } catch (NamingException e) {
            LOGGER.warn("Search failed with " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return personBeans;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser getIfValidUser(String cn, String password) {
    LDAPUser user = null;/*from w w  w .  j  a v a2s . c o m*/
    NamingEnumeration results = null;
    DirContext ctx = null;
    try {
        ctx = getAuthContext(cn, password);
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf",
                "createTimestamp" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user.setUsername((String) attributes.get("cn").get());
            if (attributes.get("sn") != null)
                user.setSurname((String) attributes.get("sn").get());
            if (attributes.get("givenName") != null)
                user.setGivenname((String) attributes.get("givenName").get());
            if (attributes.get("title") != null)
                user.setTitle((String) attributes.get("title").get());
            if (attributes.get("registeredAddress") != null)
                user.setPreferredMail((String) attributes.get("registeredAddress").get(0));
            if (attributes.get("mail") != null) {
                String mails = "";
                for (int i = 0; i < attributes.get("mail").size(); i++) {
                    if (i != 0)
                        mails = mails + ", ";
                    mails = mails + (String) attributes.get("mail").get(i);
                }
                user.setAdditionalMails(mails);
            }
            if (attributes.get("memberOf") != null) {
                for (int i = 0; i < attributes.get("memberOf").size(); i++) {
                    user.addGroup((String) attributes.get("memberOf").get(i));
                }
            }
            if (attributes.get("createTimestamp") != null) {
                String time = (String) attributes.get("createTimestamp").get();
                DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss");
                user.setCreationTime(ldapData.parse(time));
            }

        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } catch (ParseException ex) {
        _log.error(ex);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return user;
}

From source file:net.identio.server.service.authentication.ldap.LdapAuthenticationProvider.java

public AuthenticationResult validate(AuthMethod authMethod, Authentication authentication,
        TransactionData transactionData) {

    LdapAuthMethod ldapAuthMethod = (LdapAuthMethod) authMethod;
    UserPasswordAuthentication userPwAuthentication = (UserPasswordAuthentication) authentication;

    boolean validation;

    String userId = userPwAuthentication.getUserId();
    String password = userPwAuthentication.getPassword();

    GenericObjectPool<InitialLdapContext> pool = pools.get(authMethod.getName());

    InitialLdapContext ctx = null;

    try {/*www. j  av  a2  s  .c  o  m*/
        ctx = pool.borrowObject();

        // First we search the user
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        String searchFilter = ldapAuthMethod.getUserSearchFilter().replace("#UID",
                SecurityUtils.escapeLDAPSearchFilter(userId));

        NamingEnumeration<SearchResult> results = ctx.search(ldapAuthMethod.getBaseDn(), searchFilter,
                controls);

        SearchResult result;

        if (results.hasMoreElements()) {
            result = results.next();

            if (results.hasMoreElements()) {
                LOG.error("User ID {} is not unique in LDAP {}", userId, authMethod.getName());
                return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                        .setErrorStatus(AuthenticationErrorStatus.USER_NOT_UNIQUE);
            }
        } else {
            LOG.error("User ID {} does not exist in LDAP {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

        // Try to bind with the found user id
        validation = ((LdapConnectionFactory) pool.getFactory()).authenticate(authMethod.getName(),
                result.getNameInNamespace(), password);

        pool.returnObject(ctx);

        if (validation) {
            LOG.info("User {} successfully authenticated with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.SUCCESS).setUserId(userId)
                    .setAuthMethod(authMethod).setAuthLevel(authMethod.getAuthLevel());
        } else {
            LOG.error("Authentication failed for user {} with {}", userId, authMethod.getName());
            return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                    .setErrorStatus(AuthenticationErrorStatus.INVALID_CREDENTIALS);
        }

    } catch (Exception ex) {

        // Discard context
        try {
            if (ctx != null) {
                pool.invalidateObject(ctx);
            }
        } catch (Exception ex2) {
            LOG.error("An error occurend when authenticating user");
        }

        return new AuthenticationResult().setStatus(AuthenticationResultStatus.FAIL)
                .setErrorStatus(AuthenticationErrorStatus.TECHNICAL_ERROR);
    }

}

From source file:eu.uqasar.util.ldap.LdapManager.java

private LdapUser getUserByDNAndFilter(final String userDN, final String filter) throws NamingException {
    final String dnFilter = "(distinguishedName=" + userDN + ")";
    boolean conjunction = filter.startsWith("(&(") && filter.endsWith("))");
    String endFilter;/*from   w  w  w . j a v a 2s  .c om*/
    if (conjunction) {
        endFilter = filter.substring(0, filter.length() - 1) + dnFilter + ")";
    } else {
        endFilter = dnFilter;
    }
    NamingEnumeration<SearchResult> answer = getContext().search(settings.getUserFilterBaseDN(), endFilter,
            getDefaultSearchControls());
    while (answer.hasMoreElements()) {
        Attributes attr = answer.next().getAttributes();
        if (hasRequiredUserAttributesFilled(attr, settings)) {
            return new LdapUser(attr, settings);
        }
    }
    return null;
}

From source file:org.gbif.portal.registration.LDAPUtils.java

/**
 * Log attribute values for debug.//from  w  w w . j  a v  a2s  .co  m
 * @param attributes
 * @throws NamingException
 */
private void debugAttributes(Attributes attributes) throws NamingException {
    if (logger.isDebugEnabled()) {
        // useful for debug
        NamingEnumeration attributesEnum = attributes.getAll();
        while (attributesEnum != null && attributesEnum.hasMore()) {
            logger.debug("Attribute:" + attributesEnum.next());
        }
    }
}