Example usage for javax.naming.directory DirContext getAttributes

List of usage examples for javax.naming.directory DirContext getAttributes

Introduction

In this page you can find the example usage for javax.naming.directory DirContext getAttributes.

Prototype

public Attributes getAttributes(String name, String[] attrIds) throws NamingException;

Source Link

Document

Retrieves selected attributes associated with a named object.

Usage

From source file:org.pentaho.di.trans.steps.mailvalidator.MailValidation.java

private static ArrayList<String> getMX(String hostName) throws NamingException {
    // Perform a DNS lookup for MX records in the domain
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
    DirContext ictx = new InitialDirContext(env);
    Attributes attrs = ictx.getAttributes(hostName, new String[] { "MX" });
    Attribute attr = attrs.get("MX");

    // if we don't have an MX record, try the machine itself
    if ((attr == null) || (attr.size() == 0)) {
        attrs = ictx.getAttributes(hostName, new String[] { "A" });
        attr = attrs.get("A");
        if (attr == null) {
            throw new NamingException(BaseMessages.getString(PKG, "MailValidator.NoMatchName", hostName));
        }/* w w  w . java 2 s .  c  o m*/
    }

    // Huzzah! we have machines to try. Return them as an array list
    // NOTE: We SHOULD take the preference into account to be absolutely
    // correct. This is left as an exercise for anyone who cares.
    ArrayList<String> res = new ArrayList<String>();
    NamingEnumeration<?> en = attr.getAll();

    while (en.hasMore()) {
        String x = (String) en.next();
        String[] f = x.split(" ");
        if (f[1].endsWith(".")) {
            f[1] = f[1].substring(0, (f[1].length() - 1));
        }
        res.add(f[1]);
    }
    return res;
}

From source file:org.sonar.plugins.ldap.LdapAutodiscovery.java

List<LdapSrvRecord> getLdapServers(DirContext context, String domain) throws NamingException {
    Attributes lSrvAttrs = context.getAttributes("dns:/_ldap._tcp." + domain, new String[] { "srv" });
    Attribute serversAttribute = lSrvAttrs.get("srv");
    NamingEnumeration<?> lEnum = serversAttribute.getAll();
    SortedSet<LdapSrvRecord> result = new TreeSet<>();
    while (lEnum.hasMore()) {
        String srvRecord = (String) lEnum.next();
        // priority weight port target
        String[] srvData = srvRecord.split(" ");

        int priority = NumberUtils.toInt(srvData[0]);
        int weight = NumberUtils.toInt(srvData[1]);
        String port = srvData[2];
        String target = srvData[3];

        if (target.endsWith(".")) {
            target = target.substring(0, target.length() - 1);
        }//from   w ww .  jav a 2  s .  com
        String server = "ldap://" + target + ":" + port;
        result.add(new LdapSrvRecord(server, priority, weight));
    }
    return new ArrayList<>(result);
}

From source file:org.springframework.ldap.core.LdapTemplate.java

public Object lookup(final Name dn, final String[] attributes, final AttributesMapper mapper) {

    return executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            Attributes filteredAttributes = ctx.getAttributes(dn, attributes);
            return mapper.mapFromAttributes(filteredAttributes);
        }//  ww  w . j ava  2 s  . c  o  m
    });
}

From source file:org.springframework.ldap.core.LdapTemplate.java

public Object lookup(final String dn, final String[] attributes, final AttributesMapper mapper) {
    return executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            Attributes filteredAttributes = ctx.getAttributes(dn, attributes);
            return mapper.mapFromAttributes(filteredAttributes);
        }/*from ww  w  . j av a 2 s  .  co m*/
    });
}

From source file:org.springframework.ldap.core.LdapTemplate.java

public Object lookup(final Name dn, final String[] attributes, final ContextMapper mapper) {

    return executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            Attributes filteredAttributes = ctx.getAttributes(dn, attributes);
            DirContextAdapter contextAdapter = new DirContextAdapter(filteredAttributes, dn);
            return mapper.mapFromContext(contextAdapter);
        }/*from  w  w  w  .jav  a  2 s .co  m*/
    });
}

From source file:org.springframework.ldap.core.LdapTemplate.java

public Object lookup(final String dn, final String[] attributes, final ContextMapper mapper) {

    return executeReadOnly(new ContextExecutor() {
        public Object executeWithContext(DirContext ctx) throws javax.naming.NamingException {
            Attributes filteredAttributes = ctx.getAttributes(dn, attributes);
            DistinguishedName name = new DistinguishedName(dn);
            DirContextAdapter contextAdapter = new DirContextAdapter(filteredAttributes, name);
            return mapper.mapFromContext(contextAdapter);
        }/*ww w.j  a va2  s  .c  o m*/
    });
}

From source file:org.springframework.security.ldap.authentication.BindAuthenticator.java

private DirContextOperations bindWithDn(String userDnStr, String username, String password, Attributes attrs) {
    BaseLdapPathContextSource ctxSource = (BaseLdapPathContextSource) getContextSource();
    DistinguishedName userDn = new DistinguishedName(userDnStr);
    DistinguishedName fullDn = new DistinguishedName(userDn);
    fullDn.prepend(ctxSource.getBaseLdapPath());

    logger.debug("Attempting to bind as " + fullDn);

    DirContext ctx = null;
    try {/*  w  ww.jav  a 2 s . c om*/
        ctx = getContextSource().getContext(fullDn.toString(), password);
        // Check for password policy control
        PasswordPolicyControl ppolicy = PasswordPolicyControlExtractor.extractControl(ctx);

        logger.debug("Retrieving attributes...");
        if (attrs == null || attrs.size() == 0) {
            attrs = ctx.getAttributes(userDn, getUserAttributes());
        }

        DirContextAdapter result = new DirContextAdapter(attrs, userDn, ctxSource.getBaseLdapPath());

        if (ppolicy != null) {
            result.setAttributeValue(ppolicy.getID(), ppolicy);
        }

        return result;
    } catch (NamingException e) {
        // This will be thrown if an invalid user name is used and the method may
        // be called multiple times to try different names, so we trap the exception
        // unless a subclass wishes to implement more specialized behaviour.
        if ((e instanceof org.springframework.ldap.AuthenticationException)
                || (e instanceof org.springframework.ldap.OperationNotSupportedException)) {
            handleBindException(userDnStr, username, e);
        } else {
            throw e;
        }
    } catch (javax.naming.NamingException e) {
        throw LdapUtils.convertLdapException(e);
    } finally {
        LdapUtils.closeContext(ctx);
    }

    return null;
}

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   w  ww  . jav a 2  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:org.wso2.carbon.appfactory.s4.integration.DomainMappingManagementService.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 AppFactoryException if error occurred while the operation
 */// w w  w  .  java  2  s . c  o  m
public Multimap<String, String> resolveDNS(String domain, Hashtable<String, String> environmentConfigs)
        throws AppFactoryException, DomainMappingVerificationException {
    // 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 AppFactoryException(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 DomainMappingVerificationException(msg, ne);
    }
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * {@inheritDoc}/*from w w  w . j a v  a 2 s . c  o  m*/
 */
@Override
public String[] doGetUserListOfRole(String roleName, int maxItemLimit) throws UserStoreException {

    boolean debug = log.isDebugEnabled();
    List<String> userList = new ArrayList<String>();
    String[] names = new String[0];
    int givenMax = CommonConstants.MAX_USER_ROLE_LIST;
    int searchTime = CommonConstants.MAX_SEARCH_TIME;

    try {
        givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST));
    } catch (Exception e) {
        givenMax = CommonConstants.MAX_USER_ROLE_LIST;
    }

    try {
        searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = CommonConstants.MAX_SEARCH_TIME;
    }

    if (maxItemLimit <= 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    try {
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        searchCtls.setTimeLimit(searchTime);
        searchCtls.setCountLimit(maxItemLimit);

        String searchFilter = userStoreProperties.get(LDAPConstants.GROUP_NAME_LIST_FILTER);
        String roleNameProperty = userStoreProperties.get(LDAPConstants.GROUP_NAME_ATTRIBUTE);
        searchFilter = "(&" + searchFilter + "(" + roleNameProperty + "="
                + escapeSpecialCharactersForFilter(roleName) + "))";

        String membershipProperty = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
        String returnedAtts[] = { membershipProperty };
        searchCtls.setReturningAttributes(returnedAtts);
        List<String> userDNList = new ArrayList<String>();

        SearchResult sr = null;
        dirContext = connectionSource.getContext();

        // handling multiple search bases
        String searchBases = userStoreProperties.get(LDAPConstants.GROUP_SEARCH_BASE);
        String[] roleSearchBaseArray = searchBases.split("#");
        for (String searchBase : roleSearchBaseArray) {
            if (debug) {
                log.debug("Searching role: " + roleName + " SearchBase: " + searchBase + " SearchFilter: "
                        + searchFilter);
            }
            try {
                // read the DN of users who are members of the group
                answer = dirContext.search(escapeDNForSearch(searchBase), searchFilter, searchCtls);
                int count = 0;
                if (answer.hasMore()) { // to check if there is a result
                    while (answer.hasMore()) { // to check if there are more than one group
                        if (count > 0) {
                            throw new UserStoreException("More than one group exist with name");
                        }
                        sr = answer.next();
                        count++;
                    }
                    break;
                }
            } catch (NamingException e) {
                // ignore
                if (log.isDebugEnabled()) {
                    log.debug(e);
                }
            }
        }

        if (debug) {
            log.debug("Found role: " + sr.getNameInNamespace());
        }

        // read the member attribute and get DNs of the users
        Attributes attributes = sr.getAttributes();
        if (attributes != null) {
            NamingEnumeration attributeEntry = null;
            for (attributeEntry = attributes.getAll(); attributeEntry.hasMore();) {
                Attribute valAttribute = (Attribute) attributeEntry.next();
                if (membershipProperty.equals(valAttribute.getID())) {
                    NamingEnumeration values = null;
                    for (values = valAttribute.getAll(); values.hasMore();) {
                        String value = values.next().toString();
                        if (userDNList.size() >= maxItemLimit) {
                            break;
                        }
                        userDNList.add(value);
                        if (debug) {
                            log.debug("Found attribute: " + membershipProperty + " value: " + value);
                        }
                    }
                }
            }
        }

        if (MEMBER_UID.equals(userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE))) {
            /* when the GroupEntryObjectClass is posixGroup, membership attribute is memberUid. We have to
               retrieve the DN using the memberUid.
               This procedure has to make an extra call to ldap. alternatively this can be done with a single ldap
               search using the memberUid and retrieving the display name and username. */
            List<String> userDNListNew = new ArrayList<>();

            for (String user : userDNList) {
                String userDN = getNameInSpaceForUserName(user);
                userDNListNew.add(userDN);
            }
            userDNList = userDNListNew;
        }

        // iterate over users' DN list and get userName and display name
        // attribute values
        String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE);
        String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE);
        String[] returnedAttributes = { userNameProperty, displayNameAttribute };

        for (String user : userDNList) {
            if (debug) {
                log.debug("Getting name attributes of: " + user);
            }
            Attributes userAttributes;
            try {
                // '\' and '"' characters need another level of escaping before searching
                userAttributes = dirContext.getAttributes(escapeDNForSearch(user), returnedAttributes);

                String displayName = null;
                String userName = null;
                if (userAttributes != null) {
                    Attribute userNameAttribute = userAttributes.get(userNameProperty);
                    if (userNameAttribute != null) {
                        userName = (String) userNameAttribute.get();
                        if (debug) {
                            log.debug("UserName: " + userName);
                        }
                    }
                    if (org.apache.commons.lang.StringUtils.isNotEmpty(displayNameAttribute)) {
                        Attribute displayAttribute = userAttributes.get(displayNameAttribute);
                        if (displayAttribute != null) {
                            displayName = (String) displayAttribute.get();
                        }
                        if (debug) {
                            log.debug("DisplayName: " + displayName);
                        }
                    }
                }

                // Username will be null in the special case where the
                // username attribute has changed to another
                // and having different userNameProperty than the current
                // user-mgt.xml
                if (userName != null) {
                    user = UserStoreUtils.getCombinedName(userName, displayName);
                    userList.add(user);
                    if (debug) {
                        log.debug(user + " is added to the result list");
                    }
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug(
                                "User " + user + " doesn't have the user name property : " + userNameProperty);
                    }
                }

            } catch (NamingException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Error in reading user information in the user store for the user " + user
                            + e.getMessage(), e);
                }
            }

        }
        names = userList.toArray(new String[userList.size()]);

    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error in reading user information in the user store";
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error in reading user information in the user store";
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return names;
}