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:py.una.pol.karaku.security.KarakuUserService.java

private List<KarakuPermission> loadAuthoritiesByDn(String uid) {

    List<KarakuPermission> listaRoles = new ArrayList<KarakuPermission>();

    try {/* w w w  .  j  a  va2  s  . c  o  m*/
        DirContext ctx = getInitialDirContext(propertiesUtil.get(LDAP_ADMIN_KEY),
                propertiesUtil.get(LDAP_ADMIN_PASS_KEY));
        Attributes matchAttrs = new BasicAttributes(true);
        matchAttrs.put(new BasicAttribute("member", getRealUsername(uid)));
        NamingEnumeration<SearchResult> answer = ctx.search("ou=permissions", matchAttrs);

        while (answer.hasMore()) {
            SearchResult searchResult = answer.next();
            Attributes attributes = searchResult.getAttributes();
            Attribute attr = attributes.get("cn");
            String rol = (String) attr.get();
            KarakuPermission grantedAuthority = new KarakuPermission(rol);
            listaRoles.add(grantedAuthority);
        }

        return listaRoles;
    } catch (NamingException e) {
        LOG.warn("Can't create Ldap Context", e);
        return Collections.emptyList();
    }
}

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.");
    }// w  ww.  ja  v  a2 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:com.surevine.chat.auth.GroupAuthorisationFilter.java

/**
 * Get a list of the members of a group, searching for the group using an
 * LDAP filter expression and scope.//from   w ww. ja v a  2  s  .c om
 * 
 * @param filter
 *            LDAP search filter (see RFC2254)
 * @param scope
 *            One of SearchControls.OBJECT_SCOPE,
 *            SearchControls.ONELEVEL_SCOPE, or SearchControls.SUBTREE_SCOPE
 *            (see javax.naming.directory.SearchControls)
 * @return List of usernames
 * @throws NamingException
 * @throws LdapException
 *             On any LDAP error
 */
private Collection<String> getGroupMembers(final String groupName) throws NamingException {
    _logger.debug("Looking for members of " + groupName);
    String filter = "cn=" + groupName;
    Collection<String> memberList = new HashSet<String>(20);

    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<SearchResult> objects;
    DirContext ctx = getLdapConnection();

    objects = ctx.search("ou=groups", filter, controls);

    while (objects.hasMore()) {
        SearchResult sr = (SearchResult) objects.next();
        Attributes attributes = sr.getAttributes();
        Attribute attribute = attributes.get("member");

        if (attribute != null) {
            NamingEnumeration<?> valueEnum = attribute.getAll();

            while (valueEnum.hasMore()) {
                String value = valueEnum.next().toString();

                final String searchFor = "cn=";
                int start = value.indexOf(searchFor);
                int end = value.indexOf(',', start);

                if (start >= 0 && end >= 0) {
                    String name = value.substring(start + searchFor.length(), end);
                    _logger.debug(name + " is a chatter");
                    memberList.add(name);
                }
            }
        }
    }
    _logger.debug("Returning a total of " + memberList.size() + " chatters");
    return memberList;
}

From source file:com.clustercontrol.port.protocol.ReachAddressDNS.java

/**
 * DNS????????/*from w  w w .j  a v a  2 s .c om*/
 *
 * @param addressText
 * @return DNS
 */
/*
 * (non-Javadoc)
 *
 * @see
 * com.clustercontrol.port.protocol.ReachAddressProtocol#isRunning(java.
 * lang.String)
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);
        String addressStr = address.getHostAddress();
        if (address instanceof Inet6Address) {
            addressStr = "[" + addressStr + "]";
        }

        bufferOrg.append("Monitoring the DNS Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        props.put(Context.PROVIDER_URL, "dns://" + addressStr + ":" + m_portNo);
        props.put("com.sun.jndi.dns.timeout.initial", String.valueOf(m_timeout));
        props.put("com.sun.jndi.dns.timeout.retries", "1");

        InitialDirContext idctx = null;

        String hostname = HinemosPropertyUtil.getHinemosPropertyStr("monitor.port.protocol.dns", "localhost");
        m_log.debug("The hostname from which to retrieve attributes is " + hostname);

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");

                start = HinemosTime.currentTimeMillis();

                idctx = new InitialDirContext(props);
                Attributes attrs = idctx.getAttributes(hostname);

                end = HinemosTime.currentTimeMillis();

                bufferOrg.append("\n");
                NamingEnumeration<? extends Attribute> allAttr = attrs.getAll();
                while (allAttr.hasMore()) {
                    Attribute attr = allAttr.next();
                    bufferOrg.append("Attribute: " + attr.getID() + "\n");
                    NamingEnumeration<?> values = attr.getAll();
                    while (values.hasMore())
                        bufferOrg.append("Value: " + values.next() + "\n");
                }
                bufferOrg.append("\n");

                m_response = end - start;

                if (m_response > 0) {
                    if (m_response < m_timeout) {
                        result = result + ("Response Time = " + m_response + "ms");
                    } else {
                        m_response = m_timeout;
                        result = result + ("Response Time = " + m_response + "ms");
                    }
                } else {
                    result = result + ("Response Time < 1ms");
                }

                retry = false;
                isReachable = true;

            } catch (NamingException e) {
                result = (e.getMessage() + "[NamingException]");
                retry = true;
                isReachable = false;
            } catch (Exception e) {
                result = (e.getMessage() + "[Exception]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                try {
                    if (idctx != null) {
                        idctx.close();
                    }
                } catch (NamingException e) {
                    m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(DNS/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

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

protected void destroyRecursively(String dn, DirContext ctx, int limit) throws NamingException {
    if (limit == 0) {
        log.warn("Reach recursion limit, stopping deletion at" + dn);
        return;/*from  ww  w.  jav  a  2 s  .  co m*/
    }
    SearchControls scts = new SearchControls();
    scts.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    String providerUrl = (String) ctx.getEnvironment().get(Context.PROVIDER_URL);
    NamingEnumeration<SearchResult> children = ctx.search(dn, "(objectClass=*)", scts);
    try {
        while (children.hasMore()) {
            SearchResult child = children.next();
            String subDn = child.getName();
            if (!USE_EXTERNAL_TEST_LDAP_SERVER && subDn.endsWith(providerUrl)) {
                subDn = subDn.substring(0, subDn.length() - providerUrl.length() - 1);
            } else {
                subDn = subDn + ',' + dn;
            }
            destroyRecursively(subDn, ctx, limit);
        }
    } catch (SizeLimitExceededException e) {
        log.warn("SizeLimitExceededException: trying again on partial results " + dn);
        if (limit == -1) {
            limit = 100;
        }
        destroyRecursively(dn, ctx, limit - 1);
    }
    ctx.destroySubcontext(dn);
}

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

/**
 * This will enumerate through the supplied <code>NamingEnumeration</code> and
 * return a List of those results. The results are unaltered and the dn is
 * ignored. Any exceptions passed into this method will be ignored and results
 * will be returned as if no exception occurred.
 *
 * @param  sc  <code>SearchCriteria</code> used to find enumeration
 * @param  en  <code>NamingEnumeration</code> LDAP results
 * @param  ignore  <code>Class[]</code> of exception types to ignore
 *
 * @return  <code>List</code> - LDAP results
 *
 * @throws  NamingException  if the LDAP returns an error
 *//*from   ww  w. j  a v  a2  s.  c  o m*/
public List<O> process(final SearchCriteria sc, final NamingEnumeration<? extends R> en,
        final Class<?>[] ignore) throws NamingException {
    final List<O> results = new ArrayList<O>();
    if (en != null) {
        try {
            while (en.hasMore()) {
                final O o = processResult(sc, en.next());
                if (o != null) {
                    results.add(o);
                }
            }
        } catch (NamingException e) {
            boolean ignoreException = false;
            if (ignore != null && ignore.length > 0) {
                for (Class<?> ne : ignore) {
                    if (ne.isInstance(e)) {
                        if (this.logger.isDebugEnabled()) {
                            this.logger.debug("Ignoring naming exception", e);
                        }
                        ignoreException = true;
                        break;
                    }
                }
            }
            if (!ignoreException) {
                throw e;
            }
        }
    }
    return results;
}

From source file:org.jsecurity.realm.activedirectory.ActiveDirectoryRealm.java

private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
    Set<String> roleNames;
    roleNames = new LinkedHashSet<String>();

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    String userPrincipalName = username;
    if (principalSuffix != null) {
        userPrincipalName += principalSuffix;
    }/*from  w  w  w .  j av a2s . c om*/

    String searchFilter = "(&(objectClass=*)(userPrincipalName=" + userPrincipalName + "))";

    NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchCtls);

    while (answer.hasMoreElements()) {
        SearchResult sr = (SearchResult) answer.next();

        if (log.isDebugEnabled()) {
            log.debug("Retrieving group names for user [" + sr.getName() + "]");
        }

        Attributes attrs = sr.getAttributes();

        if (attrs != null) {
            NamingEnumeration ae = attrs.getAll();
            while (ae.hasMore()) {
                Attribute attr = (Attribute) ae.next();

                if (attr.getID().equals("memberOf")) {

                    Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);

                    if (log.isDebugEnabled()) {
                        log.debug("Groups found for user [" + username + "]: " + groupNames);
                    }

                    Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
                    roleNames.addAll(rolesForGroups);
                }
            }
        }
    }
    return roleNames;
}

From source file:org.apache.cxf.sts.ldap.LDAPClaimsTest.java

@org.junit.Test
@org.junit.Ignore//from  w  w  w . ja  v  a2  s  . c  o m
public void testLdapTemplate() throws Exception {

    try {
        LdapTemplate ldap = (LdapTemplate) appContext.getBean("ldapTemplate");

        String user = props.getProperty("claimUser");
        Assert.notNull(user, "Property 'claimUser' not configured");

        String dn = null;

        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", user));

        //find DN of user
        AttributesMapper mapper = new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs) throws NamingException {
                return attrs.get("distinguishedName").get();
            }
        };
        @SuppressWarnings("rawtypes")
        List users = ldap.search("OU=users,DC=emea,DC=mycompany,DC=com", filter.toString(),
                SearchControls.SUBTREE_SCOPE, mapper);

        Assert.isTrue(users.size() == 1, "Only one user expected");
        dn = (String) users.get(0);

        // get attributes
        AttributesMapper mapper2 = new AttributesMapper() {
            public Object mapFromAttributes(Attributes attrs) throws NamingException {
                Map<String, String> map = new HashMap<String, String>();
                NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
                while (attrEnum.hasMore()) {
                    Attribute att = attrEnum.next();
                    System.out.println(att.toString());
                }

                map.put("cn", (String) attrs.get("cn").get());
                map.put("mail", (String) attrs.get("mail").get());
                map.put("sn", (String) attrs.get("sn").get());
                map.put("givenName", (String) attrs.get("givenName").get());
                return map;
            }
        };
        ldap.lookup(dn, new String[] { "cn", "mail", "sn", "givenName", "c" }, mapper2);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:catalina.mbeans.GlobalResourcesLifecycleListener.java

/**
 * Create the MBeans for the interesting global JNDI resources in
 * the specified naming context.//from  www .  ja v a 2  s . co  m
 *
 * @param prefix Prefix for complete object name paths
 * @param context Context to be scanned
 *
 * @exception NamingException if a JNDI exception occurs
 */
protected void createMBeans(String prefix, Context context) throws NamingException {

    if (debug >= 1) {
        log("Creating MBeans for Global JNDI Resources in Context '" + prefix + "'");
    }

    NamingEnumeration bindings = context.listBindings("");
    while (bindings.hasMore()) {
        Binding binding = (Binding) bindings.next();
        String name = prefix + binding.getName();
        Object value = context.lookup(binding.getName());
        if (debug >= 2) {
            log("Checking resource " + name);
        }
        if (value instanceof Context) {
            createMBeans(name + "/", (Context) value);
        } else if (value instanceof UserDatabase) {
            try {
                createMBeans(name, (UserDatabase) value);
            } catch (Exception e) {
                log("Exception creating UserDatabase MBeans for " + name, e);
            }
        }
    }

}

From source file:org.springframework.ejb.support.JndiEnvironmentBeanDefinitionReader.java

/**
 * Creates new JNDIBeanFactory/*from  w w  w  .ja  v  a 2 s . c o m*/
 * @param root likely to be "java:comp/env"
 */
public JndiEnvironmentBeanDefinitionReader(BeanDefinitionRegistry beanFactory, String root)
        throws BeansException {
    // We'll take everything from the NamingContext and dump it in a
    // Properties object, so that the superclass can efficiently manipulate it
    // after we've closed the context.
    HashMap m = new HashMap();

    Context initCtx = null;
    try {
        initCtx = new InitialContext();
        // Parameterize
        NamingEnumeration bindings = initCtx.listBindings(root);

        // Orion 1.5.2 doesn't seem to regard anything under a /
        // as a true subcontext, so we need to search all bindings
        // Not all that fast, but it doesn't matter            
        while (bindings.hasMore()) {
            Binding binding = (Binding) bindings.next();
            logger.debug("Name: " + binding.getName());
            logger.debug("Type: " + binding.getClassName());
            logger.debug("Value: " + binding.getObject());
            m.put(binding.getName(), binding.getObject());
        }
        bindings.close();

        PropertiesBeanDefinitionReader propReader = new PropertiesBeanDefinitionReader(beanFactory);
        propReader.registerBeanDefinitions(m, BEANS_PREFIX);
    } catch (NamingException ex) {
        logger.debug("----- NO PROPERTIES FOUND " + ex);
    } finally {
        try {
            if (initCtx != null) {
                initCtx.close();
            }
        } catch (NamingException ex) {
            // IGNORE OR THROW RTE?
        }
    }
}