Example usage for javax.naming.directory Attribute size

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

Introduction

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

Prototype

int size();

Source Link

Document

Retrieves the number of values in this attribute.

Usage

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 .  ja v  a 2 s  . c o  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.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();) {//  w w w  .  ja  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.schedassist.impl.ldap.DefaultAttributesMapperImpl.java

/**
 * //ww  w. jav  a 2 s .  c om
 * @param attributes
 * @return
 * @throws NamingException
 */
protected final Map<String, List<String>> convertToStringAttributesMap(Attributes attributes)
        throws NamingException {
    Map<String, List<String>> attributesMap = new HashMap<String, List<String>>();

    NamingEnumeration<String> attributeNames = attributes.getIDs();
    while (attributeNames.hasMore()) {
        String attributeName = attributeNames.next();
        if (ldapAttributesKey.getPasswordAttributeName().equalsIgnoreCase(attributeName)) {
            // skip
            continue;
        }
        Attribute attribute = attributes.get(attributeName);
        int numberOfValues = attribute.size();
        for (int i = 0; i < numberOfValues; i++) {
            String value = (String) attribute.get(i);
            if (null != value) {
                value = value.trim();
            }

            List<String> list = safeGetAttributeList(attributesMap, attributeName.toLowerCase());
            list.add(value);
        }
    }
    return attributesMap;
}

From source file:no.smint.anthropos.ldap.PersonAttributesMapper.java

public Person mapFromAttributes(Attributes attributes) throws NamingException {
    Person person = new Person();
    person.setUidNumber(Long.valueOf((String) attributes.get("uidNumber").get()));
    person.setGivenName(attributes.get("givenName") != null ? (String) attributes.get("givenName").get() : "");
    person.setSn(attributes.get("sn") != null ? (String) attributes.get("sn").get() : "");
    person.setCn(attributes.get("cn") != null ? (String) attributes.get("cn").get() : "");
    person.setUid(attributes.get("uid") != null ? (String) attributes.get("uid").get() : "");
    person.setMail(attributes.get("mail") != null ? (String) attributes.get("mail").get() : "");
    person.setTelephoneNumber(/*from   w ww  .  j a v  a  2  s .c  o  m*/
            attributes.get("telephoneNumber") != null ? (String) attributes.get("telephoneNumber").get() : "");

    Attribute memberOfAtt = attributes.get("memberOf");
    if (memberOfAtt != null) {
        ArrayList<String> memberOf = new ArrayList<String>();
        for (int i = 0; i < memberOfAtt.size(); i++) {
            memberOf.add((String) memberOfAtt.get(i));
        }
        person.setMemberOf(memberOf);
    }
    return person;
}

From source file:edu.kit.scc.ldap.LdapPosixGroupAttributeMapper.java

@Override
public PosixGroup mapFromAttributes(Attributes attributes) throws NamingException {
    PosixGroup posixGroup = new PosixGroup();
    String commonName = (String) attributes.get("cn").get();
    if (commonName != null) {
        posixGroup.setCommonName(commonName);
    }/*w  ww. j av  a 2  s  . c  om*/
    Attribute gidNumber = attributes.get("gidNumber");
    if (gidNumber != null) {
        posixGroup.setGidNumber((String) gidNumber.get());
    }
    Attribute memberUids = attributes.get("memberUid");
    if (memberUids != null) {
        posixGroup.setMemberUids(new ArrayList<String>());
        for (int i = 0; i < memberUids.size(); i++) {
            posixGroup.getMemberUids().add((String) memberUids.get(i));
        }
    }

    Attribute description = attributes.get("description");
    if (description != null) {
        posixGroup.setDescription((String) description.get());
    }
    Attribute userPassword = attributes.get("userPassword");
    if (userPassword != null) {
        posixGroup.setUserPassword((byte[]) userPassword.get());
    }
    return posixGroup;
}

From source file:org.cloudfoundry.identity.uaa.ldap.PasswordComparisonAuthenticator.java

public DirContextOperations localCompareAuthenticate(DirContextOperations user, String password) {
    boolean match = false;
    try {/*from  w  w w . jav  a  2s .  c  o m*/
        Attributes attributes = user.getAttributes();
        Attribute attr = attributes.get(getPasswordAttributeName());
        if (attr.size() == 0) {
            throw new AuthenticationCredentialsNotFoundException(
                    "Missing " + getPasswordAttributeName() + " attribute.");
        }
        for (int i = 0; (attr != null) && (!match) && (i < attr.size()); i++) {
            Object valObject = attr.get(i);
            if (valObject != null && valObject instanceof byte[]) {
                if (passwordEncoder instanceof DynamicPasswordComparator) {
                    byte[] received = password.getBytes();
                    byte[] stored = (byte[]) valObject;
                    match = ((DynamicPasswordComparator) passwordEncoder).comparePasswords(received, stored);
                } else {
                    String encodedPassword = passwordEncoder.encodePassword(password, null);
                    byte[] passwordBytes = Utf8.encode(encodedPassword);
                    match = Arrays.equals(passwordBytes, (byte[]) valObject);
                }
            }
        }
    } catch (NamingException e) {
        throw new BadCredentialsException("Bad credentials", e);
    }
    if (!match)
        throw new BadCredentialsException("Bad credentials");
    return user;
}

From source file:org.nuxeo.ecm.directory.ldap.dns.DNSServiceResolverImpl.java

/**
 * Returns the host name and port that a server providing the specified service can be reached at. A DNS lookup for
 * a SRV record in the form "_service.example.com" is attempted.
 * <p>/*from w w  w.  j  av  a2s . c  om*/
 * As an example, a lookup for "example.com" for the service _gc._tcp may return "dc01.example.com:3268".
 *
 * @param service the service.
 * @param domain the domain.
 * @return a List of DNSServiceEntrys, which encompasses the hostname and port that the server can be reached at for
 *         the specified domain.
 * @throws NamingException if the DNS server is unreachable
 */
protected List<DNSServiceEntry> resolveDnsServiceRecord(final String service, final String domain)
        throws NamingException {
    List<DNSServiceEntry> addresses = new ArrayList<>();

    if (context == null) {
        return addresses;
    }

    final String key = service + "." + domain;
    /*
     * Return item from cache if it exists.
     */
    if (System.currentTimeMillis() - lastCacheUpdate > maxDelay) {
        cache.clear();
    }
    if (cache.containsKey(key)) {
        List<DNSServiceEntry> cachedAddresses = cache.get(key);
        if (cachedAddresses != null) {
            return cachedAddresses;
        }
    }

    Attributes dnsLookup = context.getAttributes(service + "." + domain, new String[] { SRV_RECORD });

    Attribute attribute = dnsLookup.get(SRV_RECORD);
    for (int i = 0; i < attribute.size(); i++) {
        /*
         * Get the current resource record
         */
        String entry = (String) attribute.get(i);

        String[] records = entry.split(" ");
        String host = records[records.length - 1];
        int port = Integer.parseInt(records[records.length - 2]);
        int weight = Integer.parseInt(records[records.length - 3]);
        int priority = Integer.parseInt(records[records.length - 4]);

        /*
         * possible to get TTL?
         */

        /*
         * Host entries in DNS should end with a "."
         */
        if (host.endsWith(".")) {
            host = host.substring(0, host.length() - 1);
        }

        addresses.add(new DNSServiceEntry(host, port, priority, weight));
    }

    /*
     * Sort the addresses by DNS priority and weight settings
     */
    Collections.sort(addresses);

    /*
     * Add item to cache.
     */
    if (cache.size() > 100) {
        cache.clear();
    }
    cache.put(key, addresses);
    lastCacheUpdate = System.currentTimeMillis();
    return addresses;
}

From source file:ldap.Entry.java

/**
 * Utility method to get as a String an attribute value.  Returns 'first'
 * attribute value if multi valued./* w  w  w .j  ava  2s .  com*/
 * @param attributeName
 * @return null if attribute doesn't exist.
 * @throws NamingException
 */
public String getValue(String attributeName) throws NamingException {
    Attribute att = get(attributeName);
    if (att == null)
        return null;
    if (att.size() == 0) // can this happen?
        return "";

    Object value = att.get();
    if (value == null)
        return null;

    return value.toString();
}

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
 *//*w ww  .  j a  v  a  2 s.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:ldap.Entry.java

/**
 * Utility method to get as a String all the attribute values
 * of a particular attribute.//from   w  w  w  . j  a v  a2s  . c o m
 * @param attributeName
 * @return null if attribute does not exist, an array of string values otherwise.
 * @throws NamingException
 */
public String[] getValues(String attributeName) throws NamingException {
    Attribute att = get(attributeName);
    if (att == null)
        return null;

    String[] returnVals = new String[att.size()];

    for (int i = 0; i < att.size(); i++)
        returnVals[i] = att.get(i).toString();

    return returnVals;
}