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:io.apiman.tools.ldap.ApimanLdapServer.java

@Test
public void startLdapServer() throws Exception {
    DirContext ctx = createContext();
    Assert.assertNotNull(ctx);//from   ww  w  .j  av a2 s  .c o  m

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    NamingEnumeration<SearchResult> result = ctx.search("o=apiman", "(ObjectClass=*)", controls);

    int count = 0;
    while (result.hasMore()) {
        result.next();
        count++;
    }

    String url = "ldap://" + LDAP_SERVER + ":" + ldapServer.getPort();
    System.out.println("======================================================");
    System.out.println("LDAP server started successfully.");
    System.out.println("");
    System.out.println("  URL: " + url);
    System.out.println("  Node Count: " + count);
    System.out.println("  Direct Bind DN: cn=${username},ou=developers,ou=people,o=apiman");
    System.out.println("======================================================");
    System.out.println("");
    System.out.println("");
    System.out.println("Press Enter to stop the LDAP server.");
    new BufferedReader(new InputStreamReader(System.in)).readLine();
    System.out.println("Shutting down the LDAP server...");
}

From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java

/**
 * check if client's ip is listed in the Ldap Roles if yes, return true and
 * update ldapent. if not, return false/*from   w  ww.j a v a2 s .co  m*/
 * */
@SuppressWarnings("unchecked")
private boolean getLdapRoleEntryFromUserIp(String userIp, LdapRoleEntry ldapent) throws NamingException {
    String ipMember = hdfsIpSchemaStrPrefix + userIp;
    Attributes matchAttrs = new BasicAttributes(true);
    matchAttrs.put(new BasicAttribute(hdfsIpSchemaStr, ipMember));
    matchAttrs.put(new BasicAttribute(hdfsUidSchemaStr));
    matchAttrs.put(new BasicAttribute(hdfsPathSchemaStr));

    String[] attrIDs = { hdfsUidSchemaStr, hdfsPathSchemaStr };

    NamingEnumeration<SearchResult> results = lctx.search(baseName, matchAttrs, attrIDs);
    if (results.hasMore()) {
        String userId = null;
        ArrayList<Path> paths = new ArrayList<Path>();
        SearchResult sr = results.next();
        Attributes attrs = sr.getAttributes();
        for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) {
            Attribute attr = (Attribute) ne.next();
            if (hdfsUidSchemaStr.equalsIgnoreCase(attr.getID())) {
                userId = (String) attr.get();
            } else if (hdfsPathSchemaStr.equalsIgnoreCase(attr.getID())) {
                for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                    String pathStr = (String) e.next();
                    paths.add(new Path(pathStr));
                }
            }
        }
        ldapent.init(userId, paths);
        if (LOG.isDebugEnabled())
            LOG.debug(ldapent);
        return true;
    }
    LOG.info("Ip address " + userIp + " is not authorized to access the proxy server");
    return false;
}

From source file:edu.vt.middleware.ldap.auth.handler.CompareAuthorizationHandler.java

/** {@inheritDoc} */
public void process(final AuthenticationCriteria ac, final LdapContext ctx) throws NamingException {
    // make DN the first filter arg
    final List<Object> filterArgs = new ArrayList<Object>();
    filterArgs.add(ac.getDn());/* w  w  w. j  av  a  2  s .c  o m*/
    filterArgs.addAll(this.searchFilter.getFilterArgs());

    // perform ldap compare operation
    NamingEnumeration<SearchResult> results = null;
    try {
        results = ctx.search(ac.getDn(), this.searchFilter.getFilter(), filterArgs.toArray(),
                LdapConfig.getCompareSearchControls());
        if (!results.hasMore()) {
            throw new AuthorizationException("Compare failed");
        }
    } finally {
        if (results != null) {
            results.close();
        }
    }
}

From source file:edu.vt.middleware.ldap.handler.CompareAuthorizationHandler.java

/** {@inheritDoc} */
public void process(final AuthenticationCriteria ac, final LdapContext ctx) throws NamingException {
    // make DN the first filter arg
    final List<Object> filterArgs = new ArrayList<Object>();
    filterArgs.add(ac.getDn());//  w  w  w. j a  v a  2  s .c o m
    filterArgs.addAll(this.searchFilter.getFilterArgs());

    // perform ldap compare operation
    NamingEnumeration<SearchResult> results = null;
    try {
        results = ctx.search(ac.getDn(), this.searchFilter.getFilter(), filterArgs.toArray(),
                LdapConfig.getCompareSearchControls());
        if (!results.hasMore()) {
            throw new AuthenticationException("Compare failed");
        }
    } finally {
        if (results != null) {
            results.close();
        }
    }
}

From source file:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java

/**
 * Ensure able to obtain credentials./*  w ww .  ja  va 2  s .  c  o m*/
 */
public void testObtainCredentials() throws Exception {

    final Charset ASCII = Charset.forName("ASCII");

    // Calculate the expected credential
    String expectedRaw = "daniel:officefloor:password";
    MessageDigest digest = MessageDigest.getInstance("MD5");
    digest.update(expectedRaw.getBytes(ASCII));
    byte[] expectedBytes = digest.digest();
    String expectedCredentials = Base64.encodeBase64String(expectedBytes).trim();

    // Obtain the context
    DirContext context = this.ldap.getDirContext();

    // Obtain the People context
    DirContext people = (DirContext) context.lookup("ou=People,dc=officefloor,dc=net");
    assertNotNull("Should have People context", people);

    // Search for person
    NamingEnumeration<SearchResult> results = people.search("", "(&(objectClass=inetOrgPerson)(uid=daniel))",
            null);
    assertTrue("Expecting to find daniel entry", results.hasMore());
    SearchResult result = results.next();
    assertFalse("Should only have the daniel entry", results.hasMore());

    // Obtain the digest MD5 credentials for Daniel
    String digestMd5Credential = null;
    Attributes attributes = result.getAttributes();
    Attribute passwordAttribute = attributes.get("userPassword");
    for (NamingEnumeration<?> enumeration = passwordAttribute.getAll(); enumeration.hasMore();) {
        byte[] credentials = (byte[]) enumeration.next();
        String text = new String(credentials, ASCII);

        // Determine if MD5 credential
        if (text.toUpperCase().startsWith("{MD5}")) {
            // Found MD5 credential
            digestMd5Credential = text.substring("{MD5}".length());
        }
    }
    assertNotNull("Must have digest MD5 credential", digestMd5Credential);

    // Ensure correct credentials
    assertEquals("Incorrect DIGEST MD5 credentials", expectedCredentials, digestMd5Credential);
}

From source file:org.hyperic.hq.plugin.netservices.LDAPCollector.java

public void collect() {

    // Setup initial LDAP properties
    Properties env = new Properties();
    Properties props = getProperties();

    // Set our default factory name if one is not given
    String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
    if (factoryName == null) {
        env.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    }//w  ww . j  av a2 s.  c  om

    // Set the LDAP url
    if (isSSL()) {
        env.put("java.naming.ldap.factory.socket", LDAPSSLSocketFactory.class.getName());
        env.put(Context.SECURITY_PROTOCOL, "ssl");
    }
    String providerUrl = "ldap://" + getHostname() + ":" + getPort();
    env.setProperty(Context.PROVIDER_URL, providerUrl);

    // For log track
    setSource(providerUrl);

    // Follow referrals automatically
    env.setProperty(Context.REFERRAL, "follow");

    // Base DN
    String baseDN = props.getProperty(PROP_BASEDN);
    if (baseDN == null) {
        setErrorMessage("No Base DN given, refusing login");
        setAvailability(false);
        return;
    }

    // Search filter
    String filter = props.getProperty(PROP_FILTER);

    // Load any information we may need to bind
    String bindDN = props.getProperty(PROP_BINDDN);
    String bindPW = props.getProperty(PROP_BINDPW);
    if (bindDN != null) {
        env.setProperty(Context.SECURITY_PRINCIPAL, bindDN);
        env.setProperty(Context.SECURITY_CREDENTIALS, bindPW);
        env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
    }

    if (log.isDebugEnabled()) {
        log.debug("Using LDAP environment: " + env);
    }

    try {
        startTime();
        InitialLdapContext ctx = new InitialLdapContext(env, null);
        endTime();

        setAvailability(true);

        // If a search filter is specified, run the search and return the
        // number of matches as a metric
        if (filter != null) {
            log.debug("Using LDAP filter=" + filter);
            NamingEnumeration answer = ctx.search(baseDN, filter, getSearchControls());

            long matches = 0;
            while (answer.hasMore()) {
                matches++;
                answer.next();
            }

            setValue("NumberofMatches", matches);
        }
    } catch (Exception e) {
        setAvailability(false);
        if (log.isDebugEnabled()) {
            log.debug("LDAP check failed: " + e, e);
        }

        setErrorMessage("LDAP check failed: " + e);
    }
}

From source file:net.officefloor.plugin.jndi.ldap.CredentialStoreTest.java

/**
 * Ensure able to obtain the roles.//  www  .j  a  va 2s .c om
 */
public void testObtainRoles() throws Exception {

    // Obtain the context
    DirContext context = this.ldap.getDirContext();

    // Obtain the People context
    DirContext people = (DirContext) context.lookup("ou=People,dc=officefloor,dc=net");
    assertNotNull("Should have People context", people);

    // Search for person
    NamingEnumeration<SearchResult> personResults = people.search("",
            "(&(objectClass=inetOrgPerson)(uid=daniel))", null);
    assertTrue("Expecting to find daniel entry", personResults.hasMore());
    SearchResult daniel = personResults.next();
    assertFalse("Should only have the daniel entry", personResults.hasMore());

    // Obtain the Groups context
    DirContext groups = (DirContext) context.lookup("ou=Groups,dc=officefloor,dc=net");
    assertNotNull("Should have Groups context", groups);

    // Search for groups containing daniel
    String danielDn = daniel.getNameInNamespace();
    NamingEnumeration<SearchResult> groupResults = groups.search("",
            "(&(objectClass=groupOfNames)(member=" + danielDn + "))", null);

    // Obtain the listing of roles for daniel
    List<String> roles = new ArrayList<String>(2);
    for (; groupResults.hasMore();) {
        SearchResult group = groupResults.next();

        // Obtain the role from the group
        String role = (String) group.getAttributes().get("ou").get();

        // Add role to listing
        roles.add(role);
    }

    // Ensure the correct roles
    assertEquals("Incorrect number of roles", 2, roles.size());
    assertTrue("Missing user role", roles.contains("developer"));
    assertTrue("Missing developer role", roles.contains("committer"));
}

From source file:org.archone.ad.authentication.ShoadRealm.java

@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    if (principals == null) {
        throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
    }//from  w w  w .  ja v a 2 s. co  m

    String username = (String) getAvailablePrincipal(principals);

    Set<String> roleNames = null;
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContextAdapter context = (DirContextAdapter) contextSource.getReadOnlyContext();
    try {
        String userDn = (String) getUserDn(username);

        DirContextAdapter superuserGroup = (DirContextAdapter) new LdapTemplate(contextSource)
                .lookup("cn=administrator,cn=shoad");
        Set<String> superusers = superuserGroup.getAttributeSortedStringSet("uniqueMember");

        Logger.getLogger("AUTH").log(Level.INFO, "THE SIZE IS {0}", new Integer(superusers.size()).toString());

        if (superusers.contains(userDn)) {
            Logger.getLogger("AUTH").log(Level.INFO, "SUPERUSER LOGGED IN");
            roleNames.add("SUPERUSER");
        }

        NamingEnumeration<SearchResult> searchResults = context.search("",
                adConfiguration.getMembershipSearchFilter(), new String[] { userDn }, controls);
        while (searchResults.hasMore()) {
            GroupDn groupDn = new GroupDn(searchResults.next().getNameInNamespace(),
                    adConfiguration.getGroupsRdn());
            roleNames.add(groupDn.getAsGroupId());
        }

    } catch (javax.naming.NamingException ex) {
        Logger.getLogger(ShoadRealm.class.getName()).log(Level.SEVERE, null, ex);
        throw new AuthorizationException(ex);
    }

    SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);

    return info;
}

From source file:org.nuxeo.ecm.platform.io.test.TestIORemoteCopy.java

@Before
public void setUp() throws Exception {

    System.setProperty("org.nuxeo.runtime.streaming.isServer", "false");
    System.setProperty("org.nuxeo.runtime.server.port", "62475");
    System.setProperty("org.nuxeo.runtime.server.host", "localhost");
    System.setProperty("org.nuxeo.runtime.streaming.serverLocator", STREAM_SERVER_URL);

    super.setUp();

    // the core bundle
    deployContrib("org.nuxeo.ecm.core", "OSGI-INF/CoreService.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "TypeService.xml");
    deployContrib("org.nuxeo.ecm.core", "OSGI-INF/SecurityService.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "RepositoryService.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "test-CoreExtensions.xml");

    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "CoreEventListenerService.xml");

    // repo test case misc
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "DefaultPlatform.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "RepositoryManager.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "LifeCycleCoreExtensions.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "LifeCycleService.xml");
    // specific files
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "io-test-framework.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "io-test-contrib.xml");

    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "RemotingService.xml");
    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "JBossLoginConfig.xml");
    // donnot : deployContrib("StreamingServer.xml");

    deployBundle("org.nuxeo.ecm.relations.api");
    deployBundle("org.nuxeo.ecm.relations");
    deployBundle("org.nuxeo.ecm.relations.jena");
    deployBundle("org.nuxeo.ecm.platform.comment.api");
    deployBundle("org.nuxeo.ecm.platform.comment");

    InitialContext ctx1 = new InitialContext();
    System.err.println(ctx1.lookup("java:/comment-relations"));
    NamingEnumeration<NameClassPair> en = ctx1.list("/");
    while (en.hasMore()) {
        Object o = en.nextElement();
        System.err.println(o);//from w  ww  . j a  va2s .c  o  m
    }

    deployContrib("org.nuxeo.ecm.platform.io.core.tests", "commentService-config-bundle.xml");

    Map<String, Serializable> ctx = new HashMap<String, Serializable>();
    ctx.put("username", SecurityConstants.ADMINISTRATOR);
    coreSession = CoreInstance.getInstance().open(localRepositoryName, ctx);

    ioService = Framework.getService(IOManager.class);
}

From source file:jndi.view.JndiView.java

/**
 * @param path//from   ww  w  .j  ava2  s .  c o  m
 *        the path to browse
 * @return {@link List} of {@link JndiEntry}s
 * @throws NamingException
 *         on exception
 */
private List<JndiEntry> browse(final String path) throws NamingException {
    final JndiCallback<List<JndiEntry>> contextCallback = new JndiCallback<List<JndiEntry>>() {
        @Override
        public List<JndiEntry> doInContext(final Context context) throws NamingException {
            if (JAVA_GLOBAL.equals(path)) {
                // Do a little trick to handle "java:global"
                final NamingEnumeration<Binding> root = context.listBindings("");
                Context javaGlobalContext = null;
                while (root.hasMore()) {
                    final Binding binding = root.next();
                    if (JAVA_GLOBAL.equals(binding.getName())) {
                        final Object obj = binding.getObject();
                        if (obj instanceof Context) {
                            javaGlobalContext = (Context) obj;
                        }
                        break;
                    }
                }
                if (javaGlobalContext != null) {
                    return examineBindings(javaGlobalContext, path, javaGlobalContext.listBindings(""));
                }
                logger.warning("Unable to browse \"" + JAVA_GLOBAL + "\" namespace!");
                return emptyList();
            }
            return examineBindings(context, path, context.listBindings(path));
        }
    };
    return jndiTemplate.execute(contextCallback);
}