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:org.springframework.security.ldap.SpringSecurityLdapTemplate.java

/**
 * Internal method extracted to avoid code duplication in AD search.
 *//*from   w  w w.  ja v  a2 s  .c om*/
public static DirContextOperations searchForSingleEntryInternal(DirContext ctx, SearchControls searchControls,
        String base, String filter, Object[] params) throws NamingException {
    final DistinguishedName ctxBaseDn = new DistinguishedName(ctx.getNameInNamespace());
    final DistinguishedName searchBaseDn = new DistinguishedName(base);
    final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params,
            buildControls(searchControls));

    if (logger.isDebugEnabled()) {
        logger.debug("Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn
                + "', filter = '" + filter + "'");
    }

    Set<DirContextOperations> results = new HashSet<>();
    try {
        while (resultsEnum.hasMore()) {
            SearchResult searchResult = resultsEnum.next();
            DirContextAdapter dca = (DirContextAdapter) searchResult.getObject();
            Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured");

            if (logger.isDebugEnabled()) {
                logger.debug("Found DN: " + dca.getDn());
            }
            results.add(dca);
        }
    } catch (PartialResultException e) {
        LdapUtils.closeEnumeration(resultsEnum);
        logger.info("Ignoring PartialResultException");
    }

    if (results.size() == 0) {
        throw new IncorrectResultSizeDataAccessException(1, 0);
    }

    if (results.size() > 1) {
        throw new IncorrectResultSizeDataAccessException(1, results.size());
    }

    return results.iterator().next();
}

From source file:com.egt.core.util.Utils.java

public static void traceContext(Context c, String name) {
    NameClassPair ncp;/*w ww. jav a  2  s  . c o m*/
    NamingEnumeration<NameClassPair> ncpenum;
    try {
        ncpenum = c.list(name);
        while (ncpenum.hasMore()) {
            ncp = ncpenum.next();
            if (ncp.getClassName().endsWith("javaURLContext")) {
                traceContext(c, ncp.getName());
            } else {
                Bitacora.logTrace(ncp.getName() + " = " + ncp.getClassName());
            }
        }
    } catch (NamingException ex) {
        Bitacora.logFatal(ThrowableUtils.getString(ex));
    }
}

From source file:net.spfbl.core.Reverse.java

public static boolean hasValidNameServers(String hostname) throws NamingException {
    if ((hostname = Domain.normalizeHostname(hostname, false)) == null) {
        return false;
    } else {//from w  ww  . ja va  2 s.  co m
        try {
            Attributes attributesNS = Server.getAttributesDNS(hostname, new String[] { "NS" });
            if (attributesNS != null) {
                Enumeration enumerationNS = attributesNS.getAll();
                while (enumerationNS.hasMoreElements()) {
                    Attribute attributeNS = (Attribute) enumerationNS.nextElement();
                    NamingEnumeration enumeration = attributeNS.getAll();
                    while (enumeration.hasMoreElements()) {
                        String ns = (String) enumeration.next();
                        if (Domain.isHostname(ns)) {
                            return true;
                        }
                    }
                }
            }
            return false;
        } catch (NameNotFoundException ex) {
            return false;
        }
    }
}

From source file:net.spfbl.core.Reverse.java

public static TreeSet<String> getAddressSet(String hostname) throws NamingException {
    if ((hostname = Domain.normalizeHostname(hostname, false)) == null) {
        return null;
    } else {/*from   www.  jav  a 2 s. com*/
        TreeSet<String> ipSet = new TreeSet<String>();
        Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" });
        if (attributesA != null) {
            Enumeration enumerationA = attributesA.getAll();
            while (enumerationA.hasMoreElements()) {
                Attribute attributeA = (Attribute) enumerationA.nextElement();
                NamingEnumeration enumeration = attributeA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv4.isValidIPv4(address)) {
                        address = SubnetIPv4.normalizeIPv4(address);
                        ipSet.add(address);
                    }
                }
            }
        }
        Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" });
        if (attributesAAAA != null) {
            Enumeration enumerationAAAA = attributesAAAA.getAll();
            while (enumerationAAAA.hasMoreElements()) {
                Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement();
                NamingEnumeration enumeration = attributeAAAA.getAll();
                while (enumeration.hasMoreElements()) {
                    String address = (String) enumeration.next();
                    if (SubnetIPv6.isValidIPv6(address)) {
                        address = SubnetIPv6.normalizeIPv6(address);
                        ipSet.add(address);
                    }
                }
            }
        }
        return ipSet;
    }
}

From source file:edu.lafayette.metadb.model.userman.UserManDAO.java

/**
 * Get the LDAP DN for a user./*from  w w w.jav a  2 s .co m*/
 * @param searchUser
 * @param searchPassword
 * @param userName
 * @return
 */
@SuppressWarnings("unchecked")
private static String getDN(String searchUser, String searchPassword, String userName) {
    // The resultant DN
    String result;

    // Set up environment for creating initial context
    Hashtable env = new Hashtable(11);
    env.put(javax.naming.Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(javax.naming.Context.PROVIDER_URL, Global.LDAP_URL);

    // Use admin credencials for search// Authenticate
    env.put(javax.naming.Context.SECURITY_AUTHENTICATION, "Simple");
    env.put(javax.naming.Context.SECURITY_PRINCIPAL, searchUser);
    env.put(javax.naming.Context.SECURITY_CREDENTIALS, searchPassword);

    DirContext ctx = null;
    try {
        // Create initial context
        ctx = new InitialDirContext(env);
        //MetaDbHelper.note("Created LDAP context");

        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute(Global.LDAP_ID, userName));
        //MetaDbHelper.note("Created attributes");

        // look up attributes
        try {
            //MetaDbHelper.note("Setting up query");

            SearchControls ctrls = new SearchControls();
            ctrls.setSearchScope(Global.LDAP_SCOPE);

            NamingEnumeration<SearchResult> answer = ctx.search(Global.LDAP_URL + Global.LDAP_CONTEXT,
                    "(&({0}={1}))", new Object[] { Global.LDAP_ID, userName }, ctrls);

            //MetaDbHelper.note("NamingEnumeration retrieved");

            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (StringUtils.isEmpty(Global.LDAP_CONTEXT)) {
                    result = sr.getName();
                } else {
                    result = (sr.getName() + "," + Global.LDAP_CONTEXT);
                }

                //MetaDbHelper.note("Got DN: "+result);

                return result;
            }
        } catch (NamingException e) {
            MetaDbHelper.logEvent(e);
            //MetaDbHelper.note("LDAP Error: Failed Search");
        }
    } catch (NamingException e) {
        MetaDbHelper.logEvent(e);
        //MetaDbHelper.note("LDAP Error: Failed authentication");
    } finally {
        // Close the context when we're done
        try {
            if (ctx != null)
                ctx.close();
        } catch (NamingException e) {
        }
    }
    // No DN match found
    return null;
}

From source file:org.codehaus.groovy.grails.plugins.springsecurity.ldap.GrailsLdapRoleMapper.java

/**
 * {@inheritDoc}// w w  w  .ja  va  2 s .  c  o m
 * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes)
 */
public Object mapFromAttributes(final Attributes attributes) throws NamingException {
    Attribute roleAttr = attributes.get(_groupRoleAttributeName);

    NamingEnumeration<?> ne = roleAttr.getAll();
    // assert ne.hasMore();
    Object group = ne.next();
    String role = group.toString();

    return new GrantedAuthorityImpl(_rolePrefix + role.toUpperCase());
}

From source file:com.aes.touresbalon.touresbalonoms.utilities.ContactAttributeMapperJSON.java

@Override
public Object mapFromAttributes(Attributes atrbts) throws NamingException {
    NamingEnumeration<String> ids = atrbts.getIDs();
    JSONObject jo = new JSONObject();
    while (ids.hasMore()) {
        String id = ids.next();
        jo.put(id, atrbts.get(id).get());
    }/*  w ww.j  av a2s.c o  m*/
    return jo.toString();

}

From source file:EnvEntry.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/plain");
    PrintWriter out = res.getWriter();

    try {//from  www. j  av a 2s .  c  o  m
        Context initCtx = new InitialContext();
        NamingEnumeration e = initCtx.listBindings("java:comp/env");

        while (e.hasMore()) {
            Binding binding = (Binding) e.next();
            out.println("Name: " + binding.getName());
            out.println("Type: " + binding.getClassName());
            out.println("Value: " + binding.getObject());
            out.println();
        }
    } catch (NamingException e) {
        e.printStackTrace(out);
    }
}

From source file:ldap.UserAccountImpl.java

public UserAccountImpl(Attributes atts) throws NamingException {
    NamingEnumeration attList = atts.getAll();
    while (attList.hasMore()) {
        Attribute att = (Attribute) attList.next();
        put(att);//from   ww  w  .j  a v a2s. c o  m
    }
}

From source file:de.interseroh.report.test.security.LdapServerTest.java

@Test
public void testJndiSun() throws NamingException {
    Hashtable<String, String> contextParams = new Hashtable<String, String>();
    contextParams.put(Context.PROVIDER_URL, "ldap://ldap.xxx:389");
    contextParams.put(Context.SECURITY_PRINCIPAL, USER_LDAP);
    contextParams.put(Context.SECURITY_CREDENTIALS, PASSWORD_LDAP);
    contextParams.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    DirContext dirContext = new InitialDirContext(contextParams);

    Attributes attributes = dirContext.getAttributes("", new String[] { "namingContexts" });
    Attribute attribute = attributes.get("namingContexts");
    NamingEnumeration<?> all = attribute.getAll();
    while (all.hasMore()) {
        String next = (String) all.next();
        logger.info(next);/*from   ww w  .j a  v a 2 s.  c o m*/
    }
}