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.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  www  .  j a v a  2  s .  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;
}

From source file:jp.ikedam.jenkins.plugins.ldap_sasl.SearchGroupResolver.java

/**
 * Resolves groups by querying the LDAP directory. 
 * //from  w  ww  .  j  av a2 s  .c o  m
 * Never return null in any case. Returns empty list instead.
 * 
 * @param ctx
 * @param dn
 * @param username
 * @return List of authorities (not null)
 * @see jp.ikedam.jenkins.plugins.ldap_sasl.GroupResolver#resolveGroup(javax.naming.ldap.LdapContext, java.lang.String, java.lang.String)
 */
@Override
public List<GrantedAuthority> resolveGroup(LdapContext ctx, String dn, String username) {
    List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

    Logger logger = getLogger();

    if (dn == null) {
        logger.warning("Group cannot be resolved: DN of the user is not resolved!");
        return authorities;
    }

    try {
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        logger.fine(String.format("Searching groups base=%s, dn=%s", getSearchBase(), dn));
        NamingEnumeration<SearchResult> entries = ctx.search((getSearchBase() != null) ? getSearchBase() : "",
                getGroupSearchQuery(dn), searchControls);
        while (entries.hasMore()) {
            SearchResult entry = entries.next();
            String groupName = entry.getAttributes().get("cn").get().toString();
            if (getPrefix() != null) {
                groupName = getPrefix() + groupName;
            }
            authorities.add(new GrantedAuthorityImpl(groupName));
            logger.fine(String.format("group: %s", groupName));
        }
        entries.close();
    } catch (NamingException e) {
        logger.log(Level.WARNING, "Failed to search groups", e);
    }

    return authorities;
}

From source file:LDAPTest.java

/**
     * Constructs the data panel./*from  ww  w . j a  v  a  2s.  c o  m*/
     * @param attributes the attributes of the given entry
     */
    public DataPanel(Attributes attrs) throws NamingException {
        setLayout(new java.awt.GridLayout(0, 2, 3, 1));

        NamingEnumeration<? extends Attribute> attrEnum = attrs.getAll();
        while (attrEnum.hasMore()) {
            Attribute attr = attrEnum.next();
            String id = attr.getID();

            NamingEnumeration<?> valueEnum = attr.getAll();
            while (valueEnum.hasMore()) {
                Object value = valueEnum.next();
                if (id.equals("userPassword"))
                    value = new String((byte[]) value);

                JLabel idLabel = new JLabel(id, SwingConstants.RIGHT);
                JTextField valueField = new JTextField("" + value);
                if (id.equals("objectClass"))
                    valueField.setEditable(false);
                if (!id.equals("uid")) {
                    add(idLabel);
                    add(valueField);
                }
            }
        }
    }

From source file:ddf.security.sts.SecurityAttributesClaimsHandler.java

private Claim buildClaim(ClaimsParameters parameters, Entry<String, String> claimAttr, Attribute attr)
        throws URISyntaxException {
    Claim c = new Claim();
    c.setClaimType(new URI(claimAttr.getKey()));
    c.setPrincipal(parameters.getPrincipal());

    StringBuilder claimValue = new StringBuilder();
    try {/*from   w  w  w .  j  a va 2s.  com*/
        NamingEnumeration<?> list = (NamingEnumeration<?>) attr.getAll();
        while (list.hasMore()) {
            Object obj = list.next();
            if (!(obj instanceof String)) {
                LOGGER.warn("LDAP attribute '{}' has an unsupported value type", claimAttr.getValue());
                break;
            }
            claimValue.append((String) obj);
            if (list.hasMore()) {
                claimValue.append(ATTRIBUTE_DELIMITER);
            }
        }
    } catch (NamingException ex) {
        LOGGER.warn("Failed to read value of LDAP attribute '{}'", claimAttr.getValue());
    }

    c.setValue(claimValue.toString());
    return c;
}

From source file:com.photon.phresco.ldap.impl.LDAPManagerImpl.java

private User getUser(Credentials credentials, DirContext ctx) throws PhrescoException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method LDAPManagerImpl.getUserInfo(String userName, DirContext ctx)");
    }//ww w .j a v  a  2  s. co  m
    User user = new User();
    try {
        String userName = credentials.getUsername();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { "*" };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration<SearchResult> ne = ctx.search(ldapConfig.getLdapBaseDn(),
                ldapConfig.getLdapLoginAttribute() + Constants.STR_EQUALS + userName, constraints);
        if (ne.hasMore()) {
            Attributes attrs = ne.next().getAttributes();

            user.setName(userName);
            //      userInfo.setCredentials(credentials);
            user.setDisplayName(getDisplayName(attrs));
            user.setEmail(getMailId(attrs));
            user.setPhrescoEnabled(isPhrescoEnabled(attrs));
            //      userInfo.setCustomerNames(getCustomerNames(attrs));

        }

    } catch (Exception e) {
        throw new PhrescoException(e);
    }
    return user;
}

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

private int countLdapEntities(int maximum, final String baseDN, final String preferredFilter)
        throws NamingException {
    if (maximum <= 0) {
        return 0;
    }//  w ww  . j a  v a  2s  . co m
    int count = 0;
    NamingEnumeration<SearchResult> results = searchLDAP(baseDN, preferredFilter);
    while (results.hasMoreElements() && count < maximum) {
        try {
            results.next();
            count++;
        } catch (LdapReferralException ex) {
            logger.warn(ex.getMessage(), ex);
        }
    }
    return count;
}

From source file:org.pentaho.platform.plugin.services.security.userrole.ldap.transform.SearchResultToAttrValueList.java

public Object transform(final Object obj) {
    Object transformed = obj;//from w  w w .ja va2  s  .  co m
    if (obj instanceof SearchResult) {
        transformed = new HashSet();
        Set valueSet = (Set) transformed;
        SearchResult res = (SearchResult) obj;
        if (SearchResultToAttrValueList.logger.isDebugEnabled()) {
            SearchResultToAttrValueList.logger.debug(Messages.getInstance().getString(
                    "SearchResultToAttrValueList.DEBUG_ATTRIBUTES_FROM_SEARCHRESULT",
                    (null != res.getAttributes()) ? res.getAttributes().toString() : "null")); //$NON-NLS-1$ //$NON-NLS-2$
        }
        Attribute attr = res.getAttributes().get(attributeName);
        if (SearchResultToAttrValueList.logger.isDebugEnabled()) {
            SearchResultToAttrValueList.logger
                    .debug(Messages.getInstance().getString("SearchResultToAttrValueList.DEBUG_ATTRIBUTE_VALUE",
                            attributeName, (null != attr) ? attr.toString() : "null")); //$NON-NLS-1$ //$NON-NLS-2$
        }
        if (attr != null) { // check for null as node might not have attribute we're looking for
            try {
                NamingEnumeration values = attr.getAll();
                while (values.hasMore()) {
                    // if tokenName was specified, extract from value; otherwise
                    // store value unchanged
                    Object value = values.next();
                    if (StringUtils.hasLength(tokenName)) {
                        if ((null != value) && (value instanceof String)) {
                            String tokenValue = extract((String) value, tokenName);
                            if (null != tokenValue) {
                                valueSet.add(tokenValue);
                            }
                        } else {
                            if (SearchResultToAttrValueList.logger.isWarnEnabled()) {
                                SearchResultToAttrValueList.logger.warn(Messages.getInstance()
                                        .getString("SearchResultToAttrValueList.WARN_ATTRIBUTE_NOT_A_STRING")); //$NON-NLS-1$
                            }
                        }
                    } else {
                        if (null != value) {
                            valueSet.add(value.toString());
                        }
                    }
                }
            } catch (NamingException e) {
                if (SearchResultToAttrValueList.logger.isErrorEnabled()) {
                    SearchResultToAttrValueList.logger.error(Messages.getInstance()
                            .getErrorString("SearchResultToAttrValueList.ERROR_0001_NAMING_EXCEPTION"), e); //$NON-NLS-1$
                }
            }
        }
        return transformed;

    }
    return transformed;

}

From source file:org.jboss.additional.testsuite.jdkall.present.elytron.sasl.OtpSaslTestCase.java

/**
 * Check correct user attribute values in the LDAP when using OTP algorithm.
 *//*from   ww  w.ja v a2 s  . com*/
private void assertSequenceAndHash(Integer expectedSequence, byte[] expectedHash) throws NamingException {
    final Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, LDAP_URL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
    env.put(Context.SECURITY_CREDENTIALS, "secret");
    final LdapContext ctx = new InitialLdapContext(env, null);
    NamingEnumeration<?> namingEnum = ctx.search("dc=wildfly,dc=org", new BasicAttributes("cn", "jduke"));
    if (namingEnum.hasMore()) {
        SearchResult sr = (SearchResult) namingEnum.next();
        Attributes attrs = sr.getAttributes();
        assertEquals("Unexpected sequence number in LDAP attribute", expectedSequence,
                new Integer(attrs.get("telephoneNumber").get().toString()));
        assertEquals("Unexpected hash value in LDAP attribute",
                Base64.getEncoder().encodeToString(expectedHash), attrs.get("title").get().toString());
    } else {
        fail("User not found in LDAP");
    }

    namingEnum.close();
    ctx.close();
}

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

public static String getOrgDN(String organisation, String countryCode) {
    NamingEnumeration results = null;
    DirContext ctx = null;/*from  ww  w  .j a v  a2s  . c om*/
    String dn = null;
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String retAttrs[] = { "dn" };
        controls.setReturningAttributes(retAttrs);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search("c=" + countryCode + "," + rb.getString("organisationsRoot"),
                "(&(objectclass=organization)(o=" + organisation + "))", controls);

        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            dn = searchResult.getNameInNamespace();
        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } 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 dn;
}

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 www . j av a 2 s.  c o m*/
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);
    }
}