Example usage for javax.naming.directory Attributes size

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

Introduction

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

Prototype

int size();

Source Link

Document

Retrieves the number of attributes in the attribute set.

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  ww w .  j  av a 2  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.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 .  j a va 2 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();) {//w  ww.j  av a 2 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:hsa.awp.common.naming.DirectoryTest.java

/**
 * Checks if the content of the Attributes and Properties is equal. In
 * properties it assumes the mapping from ldap names to our names.
 *
 * @param attributes Ldap Attribtues//  w ww  . j  a va  2 s.c om
 * @param properties Properties returned from Directory
 * @return True if they are equal, otherwise false
 * @throws Exception If someone went wron.
 */
private boolean isEqual(Attributes attributes, Properties properties) throws Exception {

    if (attributes.size() != properties.size()) {
        return false;
    }

    NamingEnumeration<String> attribIds = attributes.getIDs();
    while (attribIds.hasMoreElements()) {
        String curAttribId = attribIds.nextElement();
        String currentAttribValue = (String) attributes.get(curAttribId).get();
        String currentPropertyId = (String) directory.getClass().getField(mapping.getProperty(curAttribId))
                .get("");
        String currentPropertyValue = properties.getProperty(currentPropertyId);
        if (!currentAttribValue.equals(currentPropertyValue)) {
            return false;
        }
    }

    return true;
}

From source file:com.dianping.cat.system.page.login.service.SessionManager.java

public SessionManager() {
    super();// w w w  .j a  v a  2s  .  c om
    AuthType type = AuthType.valueOf(CatPropertyProvider.INST.getProperty("CAT_AUTH_TYPE", "ADMIN_PWD"));
    switch (type) {
    case NOP:
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();
                return new Token(account, account);
            }
        };
        break;
    case LDAP:
        final String ldapUrl = CatPropertyProvider.INST.getProperty("CAT_LDAP_URL", null);
        if (StringUtils.isBlank(ldapUrl)) {
            throw new IllegalArgumentException("required CAT_LDAP_URL");
        }
        final String userDnTpl = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DN_TPL", null);
        if (StringUtils.isBlank(userDnTpl)) {
            throw new IllegalArgumentException("required CAT_LDAP_USER_DN_TPL");
        }
        final String userDisplayAttr = CatPropertyProvider.INST.getProperty("CAT_LDAP_USER_DISPLAY_ATTR", null);
        final Pattern pattern = Pattern.compile("\\{0}");
        final Matcher userDnTplMatcher = pattern.matcher(userDnTpl);
        final String[] attrs = userDisplayAttr == null ? null : new String[] { userDisplayAttr };
        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                final String account = credential.getAccount();
                final String pwd = credential.getPassword();
                if (StringUtils.isEmpty(account) || StringUtils.isEmpty(pwd)) {
                    return null;
                }
                Hashtable<String, String> env = new Hashtable<String, String>();
                env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
                env.put(Context.PROVIDER_URL, ldapUrl);// LDAP server
                String userDn = userDnTplMatcher.replaceAll(account);
                env.put(Context.SECURITY_PRINCIPAL, pwd);
                env.put(Context.SECURITY_CREDENTIALS, pwd);
                try {
                    InitialLdapContext context = new InitialLdapContext(env, null);
                    final String baseDn = context.getNameInNamespace();
                    if (userDn.endsWith(baseDn)) {
                        userDn = userDn.substring(0, userDn.length() - baseDn.length() - 1);
                    }
                    String displayName = null;
                    if (attrs != null) {
                        final Attributes attributes = context.getAttributes(userDn, attrs);
                        if (attributes.size() > 0) {
                            displayName = attributes.getAll().next().get().toString();
                        }
                    }

                    return new Token(account, displayName == null ? account : displayName);
                } catch (Exception e) {
                    Cat.logError(e);
                    return null;
                }
            }

        };
        break;
    case ADMIN_PWD:
        final String p = CatPropertyProvider.INST.getProperty("CAT_ADMIN_PWD", "admin");

        tokenCreator = new Function<Credential, Token>() {
            @Override
            public Token apply(Credential credential) {
                String account = credential.getAccount();

                if ("admin".equals(account) && p.equals(credential.getPassword())) {
                    return new Token(account, account);
                }
                return null;
            }

        };
        break;
    }
}

From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java

public String searchQueryLDAP() {
    NamingEnumeration results = null;
    ObjectMapper mapper = new ObjectMapper();
    Response response;/*from  w  ww  .j a  v a 2  s.c  o  m*/
    String resultOutput = new String();
    List<Map<String, String>> attributesList = new LinkedList<>();

    String[] attributesToReturn = splitAttributes(allLDAPClientParameters.get(ARG_SELECTED_ATTRIBUTES));
    try {
        ldapConnection = LDAPConnectionUtility.connect(allLDAPClientParameters.get(ARG_URL),
                allLDAPClientParameters.get(ARG_DN_BASE), allLDAPClientParameters.get(ARG_USERNAME),
                allLDAPClientParameters.get(ARG_PASSWORD));
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        if (attributesToReturn.length > 0) {
            controls.setReturningAttributes(attributesToReturn);
        }
        results = ldapConnection.search(
                getFullLdapSearchBase(allLDAPClientParameters.get(ARG_DN_BASE),
                        allLDAPClientParameters.get(ARG_SEARCH_BASE)),
                allLDAPClientParameters.get(ARG_SEARCH_FILTER), controls);

        // Iterate through all attributes in the result of search query
        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();

            if (attributes != null && attributes.size() > 0) {
                NamingEnumeration ae = attributes.getAll();
                Map<String, String> attributesMap = new HashMap<>();
                while (ae.hasMore()) {
                    Attribute attribute = (Attribute) ae.next();
                    attributesMap.put(attribute.getID(), attribute.get().toString());
                }
                attributesList.add(attributesMap);
            }
        }
        response = new LDAPResponse("Ok", attributesList);
    } catch (Exception e) {
        response = new ErrorResponse("Error", e.toString());
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (ldapConnection != null) {
            try {
                ldapConnection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    try {
        resultOutput = mapper.writeValueAsString(response);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return resultOutput;
}

From source file:edu.vt.middleware.ldap.AuthenticatorCli.java

/**
 * Executes the authenticate operation./*from   www .  j a  v a 2 s .c o  m*/
 *
 * @param  config  Authenticator configuration.
 * @param  attrs  Ldap attributes to return
 *
 * @throws  Exception  On errors.
 */
protected void authenticate(final AuthenticatorConfig config, final String[] attrs) throws Exception {
    final Authenticator auth = new Authenticator();
    auth.setAuthenticatorConfig(config);

    Attributes results = null;
    try {
        if (attrs == null || attrs.length == 0) {
            results = auth.authenticate(null);
        } else {
            results = auth.authenticate(attrs);
        }
        if (results != null && results.size() > 0) {
            final LdapEntry entry = new LdapEntry();
            final LdapResult result = new LdapResult(entry);
            entry.setDn(auth.getDn(config.getUser()));
            entry.setLdapAttributes(new LdapAttributes(results));
            if (this.outputDsmlv1) {
                (new Dsmlv1()).outputDsml(result.toSearchResults().iterator(),
                        new BufferedWriter(new OutputStreamWriter(System.out)));
            } else if (this.outputDsmlv2) {
                (new Dsmlv2()).outputDsml(result.toSearchResults().iterator(),
                        new BufferedWriter(new OutputStreamWriter(System.out)));
            } else {
                (new Ldif()).outputLdif(result.toSearchResults().iterator(),
                        new BufferedWriter(new OutputStreamWriter(System.out)));
            }
        }
    } finally {
        if (auth != null) {
            auth.close();
        }
    }
}

From source file:edu.vt.middleware.ldap.auth.AuthenticatorCli.java

/**
 * Executes the authenticate operation./*from  ww w.  ja  va  2s .  c  om*/
 *
 * @param  config  Authenticator configuration.
 * @param  attrs  Ldap attributes to return
 *
 * @throws  Exception  On errors.
 */
protected void authenticate(final AuthenticatorConfig config, final String[] attrs) throws Exception {
    final Authenticator auth = new Authenticator();
    auth.setAuthenticatorConfig(config);

    Attributes results = null;
    try {
        if (attrs == null || attrs.length == 0) {
            results = auth.authenticate(null);
        } else {
            results = auth.authenticate(attrs);
        }
        if (results != null && results.size() > 0) {
            final LdapEntry entry = LdapBeanProvider.getLdapBeanFactory().newLdapEntry();
            final LdapResult result = LdapBeanProvider.getLdapBeanFactory().newLdapResult();
            result.addEntry(entry);
            entry.setDn(auth.getDn(config.getUser()));

            final LdapAttributes la = LdapBeanProvider.getLdapBeanFactory().newLdapAttributes();
            la.addAttributes(results);
            entry.setLdapAttributes(la);
            if (this.outputDsmlv1) {
                (new Dsmlv1()).outputDsml(result.toSearchResults().iterator(),
                        new BufferedWriter(new OutputStreamWriter(System.out)));
            } else if (this.outputDsmlv2) {
                (new Dsmlv2()).outputDsml(result.toSearchResults().iterator(),
                        new BufferedWriter(new OutputStreamWriter(System.out)));
            } else {
                (new Ldif()).outputLdif(result.toSearchResults().iterator(),
                        new BufferedWriter(new OutputStreamWriter(System.out)));
            }
        }
    } finally {
        if (auth != null) {
            auth.close();
        }
    }
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves an attribute by its name./*from   w ww . j  a v a  2 s  . co m*/
 * @param attributes the list of attributes to query on
 * @param attributeName the name of the attribute to return
 * @return the value of the attribute, or null if not found
 * @throws NamingException if an exception is thrown
 * @since 1.4.0
 */
public String getAttribute(Attributes attributes, String attributeName) throws NamingException {
    if (attributes == null || attributes.size() == 0) {
        return null;
    } else {
        final Attribute attribute = attributes.get(attributeName);
        if (attribute != null) {
            final Object o = attribute.get();
            if (o instanceof String) {
                return (String) attribute.get();
            }
        }
    }
    return null;
}

From source file:ca.tnt.ldaputils.impl.LdapEntry.java

/**
 * Updates the specified attribute from LDAP.
 * <p/>/*  www  . j av a2 s  . co m*/
 * MINOR : Instead of using LDAPFactory.getAttributes, using
 * DirContext.getAttributes().  Then we can remove the getAttributes().
 * <p/>
 * CRITICAL reload the attribute using the reflection framework somehow.
 *
 * @param attrName the name of the attribute
 *
 * @throws NamingException if any LDAP errors occur.
 */
protected void updateAttribute(final String attrName) throws NamingException {
    final String[] returningAttributes;
    final Attributes returnedAttributes;

    returningAttributes = new String[1];
    returningAttributes[0] = attrName;
    returnedAttributes = manager.getAttributes(getDn(), returningAttributes);

    if (returnedAttributes.size() == 1) { // only attempt to load the attributes if the search found them.
                                          // the attribute to update
        attributes.put(returnedAttributes.get(attrName));
    }
}