Example usage for javax.naming.directory Attributes get

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

Introduction

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

Prototype

Attribute get(String attrID);

Source Link

Document

Retrieves the attribute with the given attribute id from the attribute set.

Usage

From source file:openscim.restful.server.resources.group.ldap.GroupAttributesMapper.java

public Object mapFromAttributes(Attributes attributes) throws NamingException {
    // create a group resource
    Group group = ResourceUtilities.FACTORY.createGroup();

    // get the gid attribute name
    String gidAtttributeName = properties.getProperty(GID_ATTRIBUTE, DEFAULT_GID_ATTRIBUTE);

    // get the gid      
    Attribute gidAttribute = attributes.get(gidAtttributeName);
    if (gidAttribute != null)
        group.setId((String) gidAttribute.get());

    // get the member attribute name
    String memberAtttributeName = properties.getProperty(MEMBER_ATTRIBUTE, DEFAULT_MEMBER_ATTRIBUTE);

    // get the members
    NamingEnumeration memberEnumeration = attributes.get(memberAtttributeName).getAll();
    if (memberEnumeration != null) {
        // create a members resource
        List<PluralAttribute> members = new ArrayList<PluralAttribute>();

        while (memberEnumeration.hasMoreElements()) {
            // get the next member
            String memberAttribute = (String) memberEnumeration.next();
            if (memberAttribute != null) {
                PluralAttribute pluralAttribute = ResourceUtilities.FACTORY.createPluralAttribute();

                // check if the member dns need to be concealed 
                if (properties
                        .getProperty(GroupAttributesMapper.CONCEAL_GROUP_DNS,
                                GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)
                        .equalsIgnoreCase(GroupAttributesMapper.DEFAULT_CONCEAL_GROUP_DNS)) {
                    Matcher matcher = pattern.matcher(memberAttribute);
                    if (matcher.matches()) {
                        memberAttribute = matcher.group(1);
                    }/*from w  w w.ja v  a  2s  . c  om*/
                }

                pluralAttribute.setValue(memberAttribute);
                members.add(pluralAttribute);
            }
        }

        // add the members to the group resource
        group.setAny(members);
    }

    return group;
}

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
 *//*ww w  .  j a va  2  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.jasig.schedassist.impl.oraclecalendar.OracleCalendarUserAccountAttributesMapper.java

public Object mapFromAttributes(Attributes attributes) throws NamingException {
    OracleCalendarUserAccount user = new OracleCalendarUserAccount();
    NamingEnumeration<String> attributeNames = attributes.getIDs();
    Map<String, String> attributesMap = new HashMap<String, String>();
    while (attributeNames.hasMore()) {
        String attributeName = attributeNames.next();
        Attribute attribute = attributes.get(attributeName);
        String value = (String) attribute.get();
        if (null != value) {
            value = value.trim();/*from ww  w .  j a  v a2  s  . c om*/
        }
        final String lcAttributeName = attributeName.toLowerCase();
        attributesMap.put(lcAttributeName, value);

        if (USERNAME_ATTRIBUTE.equals(lcAttributeName)) {
            user.setUsername(value);
        } else if (CALENDAR_UNIQUEID_ATTRIBUTE.equals(lcAttributeName)) {
            user.setCtcalxitemid(value);
        } else if (EMAIL_ATTRIBUTE.equals(lcAttributeName)) {
            user.setEmailAddress(value);
        } else if (DISPLAYNAME_ATTRIBUTE.equals(lcAttributeName)) {
            user.setDisplayName(value);
        } else if (GIVENNAME_ATTRIBUTE.equals(lcAttributeName)) {
            user.setGivenName(value);
        } else if (SURNAME_ATTRIBUTE.equals(lcAttributeName)) {
            user.setSurname(value);
        }
    }
    user.setAttributes(attributesMap);

    if (user.getCalendarUniqueId() != null) {
        String oracleGuid = this.oracleGUIDSource.getOracleGUID(user);
        user.setOracleGuid(oracleGuid);
        user.getAttributes().put(AbstractOracleCalendarAccount.ORACLE_GUID_ATTRIBUTE, oracleGuid);
    }
    return user;
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

private String getStringValue(Attributes attributes, LDAPAttributeNames attributeName) throws NamingException {
    String ret = null;//from  www.j  a va2  s  .  com
    Attribute attribute = attributes.get(attributeName.getLdapKey());
    if (attribute != null) {
        for (int i = 0; i < attribute.size(); i++) {
            ret = (String) attribute.get(i);
        }
    }
    return ret;
}

From source file:com.evolveum.midpoint.pwdfilter.opendj.PasswordPusher.java

private void readConfig() throws InitializationException {

    String configFile = "/opt/midpoint/opendj-pwdpusher.xml";
    if (System.getProperty("config") != null) {
        configFile = System.getProperty("config");
    }//from  w w  w  .j a  v a2s.c  o  m

    File f = new File(configFile);
    if (!f.exists() || !f.canRead()) {
        throw new IllegalArgumentException("Config file " + configFile + " does not exist or is not readable");
    }

    try {
        XMLConfiguration config = new XMLConfiguration(f);

        String notifierDN = "cn=" + config.getString("passwordpusher.statusNotifierName")
                + ",cn=Account Status Notification Handlers";
        String ldapURL = config.getString("passwordpusher.ldapServerURL");
        boolean ldapSSL = config.getBoolean("passwordpusher.ldapServerSSL");
        String ldapUsername = config.getString("passwordpusher.ldapServerUsername");
        String ldapPassword = config.getString("passwordpusher.ldapServerPassword");

        Hashtable<Object, Object> env = new Hashtable<Object, Object>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapURL + "/cn=config");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
        env.put(Context.SECURITY_CREDENTIALS, ldapPassword);

        if (ldapSSL) {
            env.put(Context.SECURITY_PROTOCOL, "ssl");
        }

        try {
            DirContext context = new InitialDirContext(env);
            Attributes attr = context.getAttributes(notifierDN);

            this.endPoint = attr.get("ds-cfg-referrals-url").get(0).toString();
            this.username = attr.get("ds-cfg-midpoint-username").get(0).toString();
            this.password = attr.get("ds-cfg-midpoint-password").get(0).toString();
            this.pwdChangeDirectory = attr.get("ds-cfg-midpoint-passwordcachedir").get(0).toString();
        } catch (NamingException ne) {
            throw new InitializationException(
                    ERR_MIDPOINT_PWDSYNC_READING_CONFIG_FROM_LDAP.get(ne.getMessage()), ne);
        }
    } catch (ConfigurationException ce) {
        throw new InitializationException(ERR_MIDPOINT_PWDSYNC_PARSING_XML_CONFIG.get(ce.getMessage()), ce);
    }
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from LDAP. */
private List<String> getUserList(JndiLdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    String userDnTemplate = r.getUserDnTemplate();
    String userDn[] = userDnTemplate.split(",", 2);
    String userDnPrefix = userDn[0].split("=")[0];
    String userDnSuffix = userDn[1];
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {/*from   www . j a  v  a2s .  c o m*/
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setCountLimit(numUsersToFetch);
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        String[] attrIDs = { userDnPrefix };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userDnSuffix, "(" + userDnPrefix + "=*" + searchText + "*)",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userDnPrefix) != null) {
                String currentUser = attrs.get(userDnPrefix).toString();
                userList.add(currentUser.split(":")[1].trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    LOGGER.info("UserList: " + userList);
    return userList;
}

From source file:org.apache.zeppelin.service.ShiroAuthenticationService.java

/** Function to extract users from Zeppelin LdapRealm. */
private List<String> getUserList(LdapRealm r, String searchText, int numUsersToFetch) {
    List<String> userList = new ArrayList<>();
    LOGGER.debug("SearchText: " + searchText);
    String userAttribute = r.getUserSearchAttributeName();
    String userSearchRealm = r.getUserSearchBase();
    String userObjectClass = r.getUserObjectClass();
    JndiLdapContextFactory cf = (JndiLdapContextFactory) r.getContextFactory();
    try {/*from  w  ww. j  a  va2s . c  o  m*/
        LdapContext ctx = cf.getSystemLdapContext();
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
        constraints.setCountLimit(numUsersToFetch);
        String[] attrIDs = { userAttribute };
        constraints.setReturningAttributes(attrIDs);
        NamingEnumeration result = ctx.search(userSearchRealm,
                "(&(objectclass=" + userObjectClass + ")(" + userAttribute + "=*" + searchText + "*))",
                constraints);
        while (result.hasMore()) {
            Attributes attrs = ((SearchResult) result.next()).getAttributes();
            if (attrs.get(userAttribute) != null) {
                String currentUser;
                if (r.getUserLowerCase()) {
                    LOGGER.debug("userLowerCase true");
                    currentUser = ((String) attrs.get(userAttribute).get()).toLowerCase();
                } else {
                    LOGGER.debug("userLowerCase false");
                    currentUser = (String) attrs.get(userAttribute).get();
                }
                LOGGER.debug("CurrentUser: " + currentUser);
                userList.add(currentUser.trim());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error retrieving User list from Ldap Realm", e);
    }
    return userList;
}

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

public String getStringAttribute(final Attributes attributes, final String attribute) throws NamingException {
    final Attribute temp;
    final String attributeValue;
    temp = attributes.get(attribute);
    if (temp != null) {
        attributeValue = (String) temp.get();
        logger.debug(attribute + ": " + getStringValue("cn"));
    } else {//from   w w w.j  av a  2  s .  c  om
        attributeValue = null;
    }

    return attributeValue;
}

From source file:alpine.auth.LdapConnectionWrapper.java

/**
 * Retrieves an attribute by its name.// w  ww  .j  a v  a2  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:org.wso2.carbon.user.core.ldap.LDAPConnectionContext.java

private void populateDCMap() throws UserStoreException {
    try {/*from   ww w.jav  a  2 s .  c  om*/
        //get the directory context for DNS
        DirContext dnsContext = new InitialDirContext(environmentForDNS);
        //compose the DNS service to be queried
        String DNSServiceName = LDAPConstants.ACTIVE_DIRECTORY_DOMAIN_CONTROLLER_SERVICE + DNSDomainName;
        //query the DNS
        Attributes attributes = dnsContext.getAttributes(DNSServiceName,
                new String[] { LDAPConstants.SRV_ATTRIBUTE_NAME });
        Attribute srvRecords = attributes.get(LDAPConstants.SRV_ATTRIBUTE_NAME);
        //there can be multiple records with same domain name - get them all
        NamingEnumeration srvValues = srvRecords.getAll();
        dcMap = new TreeMap<Integer, SRVRecord>();
        //extract all SRV Records for _ldap._tcp service under the specified domain and populate dcMap
        //int forcedPriority = 0;
        while (srvValues.hasMore()) {
            String value = srvValues.next().toString();
            SRVRecord srvRecord = new SRVRecord();
            String valueItems[] = value.split(" ");
            String priority = valueItems[0];
            if (priority != null) {
                int priorityInt = Integer.parseInt(priority);

                /*if ((priorityInt == forcedPriority) || (priorityInt < forcedPriority)) {
                forcedPriority++;
                priorityInt = forcedPriority;
                }*/
                srvRecord.setPriority(priorityInt);
            } /* else {
              forcedPriority++;
              srvRecord.setPriority(forcedPriority);
              }*/
            String weight = valueItems[1];
            if (weight != null) {
                srvRecord.setWeight(Integer.parseInt(weight));
            }
            String port = valueItems[2];
            if (port != null) {
                srvRecord.setPort(Integer.parseInt(port));
            }
            String host = valueItems[3];
            if (host != null) {
                srvRecord.setHostName(host);
            }
            //we index dcMap on priority basis, therefore, priorities must be different
            dcMap.put(srvRecord.getPriority(), srvRecord);
        }
        //iterate over the SRVRecords for Active Directory Domain Controllers and figure out the
        //host records for that
        for (SRVRecord srvRecord : dcMap.values()) {
            Attributes hostAttributes = dnsContext.getAttributes(srvRecord.getHostName(),
                    new String[] { LDAPConstants.A_RECORD_ATTRIBUTE_NAME });
            Attribute hostRecord = hostAttributes.get(LDAPConstants.A_RECORD_ATTRIBUTE_NAME);
            //we know there is only one IP value for a given host. So we do just get, not getAll
            srvRecord.setHostIP((String) hostRecord.get());
        }
    } catch (NamingException e) {
        log.error("Error obtaining information from DNS Server" + e.getMessage(), e);
        throw new UserStoreException("Error obtaining information from DNS Server " + e.getMessage(), e);
    }
}