Example usage for javax.naming NamingEnumeration close

List of usage examples for javax.naming NamingEnumeration close

Introduction

In this page you can find the example usage for javax.naming NamingEnumeration close.

Prototype

public void close() throws NamingException;

Source Link

Document

Closes this enumeration.

Usage

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

/**
 * Check whether this is the last/only user in this group.
 *
 * @param userDN DN of the User./*from   www. ja  va 2s  .c  om*/
 * @param groupEntry SearchResult Representing the Group.
 * @return true if user is the only one in role, false otherwise.
 */
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 = userStoreProperties.get(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.wso2.carbon.identity.agent.onprem.userstore.manager.ldap.LDAPUserStoreManager.java

/**
 * Check whether user is in the group by searching through its member attributes.
 *
 * @param userDN DN of the User whose existence in the group is searched.
 * @param groupEntry SearchResult representation of the Group.
 * @return true if the user exists in the role, false otherwise.
 * @throws UserStoreException If an error occurs while retrieving data.
 */// ww w.j a v a 2s. c om
protected boolean isUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException {
    boolean isUserInRole = false;
    try {
        Attributes groupAttributes = groupEntry.getAttributes();
        if (groupAttributes != null) {
            // get group's returned attributes
            NamingEnumeration attributes = groupAttributes.getAll();
            // loop through attributes
            while (attributes.hasMoreElements()) {
                Attribute memberAttribute = (Attribute) attributes.next();
                String memberAttributeName = userStoreProperties.get(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                if (memberAttributeName.equalsIgnoreCase(memberAttribute.getID())) {
                    // loop through attribute values
                    for (int i = 0; i < memberAttribute.size(); i++) {
                        if (userDN.equalsIgnoreCase((String) memberAttribute.get(i))) {
                            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 isUserInRole;
}

From source file:org.wso2.carbon.identity.agent.onprem.userstore.util.JNDIUtil.java

public static void closeNamingEnumeration(NamingEnumeration<?> namingEnumeration) {

    if (namingEnumeration != null) {
        try {/*  w w  w  .  j  av a  2 s .com*/
            namingEnumeration.close();
        } catch (NamingException e) {
            String errorMessage = "Error in closing NamingEnumeration.";
            log.error(errorMessage, e);
        }
    }

}

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

/**
 * Check whether user is in the group by searching through its member attributes.
 *
 * @param userDN/*  w  w w  .  j  a v a 2 s.c  o  m*/
 * @param groupEntry
 * @return
 * @throws UserStoreException
 */
protected boolean isUserInRole(String userDN, SearchResult groupEntry) throws UserStoreException {
    boolean isUserInRole = false;
    try {
        Attributes groupAttributes = groupEntry.getAttributes();
        if (groupAttributes != null) {
            // get group's returned attributes
            NamingEnumeration attributes = groupAttributes.getAll();
            // loop through attributes
            while (attributes.hasMoreElements()) {
                Attribute memberAttribute = (Attribute) attributes.next();
                String memberAttributeName = realmConfig
                        .getUserStoreProperty(LDAPConstants.MEMBERSHIP_ATTRIBUTE);
                if (memberAttributeName.equalsIgnoreCase(memberAttribute.getID())) {
                    // loop through attribute values
                    for (int i = 0; i < memberAttribute.size(); i++) {
                        if (userDN.equalsIgnoreCase((String) memberAttribute.get(i))) {
                            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 isUserInRole;
}

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  ww .  j av  a2 s  . co m
 * @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.wso2.carbon.user.core.util.JNDIUtil.java

/**
 * Util method to close the used NamingEnumerations to free up resources.
 *
 * @param namingEnumeration//from  www.  j  a  v a 2 s  .co  m
 */
public static void closeNamingEnumeration(NamingEnumeration<?> namingEnumeration) {

    if (namingEnumeration != null) {
        try {
            namingEnumeration.close();
        } catch (NamingException e) {
            String errorMessage = "Error in closing NamingEnumeration.";
            log.error(errorMessage, e);
        }
    }

}

From source file:org.zanata.ZanataInit.java

private static void list(Context ctx, String indent, StringBuffer buffer, boolean verbose) {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    try {//  w  ww . j  av a 2 s  .  co m
        NamingEnumeration<NameClassPair> ne = ctx.list("");
        while (ne.hasMore()) {
            NameClassPair pair = ne.next();
            String name = pair.getName();
            String className = pair.getClassName();
            boolean recursive = false;
            boolean isLinkRef = false;
            boolean isProxy = false;
            Class<?> c = null;
            try {
                c = loader.loadClass(className);
                if (Context.class.isAssignableFrom(c)) {
                    recursive = true;
                }
                if (LinkRef.class.isAssignableFrom(c)) {
                    isLinkRef = true;
                }
                isProxy = Proxy.isProxyClass(c);
            } catch (ClassNotFoundException cnfe) {
                // If this is a $Proxy* class its a proxy
                if (className.startsWith("$Proxy")) {
                    isProxy = true;
                    // We have to get the class from the binding
                    try {
                        Object p = ctx.lookup(name);
                        c = p.getClass();
                    } catch (NamingException e) {
                        Throwable t = e.getRootCause();
                        if (t instanceof ClassNotFoundException) {
                            // Get the class name from the exception msg
                            String msg = t.getMessage();
                            if (msg != null) {
                                // Reset the class name to the CNFE class
                                className = msg;
                            }
                        }
                    }
                }
            }
            buffer.append(indent).append(" +- ").append(name);
            // Display reference targets
            if (isLinkRef) {
                // Get the
                try {
                    Object obj = ctx.lookupLink(name);
                    LinkRef link = (LinkRef) obj;
                    buffer.append("[link -> ");
                    buffer.append(link.getLinkName());
                    buffer.append(']');
                } catch (Throwable t) {
                    buffer.append("invalid]");
                }
            }
            // Display proxy interfaces
            if (isProxy) {
                buffer.append(" (proxy: ").append(pair.getClassName());
                if (c != null) {
                    Class<?>[] ifaces = c.getInterfaces();
                    buffer.append(" implements ");
                    for (Class<?> iface : ifaces) {
                        buffer.append(iface);
                        buffer.append(',');
                    }
                    buffer.setCharAt(buffer.length() - 1, ')');
                } else {
                    buffer.append(" implements ").append(className).append(")");
                }
            } else if (verbose) {
                buffer.append(" (class: ").append(pair.getClassName()).append(")");
            }
            buffer.append('\n');
            if (recursive) {
                try {
                    Object value = ctx.lookup(name);
                    if (value instanceof Context) {
                        Context subctx = (Context) value;
                        list(subctx, indent + " |  ", buffer, verbose);
                    } else {
                        buffer.append(indent).append(" |   NonContext: ").append(value);
                        buffer.append('\n');
                    }
                } catch (Throwable t) {
                    buffer.append("Failed to lookup: ").append(name).append(", errmsg=").append(t.getMessage());
                    buffer.append('\n');
                }
            }
        }
        ne.close();
    } catch (NamingException ne) {
        buffer.append("error while listing context ").append(ctx.toString()).append(": ")
                .append(ne.toString(true));
    }
}

From source file:ru.runa.wfe.security.logic.LdapLogic.java

private int synchronizeActors(DirContext dirContext, Map<String, Actor> actorsByDistinguishedName)
        throws Exception {
    int changesCount = 0;
    List<Actor> existingActorsList = executorDao.getAllActors(BatchPresentationFactory.ACTORS.createNonPaged());
    Map<String, Actor> existingActorsMap = Maps.newHashMap();
    for (Actor actor : existingActorsList) {
        existingActorsMap.put(actor.getName().toLowerCase(), actor);
    }/*from w  w w  . j ava  2s  .  c  o m*/
    Set<Actor> ldapActorsToDelete = Sets.newHashSet();
    if (LdapProperties.isSynchronizationDeleteExecutors()) {
        ldapActorsToDelete.addAll(executorDao.getGroupActors(importGroup));
    }
    SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    for (String ou : LdapProperties.getSynchronizationOrganizationUnits()) {
        List<SearchResult> resultList = Lists.newArrayList();
        try {
            NamingEnumeration<SearchResult> list = dirContext.search(ou, OBJECT_CLASS_USER_FILTER, controls);
            while (list.hasMore()) {
                SearchResult searchResult = list.next();
                resultList.add(searchResult);
            }
            list.close();
        } catch (SizeLimitExceededException e) {
            resultList.clear();
            for (String y : ALPHABETS) {
                NamingEnumeration<SearchResult> list = dirContext.search(ou,
                        MessageFormat.format(LOGIN_FIRST_LETTER_FILTER, ATTR_ACCOUNT_NAME, y, y.toLowerCase(),
                                OBJECT_CLASS_USER_FILTER),
                        controls);
                while (list.hasMore()) {
                    SearchResult searchResult = list.next();
                    resultList.add(searchResult);
                }
                list.close();
            }
        }
        for (SearchResult searchResult : resultList) {
            String name = getStringAttribute(searchResult, ATTR_ACCOUNT_NAME);
            String description = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDescriptionAttribute());
            String fullName = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserFullNameAttribute());
            String email = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserEmailAttribute());
            String phone = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserPhoneAttribute());
            String title = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserTitleAttribute());
            String department = getStringAttribute(searchResult,
                    LdapProperties.getSynchronizationUserDepartmentAttribute());
            ToStringHelper toStringHelper = MoreObjects.toStringHelper("user info");
            toStringHelper.add("name", name).add("description", description).add("fullName", fullName)
                    .add("email", email);
            toStringHelper.add("phone", phone).add("title", title).add("department", department)
                    .omitNullValues();
            log.debug("Read " + toStringHelper.toString());
            Actor actor = existingActorsMap.get(name.toLowerCase());
            if (actor == null) {
                if (!LdapProperties.isSynchronizationCreateExecutors()) {
                    continue;
                }
                actor = new Actor(name, description, fullName, null, email, phone, title, department);
                log.info("Creating " + actor);
                executorDao.create(actor);
                executorDao.addExecutorsToGroup(Lists.newArrayList(actor), importGroup);
                permissionDao.setPermissions(importGroup, Lists.newArrayList(Permission.LIST), actor);
                changesCount++;
            } else {
                ldapActorsToDelete.remove(actor);
                if (LdapProperties.isSynchronizationUpdateExecutors()) {
                    List<IChange> changes = Lists.newArrayList();
                    if (isAttributeNeedsChange(description, actor.getDescription())) {
                        changes.add(new AttributeChange("description", actor.getDescription(), description));
                        actor.setDescription(description);
                    }
                    if (isAttributeNeedsChange(fullName, actor.getFullName())) {
                        changes.add(new AttributeChange("fullName", actor.getFullName(), fullName));
                        actor.setFullName(fullName);
                    }
                    if (isAttributeNeedsChange(email, actor.getEmail())) {
                        changes.add(new AttributeChange("email", actor.getEmail(), email));
                        actor.setEmail(email);
                    }
                    if (isAttributeNeedsChange(phone, actor.getPhone())) {
                        changes.add(new AttributeChange("phone", actor.getPhone(), phone));
                        actor.setPhone(phone);
                    }
                    if (isAttributeNeedsChange(title, actor.getTitle())) {
                        changes.add(new AttributeChange("title", actor.getTitle(), title));
                        actor.setTitle(title);
                    }
                    if (isAttributeNeedsChange(department, actor.getDepartment())) {
                        changes.add(new AttributeChange("department", actor.getDepartment(), department));
                        actor.setDepartment(department);
                    }
                    if (!actor.isActive()) {
                        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
                            actor.setActive(true);
                            changes.add(new AttributeChange("active", "false", "true"));
                        }
                        if (executorDao.removeExecutorFromGroup(actor, wasteGroup)) {
                            changes.add(new Change("waste group removal"));
                        }
                        if (executorDao.addExecutorToGroup(actor, importGroup)) {
                            changes.add(new Change("import group addition"));
                        }
                    }
                    if (!changes.isEmpty()) {
                        executorDao.update(actor);
                        log.info("Updating " + actor + ": " + changes);
                        changesCount++;
                    }
                }
            }
            actorsByDistinguishedName.put(searchResult.getNameInNamespace(), actor);
        }
    }
    if (LdapProperties.isSynchronizationDeleteExecutors() && ldapActorsToDelete.size() > 0) {
        if (LdapProperties.isSynchronizationUserStatusEnabled()) {
            for (Actor actor : ldapActorsToDelete) {
                actor.setActive(false);
                executorDao.update(actor);
                log.info("Inactivating " + actor);
                changesCount++;
            }
        }
        executorDao.removeExecutorsFromGroup(ldapActorsToDelete, importGroup);
        executorDao.addExecutorsToGroup(ldapActorsToDelete, wasteGroup);
        changesCount += ldapActorsToDelete.size();
    }
    return changesCount;
}