Example usage for javax.naming.directory Attribute getAll

List of usage examples for javax.naming.directory Attribute getAll

Introduction

In this page you can find the example usage for javax.naming.directory Attribute getAll.

Prototype

NamingEnumeration<?> getAll() throws NamingException;

Source Link

Document

Retrieves an enumeration of the attribute's values.

Usage

From source file:org.iplantc.persondir.support.ldap.AttributesMapperImpl.java

@Override
public Object mapFromAttributes(Attributes attributes) throws NamingException {
    final int attributeCount = attributes.size();
    final Map<String, Object> mapOfAttrValues = this.createAttributeMap(attributeCount);

    for (final NamingEnumeration<? extends Attribute> attributesEnum = attributes.getAll(); attributesEnum
            .hasMore();) {/*from   w  w  w .  j  a va2  s . co m*/
        final Attribute attribute = attributesEnum.next();

        if (!this.ignoreNull || attribute.size() > 0) {
            final String attrName = attribute.getID();
            final String key = this.getAttributeKey(attrName);

            final NamingEnumeration<?> valuesEnum = attribute.getAll();
            final List<?> values = this.getAttributeValues(valuesEnum);

            mapOfAttrValues.put(key, values);
        }
    }

    return mapOfAttrValues;
}

From source file:org.apereo.services.persondir.support.ldap.AttributeMapAttributesMapper.java

@Override
public Object mapFromAttributes(final Attributes attributes) throws NamingException {
    final int attributeCount = attributes.size();
    final Map<String, Object> mapOfAttrValues = this.createAttributeMap(attributeCount);

    for (final NamingEnumeration<? extends Attribute> attributesEnum = attributes.getAll(); attributesEnum
            .hasMore();) {//from  w w  w .j a  va  2  s  .c  om
        final Attribute attribute = attributesEnum.next();

        if (!this.ignoreNull || attribute.size() > 0) {
            final String attrName = attribute.getID();
            final String key = this.getAttributeKey(attrName);

            final NamingEnumeration<?> valuesEnum = attribute.getAll();
            final List<?> values = this.getAttributeValues(valuesEnum);

            mapOfAttrValues.put(key, values);
        }
    }

    return mapOfAttrValues;
}

From source file:org.jasig.services.persondir.support.ldap.AttributeMapAttributesMapper.java

public Object mapFromAttributes(Attributes attributes) throws NamingException {
    final int attributeCount = attributes.size();
    final Map<String, Object> mapOfAttrValues = this.createAttributeMap(attributeCount);

    for (final NamingEnumeration<? extends Attribute> attributesEnum = attributes.getAll(); attributesEnum
            .hasMore();) {//from ww w.ja v  a  2  s .  com
        final Attribute attribute = attributesEnum.next();

        if (!this.ignoreNull || attribute.size() > 0) {
            final String attrName = attribute.getID();
            final String key = this.getAttributeKey(attrName);

            final NamingEnumeration<?> valuesEnum = attribute.getAll();
            final List<?> values = this.getAttributeValues(valuesEnum);

            mapOfAttrValues.put(key, values);
        }
    }

    return mapOfAttrValues;
}

From source file:org.georchestra.security.LdapUserDetailsRequestHeaderProvider.java

@SuppressWarnings("unchecked")
@Override/*  w w w . j  a v a2 s .co m*/
protected Collection<Header> getCustomRequestHeaders(HttpSession session, HttpServletRequest originalRequest) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication instanceof AnonymousAuthenticationToken) {
        return Collections.emptyList();
    }
    String username = authentication.getName();
    DirContextOperations userData;

    Collection<Header> headers = Collections.emptyList();

    synchronized (session) {

        if (session.getAttribute("security-proxy-cached-attrs") != null) {
            try {
                headers = (Collection<Header>) session.getAttribute("security-proxy-cached-attrs");
                String expectedUsername = (String) session.getAttribute("security-proxy-cached-username");

                if (username.equals(expectedUsername)) {
                    return headers;
                }
            } catch (Exception e) {
                logger.info("Unable to lookup cached user's attributes for user :" + username, e);
            }
        } else {
            try {
                userData = _userSearch.searchForUser(username);
            } catch (Exception e) {
                logger.info("Unable to lookup user:" + username, e);
                return Collections.emptyList();
            }
            headers = new ArrayList<Header>();
            for (Map.Entry<String, String> entry : _headerMapping.entrySet()) {
                try {
                    Attribute attributes = userData.getAttributes().get(entry.getValue());
                    if (attributes != null) {
                        NamingEnumeration<?> all = attributes.getAll();
                        StringBuilder value = new StringBuilder();
                        while (all.hasMore()) {
                            if (value.length() > 0) {
                                value.append(',');
                            }
                            value.append(all.next());
                        }
                        headers.add(new BasicHeader(entry.getKey(), value.toString()));
                    }
                } catch (javax.naming.NamingException e) {
                    logger.error("problem adding headers for request:" + entry.getKey(), e);
                }
            }

            // Add user organization
            try {
                // Retreive memberOf attributes
                String[] attrs = { "memberOf" };
                ((FilterBasedLdapUserSearch) this._userSearch).setReturningAttributes(attrs);
                userData = _userSearch.searchForUser(username);
                Attribute attributes = userData.getAttributes().get("memberOf");
                if (attributes != null) {
                    NamingEnumeration<?> all = attributes.getAll();

                    while (all.hasMore()) {
                        String memberOf = all.next().toString();
                        Matcher m = this.pattern.matcher(memberOf);
                        if (m.matches()) {
                            headers.add(new BasicHeader("sec-org", m.group(2)));
                            break;
                        }
                    }
                }
            } catch (javax.naming.NamingException e) {
                logger.error("problem adding headers for request: organization", e);
            } finally {
                // restore standard attribute list
                ((FilterBasedLdapUserSearch) this._userSearch).setReturningAttributes(null);
            }

            logger.info("Storing attributes into session for user :" + username);
            session.setAttribute("security-proxy-cached-username", username);
            session.setAttribute("security-proxy-cached-attrs", headers);
        }
    }

    return headers;
}

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 a va  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);
    }
}

From source file:org.apache.cloudstack.ldap.OpenLdapUserManagerImpl.java

@Override
public List<LdapUser> getUsersInGroup(String groupName, LdapContext context) throws NamingException {
    String attributeName = _ldapConfiguration.getGroupUniqueMemeberAttribute();
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(_ldapConfiguration.getScope());
    controls.setReturningAttributes(new String[] { attributeName });

    NamingEnumeration<SearchResult> result = context.search(_ldapConfiguration.getBaseDn(),
            generateGroupSearchFilter(groupName), controls);

    final List<LdapUser> users = new ArrayList<LdapUser>();
    //Expecting only one result which has all the users
    if (result.hasMoreElements()) {
        Attribute attribute = result.nextElement().getAttributes().get(attributeName);
        NamingEnumeration<?> values = attribute.getAll();

        while (values.hasMoreElements()) {
            String userdn = String.valueOf(values.nextElement());
            try {
                users.add(getUserForDn(userdn, context));
            } catch (NamingException e) {
                s_logger.info("Userdn: " + userdn + " Not Found:: Exception message: " + e.getMessage());
            }/*from  w w w  . ja v a 2s  .co m*/
        }
    }

    Collections.sort(users);

    return users;
}

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

/**
 * DNS????????//from w w  w.  j  a  v a 2s  .  com
 *
 * @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:LDAPTest.java

/**
     * Constructs the data panel.//  www.  jav  a2s  . c  om
     * @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:edu.umich.ctools.sectionsUtilityTool.SectionUtilityToolFilter.java

private boolean ldapAuthorizationVerification(String user) {
    M_log.debug("ldapAuthorizationVerification(): called");
    boolean isAuthorized = false;
    DirContext dirContext = null;
    NamingEnumeration listOfPeopleInAuthGroup = null;
    NamingEnumeration allSearchResultAttributes = null;
    NamingEnumeration simpleListOfPeople = null;
    Hashtable<String, String> env = new Hashtable<String, String>();
    if (!isEmpty(providerURL) && !isEmpty(mcommunityGroup)) {
        env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_CTX_FACTORY);
        env.put(Context.PROVIDER_URL, providerURL);
    } else {//  w  ww  .j a  v a2s  .c om
        M_log.error(
                " [ldap.server.url] or [mcomm.group] properties are not set, review the sectionsToolPropsLessSecure.properties file");
        return isAuthorized;
    }
    try {
        dirContext = new InitialDirContext(env);
        String[] attrIDs = { "member" };
        SearchControls searchControls = new SearchControls();
        searchControls.setReturningAttributes(attrIDs);
        searchControls.setReturningObjFlag(true);
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String searchBase = OU_GROUPS;
        String filter = "(&(cn=" + mcommunityGroup + ") (objectclass=rfc822MailGroup))";
        listOfPeopleInAuthGroup = dirContext.search(searchBase, filter, searchControls);
        String positiveMatch = "uid=" + user + ",";
        outerloop: while (listOfPeopleInAuthGroup.hasMore()) {
            SearchResult searchResults = (SearchResult) listOfPeopleInAuthGroup.next();
            allSearchResultAttributes = (searchResults.getAttributes()).getAll();
            while (allSearchResultAttributes.hasMoreElements()) {
                Attribute attr = (Attribute) allSearchResultAttributes.nextElement();
                simpleListOfPeople = attr.getAll();
                while (simpleListOfPeople.hasMoreElements()) {
                    String val = (String) simpleListOfPeople.nextElement();
                    if (val.indexOf(positiveMatch) != -1) {
                        isAuthorized = true;
                        break outerloop;
                    }
                }
            }
        }
        return isAuthorized;
    } catch (NamingException e) {
        M_log.error("Problem getting attribute:" + e);
        return isAuthorized;
    } finally {
        try {
            if (simpleListOfPeople != null) {
                simpleListOfPeople.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration list \"simpleListOfPeople\" list ",
                    e);
        }
        try {
            if (allSearchResultAttributes != null) {
                allSearchResultAttributes.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"allSearchResultAttributes\" list ",
                    e);
        }
        try {
            if (listOfPeopleInAuthGroup != null) {
                listOfPeopleInAuthGroup.close();
            }
        } catch (NamingException e) {
            M_log.error(
                    "Problem occurred while closing the NamingEnumeration \"listOfPeopleInAuthGroup\" list ",
                    e);
        }
        try {
            if (dirContext != null) {
                dirContext.close();
            }
        } catch (NamingException e) {
            M_log.error("Problem occurred while closing the  \"dirContext\"  object", e);
        }
    }

}

From source file:org.pepstock.jem.gwt.server.security.ExtendedJndiLdapRealm.java

/**
 * Load all LDAP attributes in principal attributes and stores all in a list.
 * /*from w  w w. j a  va2 s  . c om*/
 * @param attributes LDAP attributes
 * @return list of principal attribtues
 */
@SuppressWarnings("rawtypes")
private List<PrincipalAttribute> loadAttributes(String id, Attributes attributes) {
    // creates a list
    List<PrincipalAttribute> list = new ArrayList<PrincipalAttribute>();
    if (attributes != null) {
        try {
            // scans LDAP attributes 
            for (NamingEnumeration attrEnum = attributes.getAll(); attrEnum.hasMore();) {
                Attribute attribute = (Attribute) attrEnum.next();
                // creates all principal attributes
                for (NamingEnumeration valueEnum = attribute.getAll(); valueEnum.hasMore();) {
                    PrincipalAttribute attr = new PrincipalAttribute();
                    attr.setName(attribute.getID());
                    attr.setValue(valueEnum.next());
                    list.add(attr);
                }
            }
        } catch (NamingException e) {
            LogAppl.getInstance().emit(UserInterfaceMessage.JEMG031E, e, id);
        }
    }
    return list;
}