Example usage for javax.naming.directory Attribute get

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

Introduction

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

Prototype

Object get() throws NamingException;

Source Link

Document

Retrieves one of this attribute's values.

Usage

From source file:org.apereo.portal.groups.ldap.LDAPGroupStore.java

protected void processLdapResults(NamingEnumeration results, ArrayList keys) {
    //long time1 = System.currentTimeMillis();
    //long casting=0;
    //long getting=0;
    //long setting=0;
    //long looping=0;
    //long loop1=System.currentTimeMillis();
    try {//from w ww .j  a  va 2 s  .co m
        while (results.hasMore()) {
            //long loop2 = System.currentTimeMillis();
            //long cast1=System.currentTimeMillis();
            //looping=looping+loop2-loop1;
            SearchResult result = (SearchResult) results.next();
            //long cast2 = System.currentTimeMillis();
            //long get1 = System.currentTimeMillis();
            Attributes ldapattribs = result.getAttributes();
            //long get2 = System.currentTimeMillis();
            //long set1 = System.currentTimeMillis();
            Attribute attrib = ldapattribs.get(keyfield);
            if (attrib != null) {
                keys.add(String.valueOf(attrib.get()).toLowerCase());
            }
            //long set2 = System.currentTimeMillis();
            //loop1=System.currentTimeMillis();
            //casting=casting+cast2-cast1;
            //setting=setting+set2-set1;
            //getting=getting+get2-get1;
        }
    } catch (NamingException nex) {
        log.error("LDAPGroupStore: error processing results", nex);
    } finally {
        try {
            results.close();
        } catch (Exception e) {
        }
    }
    //long time5 = System.currentTimeMillis();
    //System.out.println("Result processing took "+(time5-time1)+": "+getting+" for getting, "
    //  +setting+" for setting, "+casting+" for casting, "+looping+" for looping,"
    //  +(time5-loop1)+" for closing");
}

From source file:org.apache.james.user.ldap.ReadOnlyUsersLDAPRepository.java

/**
 * Given a userDN, this method retrieves the user attributes from the LDAP
 * server, so as to extract the items that are of interest to James.
 * Specifically it extracts the userId, which is extracted from the LDAP
 * attribute whose name is given by the value of the field
 * {@link #userIdAttribute}./*w w w . j  a va  2  s . c om*/
 *
 * @param userDN
 *            The distinguished-name of the user whose details are to be
 *            extracted from the LDAP repository.
 * @return A {@link ReadOnlyLDAPUser} instance which is initialized with the
 *         userId of this user and ldap connection information with which
 *         the userDN and attributes were obtained.
 * @throws NamingException
 *             Propagated by the underlying LDAP communication layer.
 */
private ReadOnlyLDAPUser buildUser(String userDN) throws NamingException {
    Attributes userAttributes = ldapContext.getAttributes(userDN);
    Attribute userName = userAttributes.get(userIdAttribute);
    return new ReadOnlyLDAPUser(userName.get().toString(), userDN, ldapContext);
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

private String lookupUserId(String serverName) throws DirectoryServerManagerException {

    DirContext dirContext;//  w ww .  j a v  a 2  s  . c  om
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e);
    }

    String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    //first search the existing user entry.
    String searchFilter = getServicePrincipleFilter(serverName);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { "uid" });
    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter,
                searchControls);

        // here we assume only one user
        if (namingEnumeration.hasMore()) {

            SearchResult searchResult;

            searchResult = namingEnumeration.next();

            Attributes attributes = searchResult.getAttributes();

            Attribute userId = attributes.get("uid");
            return (String) userId.get();
        } else {
            return null;
        }

    } catch (NamingException e) {
        log.error("Could not find user id for given server " + serverName, e);
        throw new DirectoryServerManagerException("Could not find user id for given server " + serverName, e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }

}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonDataLoader.java

/**
 * This method retrieves data using LDAP protocol.
 * - CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 *
 * @param urlString//  ww w. j  a v a 2 s . c o m
 * @return
 */
private byte[] ldapGet(final String urlString) {

    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, urlString);
    try {

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes("");
        final javax.naming.directory.Attribute attribute = attributes.get("certificateRevocationList;binary");
        final byte[] ldapBytes = (byte[]) attribute.get();
        if (ldapBytes == null || ldapBytes.length == 0) {
            throw new DSSException("Cannot download CRL from: " + urlString);
        }
        return ldapBytes;
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:ldap.ActiveLoginImpl.java

public Attributes hashPasswordAttribute(Attributes account) throws NamingException {
    Attribute pwdAtt = account.get(LdapConstants.ldapAttrUserPassword);
    if (pwdAtt == null || pwdAtt.get() == null)
        throw new NamingException("user password attribute missing!");

    logger.info("entered hashPassword()" + pwdAtt);
    Object o = pwdAtt.get();//ww  w . ja v  a 2s  . c o  m
    logger.info("entered hashPassword()");
    byte[] hash = hashPassword(o);
    logger.info("completed hashPassword()");

    account.remove(LdapConstants.ldapAttrUserPassword);
    logger.info("adding the ldapAttrUserPassword, " + hash);
    account.put(LdapConstants.ldapAttrUserPassword, hash);
    byte[] pwd = (byte[]) account.get("userPassword").get();
    if (pwd != null) {
        logger.info("getting the ldapAttrUserPassword, " + pwd);
    } else {
        logger.info("hash pwd is null when tried to retrieve it");
    }
    return account;
}

From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java

private String getStringAttribute(Attributes user, String name) throws NamingException {
    Attribute a = user.get(name);
    if (a == null)
        return null;
    Object v = a.get();
    if (v == null)
        return null;
    return v.toString();
}

From source file:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java

/**
 * This method retrieves data using LDAP protocol.
 * - CRL from given LDAP url, e.g. ldap://ldap.infonotary.com/dc=identity-ca,dc=infonotary,dc=com
 * - ex URL from AIA ldap://xadessrv.plugtests.net/CN=LevelBCAOK,OU=Plugtests_2015-2016,O=ETSI,C=FR?cACertificate;binary
 *
 * @param urlString//from   w  w w  .  j  a va2 s .  c om
 * @return
 */
private byte[] ldapGet(final String urlString) {

    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, urlString);
    try {

        String attributeName = StringUtils.substringAfterLast(urlString, "?");
        if (StringUtils.isEmpty(attributeName)) {
            // default was CRL
            attributeName = "certificateRevocationList;binary";
        }

        final DirContext ctx = new InitialDirContext(env);
        final Attributes attributes = ctx.getAttributes(StringUtils.EMPTY);
        final Attribute attribute = attributes.get(attributeName);
        final byte[] ldapBytes = (byte[]) attribute.get();
        if (ArrayUtils.isEmpty(ldapBytes)) {
            throw new DSSException("Cannot download CRL from: " + urlString);
        }
        return ldapBytes;
    } catch (Exception e) {
        LOG.warn(e.getMessage(), e);
    }
    return null;
}

From source file:edu.internet2.middleware.subject.provider.JNDISourceAdapter.java

/**
 * /*w  ww . j  a v a 2s. co m*/
 * @param attributes1
 * @return subject
 */
private Subject createSubject(Attributes attributes1) {
    String name1 = "";
    String subjectID = "";
    String description = "";
    try {
        Attribute attribute = attributes1.get(this.subjectIDAttributeName);
        if (attribute == null) {
            log.error("The LDAP attribute \"" + this.subjectIDAttributeName
                    + "\" does not have a value. It is beging used as the Grouper special attribute \"SubjectID\".");
            return null;
        }
        subjectID = (String) attribute.get();
        attribute = attributes1.get(this.nameAttributeName);
        if (attribute == null) {
            log.error("The LDAP attribute \"" + this.nameAttributeName
                    + "\" does not have a value. It is being used as the Grouper special attribute \"name\".");
            return null;
        }
        name1 = (String) attribute.get();
        attribute = attributes1.get(this.descriptionAttributeName);
        if (attribute == null) {
            log.error("The LDAP attribute \"" + this.descriptionAttributeName
                    + "\" does not have a value. It is being used as the Grouper special attribute \"description\".");
        } else {
            description = (String) attribute.get();
        }
    } catch (NamingException ex) {
        log.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }

    return new JNDISubject(subjectID, name1, description, this.getSubjectType().getName(), this.getId(), null);
}

From source file:edu.internet2.middleware.subject.provider.LdapSourceAdapter.java

private Subject createSubject(Attributes attributes) {
    String name = "";
    String subjectID = "";
    String description = "";

    if (attributes == null) {
        log.debug("ldap create subject with null attrs");
        return (null);
    }/*from   w  w w.j  a va 2 s  . co m*/
    try {
        Attribute attribute = attributes.get(subjectIDAttributeName);
        if (attribute == null) {
            log.error("No value for LDAP attribute \"" + subjectIDAttributeName
                    + "\". It is Grouper attribute \"SubjectID\".");
            return null;
        }
        subjectID = ((String) attribute.get()).toLowerCase();
        attribute = attributes.get(nameAttributeName);
        if (attribute == null) {
            log.debug("No immedaite value for attribute \"" + nameAttributeName + "\". Will look later.");
        } else {
            name = (String) attribute.get();
        }
        attribute = attributes.get(descriptionAttributeName);
        if (attribute == null) {
            log.debug(
                    "No immedaite value for attribute \"" + descriptionAttributeName + "\". Will look later.");
        } else {
            description = (String) attribute.get();
        }
    } catch (NamingException ex) {
        log.error("LDAP Naming Except: " + ex.getMessage(), ex);
    }
    LdapSubject subject = new LdapSubject(subjectID, name, description, this.getSubjectType().getName(),
            this.getId());

    // add the attributes

    Map myAttributes = new HashMap();
    try {
        for (NamingEnumeration e = attributes.getAll(); e.hasMore();) {
            Attribute attr = (Attribute) e.next();
            String attrName = attr.getID();
            // skip the basic ones
            if (attrName.equals(nameAttributeName))
                continue;
            if (attrName.equals(subjectIDAttributeName))
                continue;
            if (attrName.equals(descriptionAttributeName))
                continue;
            Set values = new HashSet();
            for (NamingEnumeration en = attr.getAll(); en.hasMore();) {
                Object value = en.next();
                values.add(value.toString());
            }
            myAttributes.put(attrName, values);
        }
        subject.setAttributes(myAttributes);
    } catch (NamingException e) {
        log.error("Naming error: " + e);
    }

    return subject;
}

From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java

public PrivilegeEnum mapToPrivilege(Attributes attributes, String attributeName) {
    Attribute attributeValue = null;
    PrivilegeEnum privilege = null;/* w  w  w  .  j  a va  2s . c om*/
    if (attributes != null && (attributeValue = attributes.get(attributeName)) != null) {
        try {
            String attributeString = String.valueOf(attributeValue.get()).toLowerCase(Locale.GERMAN);
            try {
                privilege = PrivilegeEnum.valueOf(attributeString.substring(4).toUpperCase(Locale.GERMAN));
            } catch (IllegalArgumentException iae) {
                LOG.log(Level.WARNING, "Name: {0}={1} - no such privilege",
                        new Object[] { attributeName, attributeString });
            }
        } catch (NamingException ne) {
            LOG.log(Level.SEVERE, "Can't convert LDAP Group " + attributeValue + " to DDB Privilege.",
                    ne.getMessage());
        }
    }
    return privilege;
}