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:com.photon.phresco.ldap.impl.LDAPManagerImpl.java

private boolean isPhrescoEnabled(Attributes attrs) throws NamingException {
    if (isDebugEnabled) {
        S_LOGGER.debug("Entering Method LDAPManagerImpl.isPhrescoEnabled(Attributes attrs");
    }//from ww  w . j a va2  s.  c  o m
    String phrescoEnabled = "false";
    Attribute attribute = attrs.get(ldapConfig.getPhrescoEnabledAttribute());
    if (attribute != null) {
        phrescoEnabled = (String) attribute.get();
    } else {
        phrescoEnabled = "true";
    }
    return Boolean.parseBoolean(phrescoEnabled);
}

From source file:info.jtrac.acegi.JtracLdapAuthenticationProvider.java

/**
 * displayName and mail are returned always, the map allows us to support
 * getting arbitrary properties in the future, hopefully
 */// w ww  .  j  av  a2 s .c om
public Map<String, String> bind(String loginName, String password) throws Exception {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapUrl);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    LdapContext ctx = null;
    if (activeDirectoryDomain != null) { // we are using Active Directory            
        Control[] controls = new Control[] { control };
        ctx = new InitialLdapContext(env, controls);
        logger.debug("Active Directory LDAP context initialized");
        ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, activeDirectoryDomain + "\\" + loginName);
        ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password);
        // javax.naming.AuthenticationException
        ctx.reconnect(controls);
        logger.debug("Active Directory LDAP bind successful");
    } else { // standard LDAP            
        env.put(Context.SECURITY_PRINCIPAL, searchKey + "=" + loginName + "," + searchBase);
        env.put(Context.SECURITY_CREDENTIALS, password);
        ctx = new InitialLdapContext(env, null);
        logger.debug("Standard LDAP bind successful");
    }
    SearchControls sc = new SearchControls();
    sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    sc.setReturningAttributes(returningAttributes);
    NamingEnumeration results = ctx.search(searchBase, searchKey + "=" + loginName, sc);
    while (results.hasMoreElements()) {
        SearchResult sr = (SearchResult) results.next();
        Attributes attrs = sr.getAttributes();
        logger.debug("attributes: " + attrs);
        Map<String, String> map = new HashMap<String, String>(returningAttributes.length);
        for (String key : returningAttributes) {
            Attribute attr = attrs.get(key);
            if (attr != null) {
                map.put(key, (String) attr.get());
            }
        }
        return map; // there should be only one anyway            
    }
    // if we reached here, there was no search result
    throw new Exception("no results returned from ldap");
}

From source file:org.apache.archiva.redback.users.ldap.LdapUserManagerTest.java

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);//from www.  j  a v a  2  s .co m
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);
    // NamingEnumeration<SearchResult> results = context.search( suffix, "(" + attribute + "=" + value + ")", ctls
    // );

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:org.apache.hadoop.hdfsproxy.LdapIpDirFilter.java

/**
 * check if client's ip is listed in the Ldap Roles if yes, return true and
 * update ldapent. if not, return false/*from  w w  w .j a va2 s . co  m*/
 * */
@SuppressWarnings("unchecked")
private boolean getLdapRoleEntryFromUserIp(String userIp, LdapRoleEntry ldapent) throws NamingException {
    String ipMember = hdfsIpSchemaStrPrefix + userIp;
    Attributes matchAttrs = new BasicAttributes(true);
    matchAttrs.put(new BasicAttribute(hdfsIpSchemaStr, ipMember));
    matchAttrs.put(new BasicAttribute(hdfsUidSchemaStr));
    matchAttrs.put(new BasicAttribute(hdfsPathSchemaStr));

    String[] attrIDs = { hdfsUidSchemaStr, hdfsPathSchemaStr };

    NamingEnumeration<SearchResult> results = lctx.search(baseName, matchAttrs, attrIDs);
    if (results.hasMore()) {
        String userId = null;
        ArrayList<Path> paths = new ArrayList<Path>();
        SearchResult sr = results.next();
        Attributes attrs = sr.getAttributes();
        for (NamingEnumeration ne = attrs.getAll(); ne.hasMore();) {
            Attribute attr = (Attribute) ne.next();
            if (hdfsUidSchemaStr.equalsIgnoreCase(attr.getID())) {
                userId = (String) attr.get();
            } else if (hdfsPathSchemaStr.equalsIgnoreCase(attr.getID())) {
                for (NamingEnumeration e = attr.getAll(); e.hasMore();) {
                    String pathStr = (String) e.next();
                    paths.add(new Path(pathStr));
                }
            }
        }
        ldapent.init(userId, paths);
        if (LOG.isDebugEnabled())
            LOG.debug(ldapent);
        return true;
    }
    LOG.info("Ip address " + userIp + " is not authorized to access the proxy server");
    return false;
}

From source file:ldap.Entry.java

/**
 * Utility method to get as a String an attribute value.  Returns 'first'
 * attribute value if multi valued./*from  www . j ava 2 s  . c  o m*/
 * @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.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java

private void assertExist(DirContext context, String dn, String attribute, String value) throws NamingException {
    SearchControls ctls = new SearchControls();

    ctls.setDerefLinkFlag(true);//from  ww  w .  j av a 2  s.  co  m
    ctls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    ctls.setReturningAttributes(new String[] { "*" });

    BasicAttributes matchingAttributes = new BasicAttributes();
    matchingAttributes.put(attribute, value);
    BasicAttribute objectClass = new BasicAttribute("objectClass");
    objectClass.add("inetOrgPerson");
    matchingAttributes.put(objectClass);

    NamingEnumeration<SearchResult> results = context.search(suffix, matchingAttributes);

    assertTrue(results.hasMoreElements());
    SearchResult result = results.nextElement();
    Attributes attrs = result.getAttributes();
    Attribute testAttr = attrs.get(attribute);
    assertEquals(value, testAttr.get());

}

From source file:org.springframework.ldap.samples.article.dao.TraditionalPersonDaoImpl.java

public List getAllPersonNames() {
    DirContext ctx = createAnonymousContext();

    LinkedList list = new LinkedList();
    NamingEnumeration results = null;
    try {//w w  w  .j  a  v  a  2s  . c  om
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        results = ctx.search("", "(objectclass=person)", controls);

        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            Attribute attr = attributes.get("cn");
            String cn = (String) attr.get();
            list.add(cn);
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return list;
}

From source file:org.springframework.ldap.demo.dao.PersonDaoImpl.java

public List<String> getAllPersonNames() {
    DirContext ctx = createAnonymousContext();

    LinkedList<String> list = new LinkedList<String>();
    NamingEnumeration<?> results = null;
    try {//from w  w w  .  j  a  va2 s.com
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        results = ctx.search("", "(objectclass=person)", controls);

        while (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            Attribute attr = attributes.get("cn");
            String cn = (String) attr.get();
            list.add(cn);
        }
    } catch (NamingException e) {
        throw new RuntimeException(e);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }
    return list;
}

From source file:se.vgregion.service.innovationsslussen.ldap.LdapService.java

AttributesMapper newAttributesMapper(final Class type) {
    return new AttributesMapper() {
        @Override/*w  w  w.  j a v  a  2 s .  c  om*/
        public Object mapFromAttributes(Attributes attributes) throws NamingException {
            try {
                return mapFromAttributesImpl(attributes);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public Object mapFromAttributesImpl(Attributes attributes)
                throws NamingException, IllegalAccessException, InstantiationException {
            Object result = type.newInstance();
            BeanMap bm = new BeanMap(result);
            NamingEnumeration<? extends Attribute> all = attributes.getAll();

            while (all.hasMore()) {
                Attribute attribute = all.next();

                String name = toBeanPropertyName(attribute.getID());
                if (bm.containsKey(name) && bm.getWriteMethod(name) != null) {
                    bm.put(name, attribute.get());
                }
            }
            return result;
        }
    };
}

From source file:com.surevine.ldap2alfresco.ProfileUpdater.java

/**
 * Update Alfresco user profile fields from LDAP user attributes.  If any users
 * cannot be updated they are logged and skipped.
 * @param ldap To connect to LDAP//from  w ww  .j  av a2 s .c  o  m
 * @param alfresco To connect to Alfresco
 * @param allUsers Set to true to update all records, not just records changed since the last run
 * @param lastRun Timestamp of the last run (string representation as returned by LDAP server)
 * @throws LdapException On any LDAP errors
 * @throws AlfrescoException On any fatal Alfresco errors
 */
public void updateFromLdapToAlfresco(final LdapConnector ldap, final AlfrescoConnector alfresco,
        final boolean allUsers, final String lastRun) throws LdapException, AlfrescoException {

    // get groups
    Collection<Attributes> users = null;

    if (allUsers) {
        users = ldap.getAllUsers();
    } else {
        users = ldap.getModifiedUsers(lastRun);
    }

    LOGGER.info("Found " + users.size() + " users to synchronise");

    Iterator<Attributes> userIter = users.iterator();

    while (userIter.hasNext()) {
        // get the user
        Attributes userAttributes = userIter.next();

        Attribute cn = userAttributes.get("cn");

        if (cn != null) {
            String username;

            try {
                username = cn.get().toString();
            } catch (NamingException e1) {
                username = null;
            }

            if (username != null) {
                LOGGER.info("Synchronising " + username);

                JSONObject fields = new JSONObject();

                // encode each profile field in turn
                Iterator<ProfileFieldConverter> fieldIter = profileFields.iterator();

                while (fieldIter.hasNext()) {
                    ProfileFieldConverter converter = fieldIter.next();
                    converter.toJson(fields, userAttributes);
                }

                try {
                    alfresco.updateProfile(username, fields);
                } catch (AlfrescoException e) {
                    recoverFromExceptionUser(ldap, e, username);
                }
            }
        }
    }
}