Example usage for javax.naming.directory Attributes get

List of usage examples for javax.naming.directory Attributes get

Introduction

In this page you can find the example usage for javax.naming.directory Attributes get.

Prototype

Attribute get(String attrID);

Source Link

Document

Retrieves the attribute with the given attribute id from the attribute set.

Usage

From source file:com.openkm.principal.LdapPrincipalAdapter.java

@SuppressWarnings("unchecked")
private List<String> ldapSearch(List<String> searchBases, String searchFilter, String attribute) {
    log.debug("ldapSearch({}, {}, {})", new Object[] { searchBases, searchFilter, attribute });
    List<String> al = new ArrayList<String>();
    DirContext ctx = null;//from   ww w .j  a  v  a 2  s  .  c om
    Hashtable<String, String> env = getEnvironment();

    try {
        ctx = new InitialDirContext(env);
        SearchControls searchCtls = new SearchControls();
        searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        for (String searchBase : searchBases) {
            NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, searchCtls);

            while (results.hasMore()) {
                SearchResult searchResult = (SearchResult) results.next();
                Attributes attributes = searchResult.getAttributes();

                if (attribute.equals("")) {
                    StringBuilder sb = new StringBuilder();

                    for (NamingEnumeration<?> ne = attributes.getAll(); ne.hasMore();) {
                        Attribute attr = (Attribute) ne.nextElement();
                        sb.append(attr.toString());
                        sb.append("\n");
                    }

                    al.add(sb.toString());
                } else {
                    Attribute attrib = attributes.get(attribute);

                    if (attrib != null) {
                        // Handle multi-value attributes
                        for (NamingEnumeration<?> ne = attrib.getAll(); ne.hasMore();) {
                            String value = (String) ne.nextElement();

                            // If FQDN get only main part
                            if (value.startsWith("CN=") || value.startsWith("cn=")) {
                                String cn = value.substring(3, value.indexOf(','));
                                log.debug("FQDN: {}, CN: {}", value, cn);
                                al.add(cn);
                            } else {
                                al.add(value);
                            }
                        }
                    }
                }
            }
        }
    } catch (ReferralException e) {
        log.error("ReferralException: {}", e.getMessage());
        log.error("ReferralInfo: {}", e.getReferralInfo());
        log.error("ResolvedObj: {}", e.getResolvedObj());

        try {
            log.error("ReferralContext: {}", e.getReferralContext());
        } catch (NamingException e1) {
            log.error("NamingException logging context: {}", e1.getMessage());
        }
    } catch (NamingException e) {
        log.error("NamingException: {} (Base: {} - Filter: {} - Attribute: {})",
                new Object[] { e.getMessage(), searchBases, searchFilter, attribute });
    } finally {
        try {
            if (ctx != null) {
                ctx.close();
            }
        } catch (NamingException e) {
            log.error("NamingException closing context: {}", e.getMessage());
        }
    }

    log.debug("ldapSearch: {}", al);
    return al;
}

From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java

private void setFields(T instance, Attributes attrs) throws LdapMappingException {
    for (Field field : getAnnotatedFields()) {

        String attrID = field.getAnnotation(LdapAttribute.class).id();
        if (!field.getAnnotation(LdapAttribute.class).oneWayEncrypted()
                && !ENCRYPTION_ALGORITHM.equals(field.getAnnotation(LdapAttribute.class).encrypted())) {

            Attribute attr = attrs.get(attrID);
            Class<?> type = field.getType();
            Object value = null;/*from w  ww.  j av  a  2 s.  c om*/

            Class valueTranslatorClass = field.getAnnotation(LdapAttribute.class).valueTranslator();

            try {
                if (attr != null) {
                    value = getSingleValue(type, attr.get());
                    if (value != null) {
                        LdapAttributeValueTranslator valueTranslator = getValueTranslator(valueTranslatorClass);
                        value = valueTranslator.fromLdap(value);

                        field.setAccessible(true);
                        field.set(instance, value);
                    }
                }
            } catch (IllegalArgumentException e) {
                final String msg = "Expected " + type + " but was " + value;
                logger.error(msg);
                throw new LdapMappingException(msg, e);
            } catch (NamingException e) {
                throw new LdapMappingException(e);
            } catch (IllegalAccessException e) {
                throw new LdapMappingException(e);
            } catch (ClassCastException e) {
                final String msg = "Expected " + type + " but was " + value;
                logger.error(msg);
                throw new LdapMappingException(msg, e);
            } catch (InstantiationException e) {
                final String msg = "Could not instantiate attribute value translator: ";
                logger.error(msg, e);
                throw new LdapMappingException(msg, e);
            }
        }
    }
}

From source file:openscim.restful.server.resources.user.ldap.UserAttributesMapper.java

public Object mapFromAttributes(Attributes attributes) throws NamingException {
    // create a user resource
    User user = ResourceUtilities.FACTORY.createUser();

    // get the uid attribute name
    String uidAtttributeName = properties.getProperty(UID_ATTRIBUTE, DEFAULT_UID_ATTRIBUTE);

    // get the uid
    //Attribute uidAttribute = attributes.get(uidAtttributeName);
    //if(uidAttribute != null) user.setId((String)uidAttribute.get());

    // get the display name attribute name
    String displayAtttributeName = properties.getProperty(DISPLAYNAME_ATTRIBUTE, DEFAULT_DISPLAYNAME_ATTRIBUTE);

    // get the display name
    Attribute displayNameAttribute = attributes.get(displayAtttributeName);
    if (displayNameAttribute != null)
        user.setDisplayName((String) displayNameAttribute.get());

    // create a user name resource
    Name name = ResourceUtilities.FACTORY.createName();

    // get the surname attribute name
    String surnameAtttributeName = properties.getProperty(FAMILYNAME_ATTRIBUTE, DEFAULT_FAMILYNAME_ATTRIBUTE);

    // get the surname name
    Attribute surnameAttribute = attributes.get(surnameAtttributeName);
    if (surnameAttribute != null)
        name.setFamilyName((String) surnameAttribute.get());

    // get the given name attribute name
    String givenAtttributeName = properties.getProperty(GIVENNAME_ATTRIBUTE, DEFAULT_GIVENNAME_ATTRIBUTE);

    // get the given name
    Attribute givenAttribute = attributes.get(givenAtttributeName);
    if (givenAttribute != null)
        name.setGivenName((String) givenAttribute.get());

    // add the name to the user resource
    user.setName(name);/* w w w  .  jav a 2  s .  c o  m*/

    // get the email attribute name
    String mailAtttributeName = properties.getProperty(MAIL_ATTRIBUTE, DEFAULT_MAIL_ATTRIBUTE);

    // get the mails
    if (attributes.get(mailAtttributeName) != null) {
        NamingEnumeration mailEnumeration = attributes.get(mailAtttributeName).getAll();
        if (mailEnumeration != null) {
            // create a emails resource
            Emails emails = ResourceUtilities.FACTORY.createUserEmails();

            while (mailEnumeration.hasMoreElements()) {
                // get the next email
                String mailAttribute = (String) mailEnumeration.next();
                if (mailAttribute != null) {
                    PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute();
                    pluralAttribute.setValue(mailAttribute);

                    if (emails.getEmail().isEmpty())
                        pluralAttribute.setPrimary(true);
                    else
                        pluralAttribute.setPrimary(false);

                    emails.getEmail().add(pluralAttribute);
                }
            }

            // add the mails to the user resource
            user.setEmails(emails);
        }
    }

    // get the telephone attribute name
    String telephoneAtttributeName = properties.getProperty(TELEPHONE_ATTRIBUTE, DEFAULT_TELEPHONE_ATTRIBUTE);

    // get the telephones
    if (attributes.get(telephoneAtttributeName) != null) {
        NamingEnumeration telephoneEnumeration = attributes.get(telephoneAtttributeName).getAll();
        if (telephoneEnumeration != null) {
            // create a telephones resource
            PhoneNumbers telephones = ResourceUtilities.FACTORY.createUserPhoneNumbers();

            while (telephoneEnumeration.hasMoreElements()) {
                // get the next telephone
                String telephoneAttribute = (String) telephoneEnumeration.next();
                if (telephoneAttribute != null) {
                    PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute();
                    pluralAttribute.setValue(telephoneAttribute);

                    if (telephones.getPhoneNumber().isEmpty())
                        pluralAttribute.setPrimary(true);
                    else
                        pluralAttribute.setPrimary(false);

                    telephones.getPhoneNumber().add(pluralAttribute);
                }
            }

            // add the telephones to the user resource
            user.setPhoneNumbers(telephones);
        }
    }

    // get the password attribute name
    String passwordAtttributeName = properties.getProperty(PASSWORD_ATTRIBUTE, DEFAULT_PASSWORD_ATTRIBUTE);

    // get the password
    Attribute passwordAttribute = attributes.get(passwordAtttributeName);
    if (passwordAttribute != null)
        user.setPassword(new String((byte[]) passwordAttribute.get()));

    // get the memberOf attribute name
    String memberOfAtttributeName = properties.getProperty(MEMBEROF_ATTRIBUTE, DEFAULT_MEMBEROF_ATTRIBUTE);

    // get the memberOf
    if (attributes.get(memberOfAtttributeName) != null) {
        NamingEnumeration memberOfEnumeration = attributes.get(memberOfAtttributeName).getAll();
        if (memberOfEnumeration != null) {
            // create a memberof resource
            MemberOf memberof = ResourceUtilities.FACTORY.createUserMemberOf();

            while (memberOfEnumeration.hasMoreElements()) {
                // get the next member
                String memberOfAttribute = (String) memberOfEnumeration.next();
                if (memberOfAttribute != null) {
                    PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute();

                    // check if the member dns need to be concealed 
                    if (properties
                            .getProperty(UserAttributesMapper.CONCEAL_ACCOUNT_DNS,
                                    UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)
                            .equalsIgnoreCase(UserAttributesMapper.DEFAULT_CONCEAL_ACCOUNT_DNS)) {
                        Matcher matcher = pattern.matcher(memberOfAttribute);
                        if (matcher.matches()) {
                            memberOfAttribute = matcher.group(1);
                        }
                    }

                    pluralAttribute.setValue(memberOfAttribute);
                    memberof.getGroup().add(pluralAttribute);
                }
            }

            // add the memberOf to the user resource
            user.setMemberOf(memberof);
        }
    }

    return user;
}

From source file:nl.knaw.dans.common.ldap.repo.LdapMapper.java

private void setMethods(T instance, Attributes attrs) throws LdapMappingException {
    for (Method method : getAnnotatedSetMethods()) {
        String attrID = method.getAnnotation(LdapAttribute.class).id();
        if (!method.getAnnotation(LdapAttribute.class).oneWayEncrypted()
                || !ENCRYPTION_ALGORITHM.equals(method.getAnnotation(LdapAttribute.class).encrypted())) {
            Attribute attr = attrs.get(attrID);
            Class<?> type = method.getParameterTypes()[0];
            Object value = null;//from www.j  a  v  a 2s .c o  m

            Class valueTranslatorClass = method.getAnnotation(LdapAttribute.class).valueTranslator();

            try {
                if (attr != null) {
                    method.setAccessible(true);
                    for (int i = 0; i < attr.size(); i++) {
                        Object o = attr.get(i); // are not all attribute values Strings?
                        value = getSingleValue(type, o);
                        if (value != null) {
                            LdapAttributeValueTranslator valueTranslator = getValueTranslator(
                                    valueTranslatorClass);
                            value = valueTranslator.fromLdap(value);

                            method.invoke(instance, value);
                        }
                    }
                }
            } catch (IllegalArgumentException e) {
                final String msg = "Expected " + type + " but was " + value;
                logger.error(msg);
                throw new LdapMappingException(msg, e);
            } catch (NamingException e) {
                throw new LdapMappingException(e);
            } catch (IllegalAccessException e) {
                throw new LdapMappingException(e);
            } catch (InvocationTargetException e) {
                final String msg = "Method threw exception: ";
                logger.error(msg, e);
                throw new LdapMappingException(msg, e);
            } catch (IndexOutOfBoundsException e) {
                final String msg = "Setter method has no argument: ";
                logger.error(msg, e);
                throw new LdapMappingException(msg, e);
            } catch (InstantiationException e) {
                final String msg = "Could not instantiate attribute value translator: ";
                logger.error(msg, e);
                throw new LdapMappingException(msg, e);
            }
        }
    }

}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Get all ldap groups// ww w .jav a2s  . c  o  m
 * 
 * @param siteBean
 * @param baseDnGroup
 * @param ldapFilterGroups
 * @param groupAttributeName
 * @param groupToMemberReferencesMap
 * @return
 * @throws Exception
 */
public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean,
        String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap,
        Map<String, String> groups) throws Exception {
    HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>();
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER);
    if (groupMemberAttributName == null) {
        LOGGER.debug(
                "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER);
        groupMemberAttributName = DEFAULT_GROUP_MEMBER;
    }
    LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword);
    if (baseContext == null) {
        LOGGER.warn("Context is null for baseURL " + baseURL);
        return ldapGroupsMap;
    }
    for (Map.Entry<String, String> groupEntry : groups.entrySet()) {
        String groupName = groupEntry.getKey();
        String groupDN = groupEntry.getValue();
        int index = groupDN.indexOf(",");
        if (index != -1) {
            String searchPart = groupDN.substring(0, index);
            String searchStr = "(" + searchPart + ")";
            String parentDNPart = groupDN.substring(index + 1);
            LdapContext context = (LdapContext) baseContext.lookup(parentDNPart);
            if (context == null) {
                LOGGER.warn("Context is null after lookup for " + parentDNPart);
                continue;
            }
            int recordCount = 0;
            SearchControls ctls = null;
            try {
                // Activate paged results
                int pageSize = 5;
                byte[] cookie = null;
                context.setRequestControls(
                        new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
                int total;
                // Control the search
                ctls = new SearchControls();
                ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                        + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can
                                                                                                                                                                             // handle anyways
                do {
                    /* perform the search */
                    NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls);
                    /*
                     * for each entry print out name + all attrs and values
                     */
                    while (results != null && results.hasMore()) {
                        SearchResult searchResult = (SearchResult) results.next();
                        // Attributes atrs = sr.getAttributes();
                        Attributes attributes = searchResult.getAttributes();
                        if (attributes == null) {
                            LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
                            continue;
                        }
                        TPersonBean personBean = new TPersonBean();
                        try {
                            personBean.setLoginName(groupName);
                            ldapGroupsMap.put(personBean.getLoginName(), personBean);
                            Attribute memberAttribute = attributes.get(groupMemberAttributName);
                            if (memberAttribute != null) {
                                NamingEnumeration<?> members = memberAttribute.getAll();
                                while (members != null && members.hasMore()) {
                                    String memberSearchResult = (String) members.next();
                                    List<String> memberDNList = groupToMemberReferencesMap.get(groupName);
                                    if (memberDNList == null) {
                                        memberDNList = new ArrayList<String>();
                                        groupToMemberReferencesMap.put(groupName, memberDNList);
                                    }
                                    LOGGER.debug("Member found: " + memberSearchResult);
                                    memberDNList.add(memberSearchResult);
                                }
                            } else {
                                LOGGER.info("Could not find value(s) for group member attribute "
                                        + groupMemberAttributName + " for group " + groupName);
                            }
                            LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
                            LOGGER.debug("Processed group " + groupName);
                        } catch (Exception e) {
                            LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
                            LOGGER.warn(
                                    "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Stack trace:", e);
                            }
                        }
                        ++recordCount;
                    }
                    // Examine the paged results control response
                    Control[] controls = context.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                            + ") *****************\n");
                                } else {
                                    LOGGER.debug("***************** END-OF-PAGE "
                                            + "(total: unknown) ***************\n");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOGGER.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    context.setRequestControls(
                            new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

                } while (cookie != null);
            } catch (SizeLimitExceededException sle) {
                if (recordCount < ctls.getCountLimit()) {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
                    LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                            + sle.getMessage());
                    LOGGER.error(
                            "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
                } else {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                            + recordCount + ").");
                    LOGGER.error(
                            "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
                }
                LOGGER.error("The LDAP synchronization is most likely incomplete.");
            } catch (NamingException e) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            } catch (IOException ie) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(ie));
            } finally {
                context.close();
            }
        }
    }
    return ldapGroupsMap;
}

From source file:org.infoscoop.account.ldap.LDAPAccountManager.java

private List searchGroupMember(DirContext context, Map filters) throws NamingException {

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

    Set userList = new HashSet();
    String filter = buildFilter(filters);
    if (log.isInfoEnabled())
        log.info("Search User from " + userBase + " by " + filter);
    NamingEnumeration searchResultEnum = context.search(this.groupBase, filter, searchControls);

    while (searchResultEnum.hasMore()) {
        SearchResult searchResult = (SearchResult) searchResultEnum.next();
        Attributes attrs = searchResult.getAttributes();
        String dn = searchResult.getName() + "," + groupBase;
        String uniquememberAttrName = "uniqueMember";
        if (this.propAttrMap.containsKey("org_member")) {
            try {
                uniquememberAttrName = (String) this.propAttrMap.get("org_member");
            } catch (Exception ex) {
                //ignore
            }//from   w w w  . j  a v  a 2s . com
        }
        Attribute uniquememberAttr = attrs.get(uniquememberAttrName);
        if (uniquememberAttr == null)
            continue;
        NamingEnumeration memberDNs = uniquememberAttr.getAll();
        while (memberDNs.hasMoreElements()) {
            //System.out.println(memberDNs[j]);
            userList.add(memberDNs.next());//DN of user
        }
    }

    List members = new ArrayList();

    for (Iterator userDns = userList.iterator(); userDns.hasNext();) {

        /* Next directory entry */
        String userDn = (String) userDns.next();
        Attributes userEntry = null;
        try {
            userEntry = context.getAttributes(userDn);//DN of user
        } catch (Exception e) {
            log.error(userDn + ": " + e.getMessage());
        }
        if (userEntry == null)
            continue;

        LDAPAccount user = createLDAPUser(userDn, userEntry);
        if (user.getUid() == null)
            continue;

        members.add(user);

    }

    return members;

}

From source file:com.alfaariss.oa.util.idmapper.jndi.JNDIMapper.java

private String getAttributes(DirContext oDirContext, String sMapperAttribute, Name name) throws OAException {
    String sReturn = null;//from w w  w.  j  a  v a  2s . c  o  m
    try {
        if (sMapperAttribute == null) {
            _logger.error("No attribute name to map to supplied");
            throw new OAException(SystemErrors.ERROR_INTERNAL);
        }

        Attributes attributes = null;
        try {
            attributes = oDirContext.getAttributes(name, new String[] { sMapperAttribute });
        } catch (InvalidSearchFilterException e) {
            StringBuffer sbFailed = new StringBuffer("Could not resolve attribute '");
            sbFailed.append(sMapperAttribute);
            sbFailed.append("' while retrieving attributes for id: ");
            sbFailed.append(name);
            _logger.error(sbFailed.toString(), e);
            throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
        }

        Attribute attrMapping = attributes.get(sMapperAttribute);
        if (attrMapping == null) {
            _logger.debug("Attribute not found: " + sMapperAttribute);
        } else {
            Object oValue = attrMapping.get();
            if (!(oValue instanceof String)) {
                StringBuffer sbError = new StringBuffer("Returned value for attribute '");
                sbError.append(sMapperAttribute);
                sbError.append("' has a value which is not of type 'String'");
                _logger.error(sbError.toString());
                throw new OAException(SystemErrors.ERROR_RESOURCE_RETRIEVE);
            }
            sReturn = (String) oValue;
        }
    } catch (OAException e) {
        throw e;
    } catch (NamingException e) {
        _logger.debug("Failed to fetch mapping attribute for id: " + name);
    } catch (Exception e) {
        _logger.fatal("Could not retrieve fields for id: " + name, e);
        throw new OAException(SystemErrors.ERROR_INTERNAL);
    }
    return sReturn;
}

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
 *///ww w.java  2s. c om
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.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Fetches the supplied user DN./*from  ww  w .  j a v a2  s  . c om*/
 *
 * @param uid the user id
 * @return the user DN for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 */
protected String selectUserDN(InitialLdapContext ctx, String uid) throws NamingException {

    String dn = null;

    String principalUidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :

        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalUidAttrName + "=" + uid + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(principalUidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'");
                continue;
            }

            String uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                dn = sr.getName() + "," + usersCtxDN;
                if (logger.isDebugEnabled())
                    logger.debug("Found user '" + principalUidAttrName + "=" + uidValue + "' for user '" + uid
                            + "' DN=" + dn);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + uid + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    }

    return dn;

}

From source file:org.atricore.idbus.idojos.ldapidentitystore.LDAPIdentityStore.java

/**
 * Fetches the supplied user.//from www  .java 2  s  .  c o  m
 *
 * @param attrValue the user id
 * @return the user id for the supplied uid
 * @throws NamingException LDAP error obtaining user information.
 */
protected String selectUser(String attrId, String attrValue) throws NamingException {
    String uidValue = null;

    InitialLdapContext ctx = createLdapInitialContext();

    String uidAttrName = this.getPrincipalUidAttributeID();
    String usersCtxDN = this.getUsersCtxDN();

    try {
        // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr);
        // This gives more control over search behavior :
        NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + attrId + "=" + attrValue + "))",
                getSearchControls());

        while (answer.hasMore()) {
            SearchResult sr = (SearchResult) answer.next();
            Attributes attrs = sr.getAttributes();
            Attribute uidAttr = attrs.get(uidAttrName);

            if (uidAttr == null) {
                logger.warn("Invalid user attrValue attribute '" + uidAttrName + "'");
                continue;
            }

            uidValue = uidAttr.get().toString();

            if (uidValue != null) {
                if (logger.isDebugEnabled())
                    logger.debug(
                            "Found user '" + uidAttrName + "=" + uidValue + "' for user '" + attrValue + "'");
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("User not found for user '" + attrValue + "'");
            }
        }
    } catch (NamingException e) {
        if (logger.isDebugEnabled())
            logger.debug("Failed to locate user", e);
    } finally {
        // Close the context to release the connection
        ctx.close();
    }

    return uidValue;
}