Example usage for javax.naming.directory SearchControls SearchControls

List of usage examples for javax.naming.directory SearchControls SearchControls

Introduction

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

Prototype

public SearchControls(int scope, long countlim, int timelim, String[] attrs, boolean retobj, boolean deref) 

Source Link

Document

Constructs a search constraints using arguments.

Usage

From source file:org.hyperic.hq.plugin.netservices.LDAPCollector.java

/**
 * Construct default SearchControls/*  w w w.j a v a  2s  .  c om*/
 */
private SearchControls getSearchControls() {
    // Set the scope to subtree, default is one-level
    int scope = SearchControls.SUBTREE_SCOPE;

    // Use 'socket timeout' for search timeout.
    int timeLimit = getTimeoutMillis();

    // No limit on the number of entries returned
    long countLimit = 0;

    // Attributes to return.
    String returnedAttributes[] = null;

    // Don't return the object
    boolean returnObject = false;

    // No dereferencing during the search
    boolean deference = false;

    SearchControls constraints = new SearchControls(scope, countLimit, timeLimit, returnedAttributes,
            returnObject, deference);
    return constraints;
}

From source file:org.jkcsoft.java.util.JndiHelper.java

public static Map getUserInfo(BehavioralContext ctx, String userName) throws NamingException {
    Map infoMap = null;/*from   w ww.j ava  2 s.  c  o  m*/

    Configuration cfg = ctx.getConfig();
    // 
    String searchRelativeDc = cfg.getString(Constants.KEY_AD_USER_NODE_DN);
    String theFilter = LDAP_USER_SAMACCOUNTNAME + "=" + userName;
    List theAttrsList = new Vector(Arrays.asList(ldapUserAttrs));
    theAttrsList.addAll(Arrays.asList(ldapTopAttrs));

    int countLimit = 1000;
    int timeLimitMillis = 30000;
    boolean returnObject = false;
    boolean derefObj = true;

    SearchControls scs = new SearchControls(SearchControls.SUBTREE_SCOPE, countLimit, timeLimitMillis,
            (String[]) theAttrsList.toArray(new String[0]), returnObject, derefObj);

    DirContext rootCtx = getTsessAccountContext(ctx);

    try {
        log.debug("Search params name[" + searchRelativeDc + "] " + "filter[" + theFilter + "] controls[" + scs
                + "]");

        NamingEnumeration results = rootCtx.search(searchRelativeDc, theFilter, scs);

        if (results == null || !results.hasMore())
            throw new NamingException("User LDAP entry not found");

        SearchResult searchResult = ((SearchResult) results.next());
        if (searchResult == null)
            throw new NamingException("User LDAP entry not found");

        if (log.isTraceEnabled()) {
            logLdap(log, 0, 0, searchResult);
        }

        Attributes userLdapAttrs = searchResult.getAttributes();
        infoMap = new HashMap();
        for (Iterator attrIter = theAttrsList.iterator(); attrIter.hasNext();) {
            loadMap(infoMap, userLdapAttrs, (String) attrIter.next());
        }
    } finally {
        safeClose(rootCtx);
    }

    return infoMap;
}

From source file:com.liferay.portal.security.ldap.internal.exportimport.LDAPUserImporterImpl.java

@Override
public User importUser(long ldapServerId, long companyId, String emailAddress, String screenName)
        throws Exception {

    LdapContext ldapContext = null;

    NamingEnumeration<SearchResult> enu = null;

    try {//from w w  w. j  av a 2  s  .  c o m
        LDAPServerConfiguration ldapServerConfiguration = _ldapServerConfigurationProvider
                .getConfiguration(companyId, ldapServerId);

        String baseDN = ldapServerConfiguration.baseDN();

        ldapContext = _portalLDAP.getContext(ldapServerId, companyId);

        if (ldapContext == null) {
            _log.error("Unable to bind to the LDAP server");

            return null;
        }

        String filter = ldapServerConfiguration.authSearchFilter();

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter before transformation " + filter);
        }

        filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@" },
                new String[] { String.valueOf(companyId), emailAddress, screenName });

        LDAPUtil.validateFilter(filter);

        if (_log.isDebugEnabled()) {
            _log.debug("Search filter after transformation " + filter);
        }

        Properties userMappings = _ldapSettings.getUserMappings(ldapServerId, companyId);

        String userMappingsScreenName = GetterUtil.getString(userMappings.getProperty("screenName"));

        userMappingsScreenName = StringUtil.toLowerCase(userMappingsScreenName);

        SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0,
                new String[] { userMappingsScreenName }, false, false);

        enu = ldapContext.search(baseDN, filter, searchControls);

        if (enu.hasMoreElements()) {
            if (_log.isDebugEnabled()) {
                _log.debug("Search filter returned at least one result");
            }

            Binding binding = enu.nextElement();

            Attributes attributes = _portalLDAP.getUserAttributes(ldapServerId, companyId, ldapContext,
                    binding.getNameInNamespace());

            return importUser(ldapServerId, companyId, ldapContext, attributes, null);
        } else {
            return null;
        }
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn("Problem accessing LDAP server " + e.getMessage());
        }

        if (_log.isDebugEnabled()) {
            _log.debug(e, e);
        }

        throw new SystemException("Problem accessing LDAP server " + e.getMessage());
    } finally {
        if (enu != null) {
            enu.close();
        }

        if (ldapContext != null) {
            ldapContext.close();
        }
    }
}

From source file:org.danann.cernunnos.ldap.SearchTask.java

public void perform(TaskRequest req, TaskResponse res) {

    // Construct the LdapTemplate...
    final ContextSource cs = (ContextSource) contextSource.evaluate(req, res);
    final LdapTemplate template = new LdapTemplate(cs);

    // Construct the SearchControls...
    final int p = (Integer) scope.evaluate(req, res);
    final long m = Long.valueOf((String) limit.evaluate(req, res));
    final int o = Integer.valueOf((String) timeout.evaluate(req, res));
    String[] a = null; // default...
    if (attributes != null) {
        a = new String[attributes.size()];
        for (int i = 0; i < a.length; i++) {
            a[i] = (String) attributes.get(i).evaluate(req, res);
        }/*  w  ww  .j  a v  a 2s. c  om*/
    }
    final boolean ro = (Boolean) returnObject.evaluate(req, res);
    final boolean dl = (Boolean) dereferenceLinks.evaluate(req, res);
    SearchControls controls = new SearchControls(p, m, o, a, ro, dl);

    // Execute the search...
    final String name = (String) attributeName.evaluate(req, res);
    final String bdn = (String) baseDn.evaluate(req, res);
    final String ftr = (String) filter.evaluate(req, res);
    final String mt = (String) mapperType.evaluate(req, res);
    final AttributesMapper am = (AttributesMapper) attributesMapper.evaluate(req, res);
    final ContextMapper cm = (ContextMapper) contextMapper.evaluate(req, res);

    if (mt.equals("attribute")) {
        try {
            final List<?> rslt = template.search(bdn, ftr, controls, am);
            for (Object j : rslt) {
                res.setAttribute(name, j);
                super.performSubtasks(req, res);
            }

        } catch (Throwable t) {
            String msg = "Error performing the specified LDAP search:" + "\n\t\tBASE_DN=" + bdn
                    + "\n\t\tFILTER=" + ftr + "\n\t\tSCOPE=" + p + "\n\t\tLIMIT=" + m + "\n\t\tTIMEOUT=" + o
                    + "\n\t\tATTRIBUTES=" + a + "\n\t\tRETURN_OBJECT=" + ro + "\n\t\t=DEREFERENCE_LINKS=" + dl
                    + "\n\t\t=MAPPER_TYPE=" + mt + "\n\t\t=ATTRIBUTES_MAPPER (class)=" + am.getClass().getName()
                    + "\n\t\t=CONTEXT_MAPPER (class)=" + cm.getClass().getName();
            throw new RuntimeException(msg, t);
        }
    } else if (mt.equals("context")) {
        try {
            final List<?> rslt = template.search(bdn, ftr, controls, cm);
            for (Object j : rslt) {
                res.setAttribute(name, j);
                super.performSubtasks(req, res);
            }

        } catch (Throwable t) {
            String msg = "Error performing the specified LDAP search:" + "\n\t\tBASE_DN=" + bdn
                    + "\n\t\tFILTER=" + ftr + "\n\t\tSCOPE=" + p + "\n\t\tLIMIT=" + m + "\n\t\tTIMEOUT=" + o
                    + "\n\t\tATTRIBUTES=" + a + "\n\t\tRETURN_OBJECT=" + ro + "\n\t\t=DEREFERENCE_LINKS=" + dl
                    + "\n\t\t=MAPPER_TYPE=" + mt + "\n\t\t=ATTRIBUTES_MAPPER (class)=" + am.getClass().getName()
                    + "\n\t\t=CONTEXT_MAPPER (class)=" + cm.getClass().getName();
            throw new RuntimeException(msg, t);
        }

    } else {
        throw new RuntimeException("Must specify either mapper-type as 'attribute' or 'context'");
    }
}

From source file:com.liferay.portal.action.LoginAction.java

public static void login(HttpServletRequest req, HttpServletResponse res, String login, String password,
        boolean rememberMe) throws Exception {

    CookieKeys.validateSupportCookie(req);

    HttpSession ses = req.getSession();// w ww . j  a va2  s .c om

    long userId = GetterUtil.getLong(login);

    int authResult = Authenticator.FAILURE;

    Company company = PortalUtil.getCompany(req);

    //
    boolean ldaplogin = false;
    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        LdapContext ctx = PortalLDAPUtil.getContext(company.getCompanyId());
        String accountname = "";
        try {
            User user1 = UserLocalServiceUtil.getUserByScreenName(company.getCompanyId(), login);
            Properties env = new Properties();

            String baseProviderURL = PrefsPropsUtil.getString(company.getCompanyId(),
                    PropsUtil.LDAP_BASE_PROVIDER_URL);
            String userDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_USERS_DN);
            String baseDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_DN);
            String filter = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_SEARCH_FILTER);
            filter = StringUtil.replace(filter,
                    new String[] { "@company_id@", "@email_address@", "@screen_name@", "@user_id@" },
                    new String[] { String.valueOf(company.getCompanyId()), "", login, login });
            try {
                SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false,
                        false);

                NamingEnumeration enu = ctx.search(userDN, filter, cons);
                if (enu.hasMoreElements()) {
                    SearchResult result = (SearchResult) enu.nextElement();
                    accountname = result.getName();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil.getString(PropsUtil.LDAP_FACTORY_INITIAL));
            env.put(Context.PROVIDER_URL, LDAPUtil.getFullProviderURL(baseProviderURL, baseDN));
            env.put(Context.SECURITY_PRINCIPAL, accountname + "," + userDN);
            env.put(Context.SECURITY_CREDENTIALS, password);

            new InitialLdapContext(env, null);
            ldaplogin = true;
            System.out.println("LDAP Login");
        } catch (Exception e) {
            SessionErrors.add(req, "ldapAuthentication");
            e.printStackTrace();
            System.out.println("LDAP error login");
            return;
        }
    }

    //

    Map headerMap = new HashMap();

    Enumeration enu1 = req.getHeaderNames();

    while (enu1.hasMoreElements()) {
        String name = (String) enu1.nextElement();

        Enumeration enu2 = req.getHeaders(name);

        List headers = new ArrayList();

        while (enu2.hasMoreElements()) {
            String value = (String) enu2.nextElement();

            headers.add(value);
        }

        headerMap.put(name, (String[]) headers.toArray(new String[0]));
    }

    Map parameterMap = req.getParameterMap();

    if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_EA)) {
        authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_SN)) {
        authResult = UserLocalServiceUtil.authenticateByScreenName(company.getCompanyId(), login, password,
                headerMap, parameterMap);

        userId = UserLocalServiceUtil.getUserIdByScreenName(company.getCompanyId(), login);
    } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_ID)) {
        authResult = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), userId, password,
                headerMap, parameterMap);
    }

    boolean OTPAuth = false;

    if (GetterUtil.getBoolean(PropsUtil.get("use.yubicoauthentication"), false) == true) {
        String otppasswd = ParamUtil.getString(req, "otp");
        String userslist = GetterUtil.getString(PropsUtil.get("yubico.users.not.require.otp"), "root");
        if (userslist.contains(login)) {
            authResult = Authenticator.SUCCESS;
        } else {
            OTPAuth = SecurityUtils.verifyOTP(otppasswd, login);
            if (authResult == Authenticator.SUCCESS && OTPAuth) {
                authResult = Authenticator.SUCCESS;
            } else {
                authResult = Authenticator.FAILURE;
            }
        }
    }

    if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) {
        if (!login.equals("root")) {
            if (ldaplogin) {
                authResult = Authenticator.SUCCESS;
            }
        }
    }

    if (authResult == Authenticator.SUCCESS) {

        boolean loginViaPortal = true;

        setLoginCookies(req, res, ses, userId, rememberMe);
        // login to epsos
        String language = GeneralUtils.getLocale(req);
        SpiritEhrWsClientInterface webService = EpsosHelperService.getInstance().getWebService(req);

        InitUserObj initUserObj = EpsosHelperImpl.createEpsosUserInformation(req, res, language, webService,
                userId, company.getCompanyId(), login, loginViaPortal);
        SpiritUserClientDto usr = initUserObj.getUsr();
        Assertion assertion = initUserObj.getAssertion();

        if (Validator.isNotNull(usr)) {
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTIONID,
                    assertion.getID());
            req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTION, assertion);
            req.getSession().setAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE, usr);
        } else {
            SessionErrors.add(req, "User doesn't belong to epSOS role so you can't login");
        }

        if (Validator.isNull(usr) && (!(login.equals("root")))) {
            try {
                Cookie cookie = new Cookie(CookieKeys.ID, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                cookie = new Cookie(CookieKeys.PASSWORD, StringPool.BLANK);
                cookie.setMaxAge(0);
                cookie.setPath("/");

                CookieKeys.addCookie(res, cookie);

                try {
                    ses.invalidate();
                } catch (Exception e) {
                }

            } catch (Exception e) {
                req.setAttribute(PageContext.EXCEPTION, e);

            }
            throw new AuthException();

        }

    } else {
        throw new AuthException();
    }
}

From source file:org.rhq.enterprise.server.core.jaas.LdapLoginModule.java

/**
 * A simple method to construct a SearchControls object for use when doing LDAP searches. All of the defaults are
 * used, with the exception of the scope, which is set to SUBTREE rather than the default of ONE_LEVEL
 *
 * @return controls what is searched in LDAP
 *///  w  w  w. j a va2s  .  c o  m
private SearchControls getSearchControls() {
    // Set the scope to subtree, default is one-level
    int scope = SearchControls.SUBTREE_SCOPE;

    // No limit on the time waiting for a response
    int timeLimit = 0;

    // No limit on the number of entries returned
    long countLimit = 0;

    // Attributes to return.
    String[] returnedAttributes = null;

    // Don't return the object
    boolean returnObject = false;

    // No dereferencing during the search
    boolean deference = false;

    SearchControls constraints = new SearchControls(scope, countLimit, timeLimit, returnedAttributes,
            returnObject, deference);
    return constraints;
}

From source file:org.cloudfoundry.identity.uaa.ldap.extension.SpringSecurityLdapTemplate.java

/**
 * We need to make sure the search controls has the return object flag set to true, in order for
 * the search to return DirContextAdapter instances.
 * @param originalControls//from w  ww .  j  a  v  a 2  s. c o m
 * @return
 */
private static SearchControls buildControls(SearchControls originalControls) {
    return new SearchControls(originalControls.getSearchScope(), originalControls.getCountLimit(),
            originalControls.getTimeLimit(), originalControls.getReturningAttributes(), RETURN_OBJECT,
            originalControls.getDerefLinkFlag());
}

From source file:fedora.server.security.servletfilters.ldap.FilterLdap.java

private final SearchControls getSearchControls() {
    String m = FilterSetup.getFilterNameAbbrev(FILTER_NAME) + " getSearchControls() ";
    log.debug(m + ">");
    SearchControls searchControls = null;
    try {//from  ww  w .  j a v  a 2s.  c o m
        int nEntries2return = 0;
        int millisecondTimeLimit = 0;
        boolean retobj = true;
        boolean deref = true;
        searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, nEntries2return, millisecondTimeLimit,
                DIRECTORY_ATTRIBUTES_NEEDED, retobj, deref);
    } catch (Throwable th) {
        if (LOG_STACK_TRACES) {
            log.error(m + "couldn't set up search controls for dir search", th);
        } else {
            log.error(m + "couldn't set up search controls for dir search" + th.getMessage());
        }
    } finally {
        log.debug(m + "< " + searchControls);
    }
    return searchControls;
}

From source file:no.feide.moria.directory.backend.JNDIBackend.java

/**
 * Does a subtree search for an element given a pattern. Only the first
 * element found is considered, and all references are searched in order
 * until either a match is found or no more references are left to search.
 * @param ldap// w  w  w.  jav  a2s.c  o  m
 *            A prepared LDAP context.
 * @param pattern
 *            The search pattern. Must not include the character '*' or the
 *            substring '\2a' to prevent possible LDAP exploits.
 * @return The element's relative DN, or <code>null</code> if none was
 *         found. <code>null</code> is also returned if the search pattern
 *         contains an illegal character or substring.
 * @throws BackendException
 *             If there was a problem accessing the backend. Typical causes
 *             include timeouts.
 */
private String ldapSearch(final InitialLdapContext ldap, final String pattern) throws BackendException {

    // Check pattern for illegal content.
    String[] illegals = { "*", "\\2a" };
    for (int i = 0; i < illegals.length; i++) {
        if (pattern.indexOf(illegals[i]) > -1)
            return null;
    }

    // The context provider URL, for later logging.
    String url = "unknown backend";

    // Start counting the (milli)seconds and prepare for timeouts.
    long searchStart = System.currentTimeMillis();
    JNDISearchInterruptor interruptTask = new JNDISearchInterruptor(ldap, mySessionTicket);
    NamingEnumeration results;
    try {

        // Remember the URL, for later logging.
        url = (String) ldap.getEnvironment().get(Context.PROVIDER_URL);
        interruptTask.setURL(url);

        // Start timeout interruptor and perform the search.
        Timer interruptTimer = new Timer();
        interruptTimer.schedule(interruptTask, (1000 * myTimeout));
        results = ldap.search("", pattern, new SearchControls(SearchControls.SUBTREE_SCOPE, 0, 1000 * myTimeout,
                new String[] {}, false, false));
        interruptTimer.cancel();
        if (!results.hasMore())
            return null;

    } catch (TimeLimitExceededException e) {

        // The search timed out.
        log.logWarn("Search on " + url + " for " + pattern + " timed out after ~"
                + (System.currentTimeMillis() - searchStart) + "ms", mySessionTicket);
        return null;

    } catch (SizeLimitExceededException e) {

        // The search returned too many results.
        log.logWarn("Search on " + url + " for " + pattern + " returned too many results", mySessionTicket);
        return null;

    } catch (NameNotFoundException e) {

        // Element not found. Possibly non-existing reference.
        log.logDebug("Could not find " + pattern + " on " + url, mySessionTicket); // Necessary?
        return null;

    } catch (AuthenticationException e) {

        // Search failed authentication; check non-anonymous search config.
        try {
            final String searchUser = (String) ldap.getEnvironment().get(Context.SECURITY_PRINCIPAL);
            final String errorMessage;
            if ((searchUser == null) || searchUser.equals(""))
                errorMessage = "Anonymous search failed authentication on " + url;
            else
                errorMessage = "Could not authenticate search user " + searchUser + " on " + url;
            log.logDebug(errorMessage, mySessionTicket);
            throw new BackendException(errorMessage, e);
        } catch (NamingException f) {

            // Should not happen!
            log.logCritical("Unable to read LDAP environment", mySessionTicket, f);
            throw new BackendException("Unable to read LDAP environment", f);

        }

    } catch (NamingException e) {

        // Did we interrupt the search ourselves?
        if (interruptTask.finished()) {
            final long elapsed = System.currentTimeMillis() - searchStart;
            log.logWarn("Search on " + url + " for " + pattern + " timed out after ~" + elapsed + "ms",
                    mySessionTicket);
            throw new BackendException("Search on " + url + " for " + pattern + " timed out after ~" + elapsed
                    + "ms; connection terminated");
        }

        // All other exceptions.
        log.logWarn("Search on " + url + " for " + pattern + " failed", mySessionTicket, e);
        return null;

    }

    // We just found at least one element. Did we get an ambigious result?
    SearchResult entry = null;
    try {
        entry = (SearchResult) results.next();
        String buffer = new String();
        while (results.hasMoreElements())
            buffer = buffer + ", " + ((SearchResult) results.next()).getName();
        if (!buffer.equals(""))
            log.logWarn("Search on " + url + " for " + pattern + " gave ambiguous result: [" + entry.getName()
                    + buffer + "]", mySessionTicket);
        // TODO: Throw BackendException, or a subclass, or just (as now)
        // pick the first and hope for the best?
        buffer = null;
    } catch (NamingException e) {
        throw new BackendException("Unable to read search results", e);
    }
    return entry.getName(); // Relative DN (to the reference).

}

From source file:nl.nn.adapterframework.ldap.LdapSender.java

private String performOperationSearch(String entryName, ParameterResolutionContext prc, Map paramValueMap,
        String filterExpression, int scope) throws SenderException, ParameterException {
    int timeout = getSearchTimeout();
    SearchControls controls = new SearchControls(scope, getMaxEntriesReturned(), timeout,
            getAttributesReturnedParameter(), false, false);
    //      attrs = parseAttributesFromMessage(message);
    DirContext dirContext = null;
    try {/*  ww  w .j  a  va 2s .c  o  m*/
        dirContext = getDirContext(paramValueMap);
        return searchResultsToXml(dirContext.search(entryName, filterExpression, controls)).toXML();
    } catch (NamingException e) {
        if (isReplyNotFound() && e.getMessage().equals("Unprocessed Continuation Reference(s)")) {
            if (log.isDebugEnabled())
                log.debug("Searching object not found using filter[" + filterExpression + "]");
            return DEFAULT_RESULT_SEARCH;
        } else {
            storeLdapException(e, prc);
            throw new SenderException("Exception searching using filter [" + filterExpression + "]", e);
        }
    } finally {
        closeDirContext(dirContext);
    }
}