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.cggh.repo.security.sync.ldap.LDAPUserRegistry.java

public Collection<String> getGroupNames() {
    final List<String> groupNames = new LinkedList<String>();
    processQuery(new AbstractSearchCallback() {

        protected void doProcess(SearchResult result) throws NamingException, ParseException {
            Attribute nameAttribute = result.getAttributes().get(LDAPUserRegistry.this.groupIdAttributeName);
            if (nameAttribute == null) {
                if (LDAPUserRegistry.this.errorOnMissingGID) {
                    Object[] params = { result.getNameInNamespace(),
                            LDAPUserRegistry.this.groupIdAttributeName };
                    throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params);
                } else {
                    LDAPUserRegistry.logger.warn("Missing GID1 on " + result.getNameInNamespace());
                }/*from   w w  w.j  a  v  a 2  s .  c om*/
            } else {
                String authority = "GROUP_" + (String) nameAttribute.get();
                if (LDAPUserRegistry.logger.isDebugEnabled()) {
                    LDAPUserRegistry.logger.debug("Group DN recognized: " + authority);
                }
                groupNames.add(authority);
            }
        }

        public void close() throws NamingException {
        }

    }, this.groupSearchBase, this.groupQuery, new String[] { this.groupIdAttributeName });
    return groupNames;
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

public Collection<String> getGroupNames() {
    final List<String> groupNames = new LinkedList<String>();
    processQuery(new SearchCallback() {

        public void process(SearchResult result) throws NamingException, ParseException {
            Attribute nameAttribute = result.getAttributes()
                    .get(LDAPMultiBaseUserRegistry.this.groupIdAttributeName);
            if (nameAttribute == null) {
                if (LDAPMultiBaseUserRegistry.this.errorOnMissingGID) {
                    Object[] params = { result.getNameInNamespace(),
                            LDAPMultiBaseUserRegistry.this.groupIdAttributeName };
                    throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params);
                } else {
                    LDAPMultiBaseUserRegistry.logger.warn("Missing GID on " + result.getNameInNamespace());
                }//from  www .  j av  a  2 s .  c om
            } else {
                String authority = "GROUP_" + (String) nameAttribute.get();
                if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
                    LDAPMultiBaseUserRegistry.logger.debug("Group DN recognized: " + authority);
                }
                groupNames.add(authority);
            }
        }

        public void close() throws NamingException {
        }

    }, this.groupSearchBases, this.groupQuery, new String[] { this.groupIdAttributeName });
    return groupNames;
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

public Collection<String> getGroupNames() {
    final List<String> groupNames = new LinkedList<String>();
    processQuery(new AbstractSearchCallback() {

        protected void doProcess(SearchResult result) throws NamingException, ParseException {
            Attribute nameAttribute = result.getAttributes().get(LDAPUserRegistry.this.groupIdAttributeName);
            if (nameAttribute == null) {
                if (LDAPUserRegistry.this.errorOnMissingGID) {
                    Object[] params = { result.getNameInNamespace(),
                            LDAPUserRegistry.this.groupIdAttributeName };
                    throw new AlfrescoRuntimeException("synchronization.err.ldap.get.group.id.missing", params);
                } else {
                    LDAPUserRegistry.logger.warn("Missing GID on " + result.getNameInNamespace());
                }//  w  ww  .  j  a v  a  2 s.co m
            } else {
                String authority = "GROUP_" + (String) nameAttribute.get();
                if (LDAPUserRegistry.logger.isDebugEnabled()) {
                    LDAPUserRegistry.logger.debug("Group DN recognized: " + authority);
                }
                groupNames.add(authority);
            }
        }

        public void close() throws NamingException {
        }

    }, this.groupSearchBase, this.groupQuery, new String[] { this.groupIdAttributeName });
    return groupNames;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * {@inheritDoc}/*from w  ww.  j  av  a  2  s  .  c om*/
 */
public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {
    boolean debug = log.isDebugEnabled();
    String[] userNames = new String[0];

    if (maxItemLimit == 0) {
        return userNames;
    }

    int givenMax;
    int searchTime;

    try {
        givenMax = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_USER_LIST));
    } catch (Exception e) {
        givenMax = CommonConstants.MAX_USER_LIST;
    }

    try {
        searchTime = Integer.parseInt(userStoreProperties.get(CommonConstants.PROPERTY_MAX_SEARCH_TIME));
    } catch (Exception e) {
        searchTime = CommonConstants.MAX_SEARCH_TIME;
    }

    if (maxItemLimit <= 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);
    searchCtls.setTimeLimit(searchTime);

    if (filter.contains("?") || filter.contains("**")) {
        throw new UserStoreException(
                "Invalid character sequence entered for user search. Please enter valid sequence.");
    }

    StringBuilder searchFilter = new StringBuilder(
            userStoreProperties.get(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBases = userStoreProperties.get(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = userStoreProperties.get(LDAPConstants.USER_NAME_ATTRIBUTE);

    String serviceNameAttribute = "sn";

    StringBuilder finalFilter = new StringBuilder();

    // read the display name attribute - if provided
    String displayNameAttribute = userStoreProperties.get(LDAPConstants.DISPLAY_NAME_ATTRIBUTE);

    String[] returnedAtts;

    if (StringUtils.isNotEmpty(displayNameAttribute)) {
        returnedAtts = new String[] { userNameProperty, serviceNameAttribute, displayNameAttribute };
        finalFilter.append("(&").append(searchFilter).append("(").append(displayNameAttribute).append("=")
                .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");
    } else {
        returnedAtts = new String[] { userNameProperty, serviceNameAttribute };
        finalFilter.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=")
                .append(escapeSpecialCharactersForFilterWithStarAsRegex(filter)).append("))");
    }

    if (debug) {
        log.debug(
                "Listing users. SearchBase: " + searchBases + " Constructed-Filter: " + finalFilter.toString());
        log.debug("Search controls. Max Limit: " + maxItemLimit + " Max Time: " + searchTime);
    }

    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    List<String> list = new ArrayList<>();

    try {
        dirContext = connectionSource.getContext();
        // handle multiple search bases
        String[] searchBaseArray = searchBases.split(CommonConstants.XML_PATTERN_SEPERATOR);

        for (String searchBase : searchBaseArray) {

            answer = dirContext.search(escapeDNForSearch(searchBase), finalFilter.toString(), searchCtls);
            while (answer.hasMoreElements()) {
                SearchResult sr = answer.next();
                if (sr.getAttributes() != null) {
                    log.debug("Result found ..");
                    Attribute attr = sr.getAttributes().get(userNameProperty);

                    // If this is a service principle, just ignore and
                    // iterate rest of the array. The entity is a service if
                    // value of surname is Service

                    Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute);

                    if (attrSurname != null) {
                        if (debug) {
                            log.debug(serviceNameAttribute + " : " + attrSurname);
                        }
                        String serviceName = (String) attrSurname.get();
                        if (serviceName != null
                                && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                            continue;
                        }
                    }

                    if (attr != null) {
                        String name = (String) attr.get();
                        list.add(name);
                    }
                }
            }
        }
        userNames = list.toArray(new String[list.size()]);
        Arrays.sort(userNames);

        if (debug) {
            for (String username : userNames) {
                log.debug("result: " + username);
            }
        }
    } catch (PartialResultException e) {
        // can be due to referrals in AD. so just ignore error
        String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : "
                + maxItemLimit;
        if (isIgnorePartialResultException()) {
            if (log.isDebugEnabled()) {
                log.debug(errorMessage, e);
            }
        } else {
            throw new UserStoreException(errorMessage, e);
        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while getting user list for filter : " + filter + "max limit : "
                + maxItemLimit;
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return userNames;
}

From source file:org.wso2.carbon.user.core.ldap.ReadWriteLDAPUserStoreManager.java

/**
 * Check whether this is the last/only user in this group.
 *
 * @param userDN/*from   w  w  w  .java 2 s . com*/
 * @param groupEntry
 * @return groupContext
 */
@SuppressWarnings("rawtypes")
protected boolean isOnlyUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException {
    boolean isOnlyUserInRole = false;
    try {
        Attributes groupAttributes = groupEntry.getAttributes();
        if (groupAttributes != null) {
            NamingEnumeration attributes = groupAttributes.getAll();
            while (attributes.hasMoreElements()) {
                Attribute memberAttribute = (Attribute) attributes.next();
                String memberAttributeName = realmConfig
                        .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                String attributeID = memberAttribute.getID();
                if (memberAttributeName.equals(attributeID)) {
                    if (memberAttribute.size() == 1 && userDN.equals(memberAttribute.get())) {
                        return true;
                    }
                }

            }

            attributes.close();

        }
    } catch (NamingException e) {
        String errorMessage = "Error occurred while looping through attributes set of group: "
                + groupEntry.getNameInNamespace();
        if (log.isDebugEnabled()) {
            log.debug(errorMessage, e);
        }
        throw new UserStoreException(errorMessage, e);
    }
    return isOnlyUserInRole;
}

From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java

public Collection<String> getPersonNames() {
    final List<String> personNames = new LinkedList<String>();
    processQuery(new AbstractSearchCallback() {
        protected void doProcess(SearchResult result) throws NamingException, ParseException {
            Attribute nameAttribute = result.getAttributes().get(LDAPUserRegistry.this.userIdAttributeName);
            if (nameAttribute == null) {
                if (LDAPUserRegistry.this.errorOnMissingUID) {
                    Object[] params = { result.getNameInNamespace(),
                            LDAPUserRegistry.this.userIdAttributeName };
                    throw new AlfrescoRuntimeException("synchronization.err.ldap.get.user.id.missing", params);
                } else {
                    LDAPUserRegistry.logger
                            .warn("User missing user id attribute DN =" + result.getNameInNamespace()
                                    + "  att = " + LDAPUserRegistry.this.userIdAttributeName);
                }/*  w  w w  .j  a v a 2s. c om*/
            } else {
                if (LDAPUserRegistry.logger.isDebugEnabled()) {
                    LDAPUserRegistry.logger.debug("Person DN recognized: " + nameAttribute.get());
                }
                personNames.add((String) nameAttribute.get());
            }
        }

        public void close() throws NamingException {
        }

    }, this.userSearchBase, this.personQuery, new String[] { this.userIdAttributeName });
    return personNames;
}

From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java

public Collection<String> getPersonNames() {
    final List<String> personNames = new LinkedList<String>();
    processQuery(new SearchCallback() {
        public void process(SearchResult result) throws NamingException, ParseException {
            Attribute nameAttribute = result.getAttributes()
                    .get(LDAPMultiBaseUserRegistry.this.userIdAttributeName);
            if (nameAttribute == null) {
                if (LDAPMultiBaseUserRegistry.this.errorOnMissingUID) {
                    Object[] params = { result.getNameInNamespace(),
                            LDAPMultiBaseUserRegistry.this.userIdAttributeName };
                    throw new AlfrescoRuntimeException("synchronization.err.ldap.get.user.id.missing", params);
                } else {
                    LDAPMultiBaseUserRegistry.logger
                            .warn("User missing user id attribute DN =" + result.getNameInNamespace()
                                    + "  att = " + LDAPMultiBaseUserRegistry.this.userIdAttributeName);
                }//from  w  ww.  j  a  v a2 s.co  m
            } else {
                if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) {
                    LDAPMultiBaseUserRegistry.logger.debug("Person DN recognized: " + nameAttribute.get());
                }
                personNames.add((String) nameAttribute.get());
            }
        }

        public void close() throws NamingException {
        }

    }, this.userSearchBases, this.personQuery, new String[] { this.userIdAttributeName });
    return personNames;
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 */// w w  w .ja  v a2  s. c o m
public void loadUserByAccountName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String accountName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField dataField : aUserBag.getFields()) {
        fieldName = dataField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = dataField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_COMMON_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aUserBag Active Directory user fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///from   ww  w. ja  v  a 2 s.c o  m
public void loadUserByCommonName(DataBag aUserBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadUserByCommonName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String commonName = null;
    int attrCount = aUserBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aUserBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_COMMON_NAME))
            commonName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (commonName == null) {
        String msgStr = String.format("LDAP common name '%s' is unassigned.", LDAP_COMMON_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String userSearchBaseDN = getPropertyValue("user_searchbasedn", null);
    String userSearchFilter = String.format("(&(objectClass=user)(%s=%s))", LDAP_COMMON_NAME, commonName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(userSearchBaseDN, userSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aUserBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", userSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.nridge.core.app.ldap.ADQuery.java

/**
 * Queries Active Directory for attributes defined within the bag.
 * The LDAP_ACCOUNT_NAME field must be populated prior to invoking
 * this method.  Any site specific fields can be assigned to the
 * bag will be included in the attribute query.
 *
 * @param aGroupBag Active Directory group fields.
 *
 * @throws NSException Thrown if an LDAP naming exception is occurs.
 *///  w w  w.j av a  2  s  .c o  m
public void loadGroupByAccountName(DataBag aGroupBag) throws NSException {
    byte[] objectSid;
    Attribute responseAttribute;
    String fieldName, fieldValue;
    Attributes responseAttributes;
    Logger appLogger = mAppMgr.getLogger(this, "loadGroupByAccountName");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (mLdapContext == null) {
        String msgStr = "LDAP context has not been established.";
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    int field = 0;
    String accountName = null;
    int attrCount = aGroupBag.count();
    String[] ldapAttrNames = new String[attrCount];
    for (DataField complexField : aGroupBag.getFields()) {
        fieldName = complexField.getName();
        if (fieldName.equals(LDAP_ACCOUNT_NAME))
            accountName = complexField.getValueAsString();
        ldapAttrNames[field++] = fieldName;
    }
    searchControls.setReturningAttributes(ldapAttrNames);

    if (accountName == null) {
        String msgStr = String.format("LDAP account name '%s' is unassigned.", LDAP_ACCOUNT_NAME);
        appLogger.error(msgStr);
        throw new NSException(msgStr);
    }

    String groupSearchBaseDN = getPropertyValue("group_searchbasedn", null);
    String groupSearchFilter = String.format("(&(objectClass=group)(%s=%s))", LDAP_ACCOUNT_NAME, accountName);
    try {
        NamingEnumeration<?> searchResponse = mLdapContext.search(groupSearchBaseDN, groupSearchFilter,
                searchControls);
        if ((searchResponse != null) && (searchResponse.hasMore())) {
            responseAttributes = ((SearchResult) searchResponse.next()).getAttributes();
            for (DataField complexField : aGroupBag.getFields()) {
                fieldName = complexField.getName();
                responseAttribute = responseAttributes.get(fieldName);
                if (responseAttribute != null) {
                    if (fieldName.equals(LDAP_OBJECT_SID)) {
                        objectSid = (byte[]) responseAttribute.get();
                        fieldValue = objectSidToString2(objectSid);
                    } else
                        fieldValue = (String) responseAttribute.get();
                    if (StringUtils.isNotEmpty(fieldValue))
                        complexField.setValue(fieldValue);
                }
            }
            searchResponse.close();
        }
    } catch (NamingException e) {
        String msgStr = String.format("LDAP Search Error (%s): %s", groupSearchFilter, e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}