Example usage for javax.naming NamingEnumeration hasMore

List of usage examples for javax.naming NamingEnumeration hasMore

Introduction

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

Prototype

public boolean hasMore() throws NamingException;

Source Link

Document

Determines whether there are any more elements in the enumeration.

Usage

From source file:ldap.SearchUtility.java

/**
 *
 * @param searchBase//from  w w  w  . jav a 2s . com
 * @param regexp
 * @param pageSize
 * @param pageNumber
 * @return  a list of matching users.
 * @throws NamingException
 */
public List<Entry> getUsers(LdapName searchBase, String regexp, int pageSize, int pageNumber,
        ArrayList<String> attributes, DirContext context) throws NamingException {
    Pattern pattern = null;
    if (regexp != null)
        pattern = Pattern.compile(regexp);
    /*
     *   Figure out an ldap search filter.  Note that unless an ORDERING matching rule is defined on the server
     *   for the attribute we are searching (and they usually aren't, since it requires extra indexing on the
     *   server), we cannot use ldap greater than / less than search filters to find
     *   a range of users, and have to do this search in code using a regular expression.
     */
    //String filter = "(objectClass=" + Config.USER_OBJECTCLASS + ")";
    String filter = "";
    if (LdapConstants.ldapObjectClassEmployeeEnable) {
        filter = "(objectClass=" + LdapConstants.ldapObjectClassEmployee + ")";
    }
    SearchControls controls = getSearchControls();
    String[] attributesToReturn;
    if (attributes == null) {
        attributesToReturn = null; // a JNDI special value that means 'return everything'
    } else {
        //attributes.add(Config.USER_NAMING_ATT);
        attributes.add(LdapConstants.ldapAttrUid);
        attributesToReturn = attributes.toArray(new String[] {});
    }

    if (controls != null) {
        controls.setReturningAttributes(attributesToReturn);
    } else {
        logger.info("controls is null");
    }

    // do the directory search
    NamingEnumeration<SearchResult> userResults = context.search(searchBase, filter, controls);

    if (userResults == null) {
        logger.info("userResults is Null in getUsers()");
        return null;
    } else {

        // parse the results, looking for entries that match our regexp
        ArrayList<Entry> users = new ArrayList<Entry>();
        while (userResults.hasMore()) {
            SearchResult userResult = userResults.next();
            Entry userEntry = new Entry(userResult);

            //String text =  userEntry.getValue(Config.USER_NAMING_ATT).toUpperCase();
            String text = userEntry.getValue(LdapConstants.ldapAttrUid).toUpperCase();

            if (pattern == null) {
                users.add(userEntry);
            } else {
                Matcher matcher = pattern.matcher(text);
                if (matcher.find()) {
                    users.add(userEntry);
                }
            }
        }

        // sort them alphabeticaly by user naming attribute
        Collections.sort(users);

        // trim the results to the page requested (if any)
        if (pageSize > 0) {
            ArrayList<Entry> userPage = new ArrayList<Entry>(pageSize);
            int startPos = pageSize * pageNumber;
            int size = users.size();
            for (int i = startPos; i < (startPos + pageSize); i++) {
                if (i < size) {
                    userPage.add(users.get(i));
                }
            }
            users = userPage;
        }

        // add 'synthetic' attributes for
        for (Entry user : users) {
            fillInSyntheticAttributes(user);
        }
        // return the final user list
        return users;
    } // else
}

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.
 *//*from  ww w  . j a  v  a 2s . c  om*/
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   w ww .  j a  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  ww . ja va2s . 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);
}

From source file:org.archone.ad.domain.LdapActions.java

@RPCAction(name = "user.membership.get", required = { "userId" })
@SecuredMethod(constraints = "administrator.by_domain")
public HashMap<String, Object> listMermbershipGroups(OperationContext opContext) throws NamingException {

    String userId = (String) opContext.getParams().get("userId");

    UserDn userDn = nameHelper.newUserDnFromId(userId);
    DomainDn domainDn = nameHelper.newDomainDnFromDomain(userDn.getDomain());

    DirContextAdapter userDirContext = (DirContextAdapter) SecurityUtils.getSubject().getPrincipal();

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

    NamingEnumeration<SearchResult> searchResults = userDirContext.search(
            nameHelper.getGroupsBaseDn(nameHelper.newDomainDnFromDomain(userDn.getDomain())),
            "(uniqueMember=" + userDn.toString() + ")", controls);

    List<HashMap<String, Object>> groups = new LinkedList<HashMap<String, Object>>();
    while (searchResults.hasMore()) {
        SearchResult sr = searchResults.next();
        if (nameHelper.isGroupDn(sr.getNameInNamespace().toLowerCase())) {
            HashMap<String, Object> group = new HashMap<String, Object>();
            group.put("groupId", nameHelper.newGroupDn(sr.getNameInNamespace().toLowerCase()).getAsGroupId());
            groups.add(group);//from  ww  w  .  j  a  va  2 s .  com
        }
    }

    HashMap<String, Object> response = new HashMap<String, Object>();
    response.put("groups", groups);

    return response;
}

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

protected Set<PrivilegeEnum> convertLdapGroupsToOrganizationPrivileges(
        NamingEnumeration<SearchResult> pPrivilegesResult) {
    Set<PrivilegeEnum> vResult = EnumSet.noneOf(PrivilegeEnum.class);
    NamingEnumeration<SearchResult> vSearchResults = pPrivilegesResult;
    try {/*from  w ww . j a va  2 s . c o  m*/
        if (pPrivilegesResult != null) {
            PrivilegeEnum p;
            SearchResult sr;
            String vCnPrivileg;
            // construct privileges
            while (vSearchResults.hasMore()) {
                sr = vSearchResults.next();
                vCnPrivileg = (String) sr.getAttributes().get(Constants.ldap_ddbPrivilege_Cn).get();
                p = this.mapToPrivilege(sr.getAttributes(), Constants.ldap_ddbPrivilege_Cn);
                if (p != null) {
                    vResult.add(p);
                } else {
                    LOG.log(Level.WARNING,
                            "Es ist ein nicht existierende Privileg: ''{0}'' im LDAP gespeichert!",
                            new Object[] { vCnPrivileg });
                }
            }
            // -- releases this context's resources immediately, instead of
            // waiting for the garbage collector
            vSearchResults.close();
        }
    } catch (NamingException ne) {
        LOG.log(Level.SEVERE, null, ne);
    } finally {
        // -- releases this context's resources immediately, instead of
        // waiting for the garbage collector
        if (vSearchResults != null) {
            try {
                vSearchResults.close();
            } catch (NamingException ex) {
            }
        }
    }
    return vResult;
}

From source file:org.projectforge.business.ldap.LdapUserDao.java

public LdapUser findByUsername(final Object username, final String... organizationalUnits) {
    return (LdapUser) new LdapTemplate(ldapConnector) {
        @Override/*from  w ww .  j av a  2s  .  c  o  m*/
        protected Object call() throws NameNotFoundException, Exception {
            NamingEnumeration<?> results = null;
            final SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            final String searchBase = getSearchBase(organizationalUnits);
            results = ctx.search(searchBase, "(&(objectClass=" + getObjectClass() + ")(uid=" + username + "))",
                    controls);
            if (results.hasMore() == false) {
                return null;
            }
            final SearchResult searchResult = (SearchResult) results.next();
            final String dn = searchResult.getName();
            final Attributes attributes = searchResult.getAttributes();
            if (results.hasMore() == true) {
                log.error("Oups, found entries with multiple id's: " + getObjectClass() + "." + username);
            }
            return mapToObject(dn, searchBase, attributes);
        }
    }.excecute();
}

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

/**
 * Performs AD-extension to LDAP query that performs recursive group lookup.
 * This Microsoft extension is explained in http://msdn.microsoft.com/en-us/library/aa746475(v=vs.85).aspx
 *
 * @return//www.j a  va 2  s.  co m
 *      false if it appears that this search failed.
 * @see
 */
private boolean chainGroupLookup(String domainDN, String userDN, DirContext context,
        Set<GrantedAuthority> groups) throws NamingException {
    NamingEnumeration<SearchResult> renum = new LDAPSearchBuilder(context, domainDN).subTreeScope()
            .returns("cn").search("(member:1.2.840.113556.1.4.1941:={0})", userDN);
    try {
        if (renum.hasMore()) {
            // http://ldapwiki.willeke.com/wiki/Active%20Directory%20Group%20Related%20Searches cites that
            // this filter search extension requires at least Win2K3 SP2. So if this didn't find anything,
            // fall back to the recursive search

            // TODO: this search alone might be producing the super set of the tokenGroups/objectSid based search in the stage 1.
            parseMembers(userDN, groups, renum);
            return true;
        } else {
            return false;
        }
    } finally {
        renum.close();
    }
}

From source file:org.nuxeo.wizard.RouterServlet.java

public void handleUserPOST(Page currentPage, HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Context ctx = Context.instance(req);
    ParamCollector collector = ctx.getCollector();

    String refreshParam = req.getParameter("refresh");
    String directoryType = collector.getConfigurationParam("nuxeo.directory.type");

    if ("true".equals(refreshParam)) {
        currentPage.dispatchToJSP(req, resp);
        return;/*from   w ww . java  2  s. c  o  m*/
    }

    if ("checkNetwork".equals(refreshParam) || "checkAuth".equals(refreshParam)
            || "checkUserLdapParam".equals(refreshParam) || "checkGroupLdapParam".equals(refreshParam)) {
        try {
            if ("checkNetwork".equals(refreshParam)) {
                bindLdapConnection(collector, false);
                ctx.trackInfo("nuxeo.ldap.url", "info.host.found");
            } else if ("checkAuth".equals(refreshParam)) {
                bindLdapConnection(collector, true);
                ctx.trackInfo("nuxeo.ldap.auth", "info.auth.success");
            } else {
                DirContext dirContext = new InitialDirContext(getContextEnv(collector, true));
                String searchScope;
                String searchBaseDn;
                String searchClass;
                String searchFilter;
                if ("checkUserLdapParam".equals(refreshParam)) {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.user.searchScope");
                    searchClass = collector.getConfigurationParam("nuxeo.ldap.user.searchClass");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.user.searchFilter");
                } else {
                    searchBaseDn = collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn");
                    searchScope = collector.getConfigurationParam("nuxeo.ldap.group.searchScope");
                    searchFilter = collector.getConfigurationParam("nuxeo.ldap.group.searchFilter");
                    searchClass = "";
                }

                SearchControls scts = new SearchControls();
                if ("onelevel".equals(searchScope)) {
                    scts.setSearchScope(SearchControls.ONELEVEL_SCOPE);
                } else {
                    scts.setSearchScope(SearchControls.SUBTREE_SCOPE);
                }
                String filter = String.format("(&(%s)(objectClass=%s))",
                        searchFilter.isEmpty() ? "objectClass=*" : searchFilter,
                        searchClass.isEmpty() ? "*" : searchClass);
                NamingEnumeration<SearchResult> results;
                try {
                    results = dirContext.search(searchBaseDn, filter, scts);
                    if (!results.hasMore()) {
                        ctx.trackError("nuxeo.ldap.search", "error.ldap.noresult");
                    } else {
                        SearchResult result = results.next();
                        if (searchBaseDn.equalsIgnoreCase(result.getNameInNamespace()) && results.hasMore()) {
                            // try not to display the root of the search
                            // base DN
                            result = results.next();
                        }
                        ctx.trackInfo("dn", result.getNameInNamespace());
                        Attributes attributes = result.getAttributes();
                        NamingEnumeration<String> ids = attributes.getIDs();
                        String id;
                        StringBuilder sb;
                        while (ids.hasMore()) {
                            id = ids.next();
                            NamingEnumeration<?> values = attributes.get(id).getAll();
                            sb = new StringBuilder();
                            while (values.hasMore()) {
                                sb.append(values.next()).append(" , ");
                            }
                            ctx.trackInfo(id, sb.substring(0, sb.length() - 3));
                        }
                    }
                } catch (NameNotFoundException e) {
                    ctx.trackError("nuxeo.ldap.search", "error.ldap.searchBaseDn");
                    log.warn(e);
                }
                dirContext.close();
            }
        } catch (AuthenticationException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.auth.failed");
            log.warn(e);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.url", "error.host.not.found");
            log.warn(e);
        }
    }

    // Form submit
    if (!"default".equals(directoryType) && refreshParam.isEmpty()) {
        // first check bind to LDAP server
        try {
            bindLdapConnection(collector, true);
        } catch (NamingException e) {
            ctx.trackError("nuxeo.ldap.auth", "error.ldap.bind.failed");
            log.warn(e);
        }

        // then check mandatory fields
        if (collector.getConfigurationParam("nuxeo.ldap.user.searchBaseDn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.searchBaseDn", "error.user.searchBaseDn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.rdn").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.rdn", "error.user.rdn.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.username").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.username", "error.user.username.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.password").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.password", "error.user.password.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.firstname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.firstname", "error.user.firstname.required");
        }
        if (collector.getConfigurationParam("nuxeo.ldap.user.mapping.lastname").isEmpty()) {
            ctx.trackError("nuxeo.ldap.user.mapping.lastname", "error.user.lastname.required");
        }
        String userGroupStorage = collector.getConfigurationParam("nuxeo.user.group.storage");
        if (!"userLdapOnly".equals(userGroupStorage) && !"multiUserSqlGroup".equals(userGroupStorage)) {
            if (collector.getConfigurationParam("nuxeo.ldap.group.searchBaseDn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.searchBaseDn", "error.group.searchBaseDn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.rdn").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.rdn", "error.group.rdn.required");
            }
            if (collector.getConfigurationParam("nuxeo.ldap.group.mapping.name").isEmpty()) {
                ctx.trackError("nuxeo.ldap.group.mapping.name", "error.group.name.required");
            }
        }
        if ("true".equals(collector.getConfigurationParam("nuxeo.user.emergency.enable"))) {
            if (collector.getConfigurationParam("nuxeo.user.emergency.username").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.username", "error.emergency.username.required");
            }
            if (collector.getConfigurationParam("nuxeo.user.emergency.password").isEmpty()) {
                ctx.trackError("nuxeo.user.emergency.password", "error.emergency.password.required");
            }
        }
    }

    if (ctx.hasErrors() || ctx.hasInfos()) {
        currentPage.dispatchToJSP(req, resp);
    } else {
        currentPage.next().dispatchToJSP(req, resp, true);
    }
}

From source file:org.apache.syncope.fit.core.reference.RoleITCase.java

@Test
public void issueSYNCOPE632() {
    RoleTO roleTO = null;/*from w  ww .  ja va  2s.  com*/
    try {
        // 1. create new LDAP resource having account id mapped to a derived attribute
        ResourceTO newLDAP = resourceService.read(RESOURCE_NAME_LDAP);
        newLDAP.setKey("new-ldap");
        newLDAP.setPropagationPrimary(true);
        MappingItemTO accountId = newLDAP.getRmapping().getAccountIdItem();
        accountId.setIntMappingType(IntMappingType.RoleDerivedSchema);
        accountId.setIntAttrName("displayProperty");
        newLDAP.getRmapping().setAccountIdItem(accountId);
        newLDAP.getRmapping().setAccountLink("'cn=' + displayProperty + ',ou=groups,o=isp'");

        MappingItemTO description = new MappingItemTO();
        description.setIntMappingType(IntMappingType.RoleId);
        description.setExtAttrName("description");
        description.setPurpose(MappingPurpose.BOTH);
        newLDAP.getRmapping().addItem(description);

        newLDAP = createResource(newLDAP);
        assertNotNull(newLDAP);

        // 2. create a role and give the resource created above
        roleTO = buildRoleTO("lastRole");
        roleTO.getRPlainAttrTemplates().add("icon");
        roleTO.getPlainAttrs().add(attrTO("icon", "anIcon"));
        roleTO.getRPlainAttrTemplates().add("show");
        roleTO.getPlainAttrs().add(attrTO("show", "true"));
        roleTO.getRDerAttrTemplates().add("displayProperty");
        roleTO.getDerAttrs().add(attrTO("displayProperty", null));
        roleTO.getResources().clear();
        roleTO.getResources().add("new-ldap");

        roleTO = createRole(roleTO);
        assertNotNull(roleTO);

        // 3. update the role
        RoleMod roleMod = new RoleMod();
        roleMod.setKey(roleTO.getKey());
        roleMod.getPlainAttrsToRemove().add("icon");
        roleMod.getPlainAttrsToUpdate().add(attrMod("icon", "anotherIcon"));

        roleTO = updateRole(roleMod);
        assertNotNull(roleTO);

        // 4. check that a single group exists in LDAP for the role created and updated above
        int entries = 0;
        DirContext ctx = null;
        try {
            ctx = getLdapResourceDirContext(null, null);

            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(new String[] { "*", "+" });
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> result = ctx.search("ou=groups,o=isp",
                    "(description=" + roleTO.getKey() + ")", ctls);
            while (result.hasMore()) {
                result.next();
                entries++;
            }
        } catch (Exception e) {
            // ignore
        } finally {
            if (ctx != null) {
                try {
                    ctx.close();
                } catch (NamingException e) {
                    // ignore
                }
            }
        }

        assertEquals(1, entries);
    } finally {
        if (roleTO != null) {
            roleService.delete(roleTO.getKey());
        }
        resourceService.delete("new-ldap");
    }
}