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

private List<KarakuPermission> loadAuthoritiesByDn(String uid) {

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

    try {/*w w  w  .  j  ava 2  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: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. j  av a2s  .com*/
 * 
 * @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:org.wso2.appcloud.core.DomainMappingManager.java

/**
 * Resolve CNAME and A records for the given {@code hostname}.
 *
 * @param domain             hostname to be resolved.
 * @param environmentConfigs environment configuration
 * @return {@link com.google.common.collect.Multimap} of resolved dns entries. This {@link com.google.common.collect.Multimap} will contain the resolved
 * "CNAME" and "A" records from the given {@code hostname}
 * @throws AppCloudException if error occurred while the operation
 *//*from   ww w  . j  av a2 s. com*/
public Multimap<String, String> resolveDNS(String domain, Hashtable<String, String> environmentConfigs)
        throws AppCloudException, NamingException {
    // result mutimap of dns records. Contains the cname and records resolved by the given hostname
    // ex:  CNAME   => foo.com,bar.com
    //      A       => 192.1.2.3 , 192.3.4.5
    Multimap<String, String> dnsRecordsResult = ArrayListMultimap.create();
    Attributes dnsRecords;
    boolean isARecordFound = false;
    boolean isCNAMEFound = false;

    try {
        if (log.isDebugEnabled()) {
            log.debug("DNS validation: resolving DNS for " + domain + " " + "(A/CNAME)");
        }
        DirContext context = new InitialDirContext(environmentConfigs);
        String[] dnsRecordsToCheck = new String[] { DNS_A_RECORD, DNS_CNAME_RECORD };
        dnsRecords = context.getAttributes(domain, dnsRecordsToCheck);
    } catch (NamingException e) {
        String msg = "DNS validation: DNS query failed for: " + domain + ". Error occurred while configuring "
                + "directory context.";
        log.error(msg, e);
        throw new AppCloudException(msg, e);
    }

    try {
        // looking for for A records
        Attribute aRecords = dnsRecords.get(DNS_A_RECORD);
        if (aRecords != null && aRecords.size() > 0) { // if an A record exists
            NamingEnumeration aRecordHosts = aRecords.getAll(); // get all resolved A entries
            String aHost;
            while (aRecordHosts.hasMore()) {
                isARecordFound = true;
                aHost = (String) aRecordHosts.next();
                dnsRecordsResult.put(DNS_A_RECORD, aHost);
                if (log.isDebugEnabled()) {
                    log.debug("DNS validation: A record found: " + aHost);
                }
            }
        }

        // looking for CNAME records
        Attribute cnameRecords = dnsRecords.get(DNS_CNAME_RECORD);
        if (cnameRecords != null && cnameRecords.size() > 0) { // if CNAME record exists
            NamingEnumeration cnameRecordHosts = cnameRecords.getAll(); // get all resolved CNAME entries for hostname
            String cnameHost;
            while (cnameRecordHosts.hasMore()) {
                isCNAMEFound = true;
                cnameHost = (String) cnameRecordHosts.next();
                if (cnameHost.endsWith(".")) {
                    // Since DNS records are end with "." we are removing it.
                    // For example real dns entry for www.google.com is www.google.com.
                    cnameHost = cnameHost.substring(0, cnameHost.lastIndexOf('.'));
                }
                dnsRecordsResult.put(DNS_CNAME_RECORD, cnameHost);
                if (log.isDebugEnabled()) {
                    log.debug("DNS validation: recurring on CNAME record towards host " + cnameHost);
                }
                dnsRecordsResult.putAll(resolveDNS(cnameHost, environmentConfigs)); // recursively resolve cnameHost
            }
        }

        if (!isARecordFound && !isCNAMEFound && log.isDebugEnabled()) {
            log.debug("DNS validation: No CNAME or A record found for domain: '" + domain);
        }
        return dnsRecordsResult;
    } catch (NamingException ne) {
        String msg = "DNS validation: DNS query failed for: " + domain + ". Provided domain: " + domain
                + " might be a " + "non existing domain.";
        // we are logging this as warn messages since this is caused, due to an user error. For example if the
        // user entered a rubbish custom url(Or a url which is, CNAME record is not propagated at the
        // time of adding the url), then url validation will fail but it is not an system error
        log.warn(msg, ne);
        throw new NamingException(msg);
    }
}

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 w w w. ja v a  2  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:com.clustercontrol.port.protocol.ReachAddressDNS.java

/**
 * DNS????????//  w  w w .  ja  v a 2 s  .c  o m
 *
 * @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.sipfoundry.sipxconfig.bulk.ldap.UserMapper.java

/**
 * Returns all string values for an attribute with a given name, ignores the values that are
 * not string values// www .  j  av  a  2s.  c o  m
 *
 * @param attrs collection of attributes
 * @param attr attribute name
 */
private Set<String> getValues(Attributes attrs, String attrName) throws NamingException {
    Attribute attribute = attrs.get(attrName);
    if (attribute == null) {
        return null;
    }
    Set<String> values = new TreeSet<String>();
    NamingEnumeration<?> allValues = attribute.getAll();
    while (allValues.hasMore()) {
        Object object = allValues.nextElement();
        if (object instanceof String) {
            values.add((String) object);
        }
    }
    return values;
}

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 w w  w  .  j  a v  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:org.apache.cxf.sts.ldap.LDAPClaimsTest.java

@org.junit.Test
@org.junit.Ignore/*from   w  w  w  .java2 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:org.archone.ad.authentication.ShoadRealm.java

private String getUserDn(String username) throws javax.naming.NamingException {
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    DirContext dirContext = contextSource.getReadOnlyContext();
    NamingEnumeration<SearchResult> searchResults = dirContext.search("",
            adConfiguration.getUserDnSearchFilter(), new String[] { username }, controls);

    SearchResult sr = searchResults.next();

    if (sr == null || searchResults.hasMore()) {
        throw new AuthenticationException();
    }/*  w  ww . jav  a2 s  .  c o m*/

    return sr.getNameInNamespace();
}

From source file:org.openadaptor.auxil.connector.jndi.JNDIReadConnector.java

/**
 * Ask the enrichment connection for the enrichment data that matches
 * the incoming record (i.e. perform the enrichment lookup).
 * //from w w w.  j a  va 2s .  c  o  m
 * @return enrichment data for the current incoming record
 * @throws Exception for example if there was a connectivity problem
 */
protected IOrderedMap[] getMatches() throws Exception {
    IOrderedMap[] results = null;
    boolean treatMultiValuedAttributesAsArray = search.getTreatMultiValuedAttributesAsArray();
    String joinArraysWithSeparator = search.getJoinArraysWithSeparator();
    NamingEnumeration current = search.execute(this.getContext());
    ArrayList resultList = new ArrayList();
    while (current.hasMore()) {
        SearchResult searchResult = (SearchResult) current.next();
        resultList.add(JNDIUtils.getOrderedMap(searchResult, treatMultiValuedAttributesAsArray,
                joinArraysWithSeparator));
    }
    if (resultList.size() > 0) {
        results = (IOrderedMap[]) resultList.toArray(new IOrderedMap[resultList.size()]);
    }
    return results;
}