Example usage for javax.naming.ldap Control CRITICAL

List of usage examples for javax.naming.ldap Control CRITICAL

Introduction

In this page you can find the example usage for javax.naming.ldap Control CRITICAL.

Prototype

boolean CRITICAL

To view the source code for javax.naming.ldap Control CRITICAL.

Click Source Link

Document

Indicates a critical control.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String url = "ldap://localhost/o=JNDITutorial";
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "userDN");
    env.put(Context.SECURITY_CREDENTIALS, "secret");

    Control[] connectCtls = new Control[] { null };
    LdapContext ctx = new InitialLdapContext(env, null);

    Control[] ctxCtls = new Control[] { new SortControl(new String[] { "cn" }, Control.CRITICAL) };

    ctx.setRequestControls(ctxCtls);//from  w  w  w  .  ja  v  a2  s .  c om

    NamingEnumeration answer = ctx.list("");

    while (answer.hasMore()) {
        NameClassPair item = (NameClassPair) answer.next();
    }
}

From source file:SortedResults.java

public static void main(String[] args) throws IOException {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {//  w  w  w.  j  a  va2 s .c  o m
        // Create initial context with no connection request controls
        LdapContext ctx = new InitialLdapContext(env, null);

        // Create a sort control that sorts based on CN
        String sortKey = "cn";
        ctx.setRequestControls(new Control[] { new SortControl(sortKey, Control.CRITICAL) });

        // Perform a search
        NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

        // Iterate over search results
        System.out.println("---->sort by cn");
        while (results != null && results.hasMore()) {
            // Display an entry
            SearchResult entry = (SearchResult) results.next();
            System.out.println(entry.getName());

            // Handle the entry's response controls (if any)
            if (entry instanceof HasControls) {
                // ((HasControls)entry).getControls();
            }
        }
        // Examine the sort control response
        Control[] controls = ctx.getResponseControls();
        if (controls != null) {
            for (int i = 0; i < controls.length; i++) {
                if (controls[i] instanceof SortResponseControl) {
                    SortResponseControl src = (SortResponseControl) controls[i];
                    if (!src.isSorted()) {
                        throw src.getException();
                    }
                } else {
                    // Handle other response controls (if any)
                }
            }
        }

        // Close when no longer needed
        ctx.close();
    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:PagedSearch.java

public static void main(String[] args) {

    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {//from   w  ww. ja va2s.  c  o m
        LdapContext ctx = new InitialLdapContext(env, null);

        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;

        do {
            /* perform the search */
            NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult entry = (SearchResult) results.next();
                System.out.println(entry.getName());
            }

            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            System.out.println("(total : " + total);
                        } else {
                            System.out.println("(total: unknown)");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                System.out.println("No controls were sent from the server");
            }
            ctx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);

        ctx.close();

    } catch (NamingException e) {
        System.err.println("PagedSearch failed.");
        e.printStackTrace();
    } catch (IOException ie) {
        System.err.println("PagedSearch failed.");
        ie.printStackTrace();
    }
}

From source file:PagedSearch.java

public static void main(String[] args) {

    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");

    /* Specify host and port to use for directory service */
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=People,o=JNDITutorial");

    try {//  www  .  ja  va2s.c  o  m
        LdapContext ctx = new InitialLdapContext(env, null);

        // Activate paged results
        int pageSize = 5;
        byte[] cookie = null;
        ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
        int total;

        do {
            /* perform the search */
            NamingEnumeration results = ctx.search("", "(objectclass=*)", new SearchControls());

            /* for each entry print out name + all attrs and values */
            while (results != null && results.hasMore()) {
                SearchResult entry = (SearchResult) results.next();
                System.out.println(entry.getName());
            }

            // Examine the paged results control response
            Control[] controls = ctx.getResponseControls();
            if (controls != null) {
                for (int i = 0; i < controls.length; i++) {
                    if (controls[i] instanceof PagedResultsResponseControl) {
                        PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                        total = prrc.getResultSize();
                        if (total != 0) {
                            System.out.println("***************** END-OF-PAGE " + "(total : " + total
                                    + ") *****************\n");
                        } else {
                            System.out.println(
                                    "***************** END-OF-PAGE " + "(total: unknown) ***************\n");
                        }
                        cookie = prrc.getCookie();
                    }
                }
            } else {
                System.out.println("No controls were sent from the server");
            }
            // Re-activate paged results
            ctx.setRequestControls(
                    new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

        } while (cookie != null);

        ctx.close();

    } catch (NamingException e) {
        System.err.println("PagedSearch failed.");
        e.printStackTrace();
    } catch (IOException ie) {
        System.err.println("PagedSearch failed.");
        ie.printStackTrace();
    }
}

From source file:com.adito.activedirectory.PagedResultTemplate.java

private void applyControls(InitialLdapContext context, int pageSize) throws NamingException {
    try {/*from  w w w .  j  av a 2  s  .  co m*/
        Control[] control = new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) };
        context.setRequestControls(control);
    } catch (IOException e) {
        logger.warn("Tried to configure paged search but got error", e);
    }
}

From source file:com.adito.activedirectory.PagedResultTemplate.java

private void applyControls(InitialLdapContext context, int pageSize, byte[] cookie) throws NamingException {
    try {//from  w w w .  ja  va2s .  c  o m
        context.setRequestControls(
                new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
    } catch (IOException ex) {
        logger.warn("Tried to reconfigure paged result controls with error", ex);
    }
}

From source file:edu.vt.middleware.ldap.AbstractLdap.java

/**
 * This will query the LDAP with the supplied dn, filter, filter arguments,
 * and search controls. See {@link #search(String, String, Object[],
 * SearchControls, SearchResultHandler...)}. The PagedResultsControl is used
 * in conjunction with {@link LdapConfig#getPagedResultsSize()} to produce the
 * results./*from www.j av  a 2  s  .c  o  m*/
 *
 * @param  dn  <code>String</code> name to begin search at
 * @param  filter  <code>String</code> expression to use for the search
 * @param  filterArgs  <code>Object[]</code> to substitute for variables in
 * the filter
 * @param  searchControls  <code>SearchControls</code> to perform search with
 * @param  handler  <code>SearchResultHandler[]</code> to post process results
 *
 * @return  <code>Iterator</code> - of LDAP search results
 *
 * @throws  NamingException  if the LDAP returns an error
 */
protected Iterator<SearchResult> pagedSearch(final String dn, final String filter, final Object[] filterArgs,
        final SearchControls searchControls, final SearchResultHandler... handler) throws NamingException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Paginated search with the following parameters:");
        this.logger.debug("  dn = " + dn);
        this.logger.debug("  filter = " + filter);
        this.logger.debug("  filterArgs = " + Arrays.toString(filterArgs));
        this.logger.debug("  searchControls = " + searchControls);
        this.logger.debug("  handler = " + Arrays.toString(handler));
        if (this.logger.isTraceEnabled()) {
            this.logger.trace("  config = " + this.config.getEnvironment());
        }
    }

    final List<SearchResult> results = new ArrayList<SearchResult>();
    LdapContext ctx = null;
    NamingEnumeration<SearchResult> en = null;
    try {
        for (int i = 0; i <= this.config.getOperationRetry() || this.config.getOperationRetry() == -1; i++) {
            try {
                byte[] cookie = null;
                ctx = this.getContext();
                ctx.setRequestControls(new Control[] {
                        new PagedResultsControl(this.config.getPagedResultsSize(), Control.CRITICAL), });
                do {
                    List<SearchResult> pagedResults = null;
                    en = ctx.search(dn, filter, filterArgs, searchControls);

                    if (handler != null && handler.length > 0) {
                        final SearchCriteria sc = new SearchCriteria();
                        if (ctx != null && !"".equals(ctx.getNameInNamespace())) {
                            sc.setDn(ctx.getNameInNamespace());
                        } else {
                            sc.setDn(dn);
                        }
                        sc.setFilter(filter);
                        sc.setFilterArgs(filterArgs);
                        if (searchControls != null) {
                            sc.setReturnAttrs(searchControls.getReturningAttributes());
                        }
                        for (int j = 0; j < handler.length; j++) {
                            if (j == 0) {
                                pagedResults = handler[j].process(sc, en,
                                        this.config.getHandlerIgnoreExceptions());
                            } else {
                                pagedResults = handler[j].process(sc, pagedResults);
                            }
                        }
                    } else {
                        pagedResults = SR_COPY_RESULT_HANDLER.process(null, en,
                                this.config.getHandlerIgnoreExceptions());
                    }

                    results.addAll(pagedResults);

                    final Control[] controls = ctx.getResponseControls();
                    if (controls != null) {
                        for (int j = 0; j < controls.length; j++) {
                            if (controls[j] instanceof PagedResultsResponseControl) {
                                final PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[j];
                                cookie = prrc.getCookie();
                            }
                        }
                    }

                    // re-activate paged results
                    ctx.setRequestControls(
                            new Control[] { new PagedResultsControl(this.config.getPagedResultsSize(), cookie,
                                    Control.CRITICAL), });

                } while (cookie != null);

                break;
            } catch (NamingException e) {
                this.operationRetry(ctx, e, i);
            } catch (IOException e) {
                if (this.logger.isErrorEnabled()) {
                    this.logger.error("Could not encode page size into control", e);
                }
                throw new NamingException(e.getMessage());
            }
        }
    } finally {
        if (en != null) {
            en.close();
        }
        if (ctx != null) {
            ctx.close();
        }
    }
    return results.iterator();
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java

/**
 * {@inheritDoc}/*from  w w  w .  j  a va 2s . c  o  m*/
 */
@Override
// copied from default Alfresco class
public boolean hasNextPage(final DirContext ctx, final int pageSize) {
    if (pageSize > 0) {
        try {
            final LdapContext ldapContext = (LdapContext) ctx;
            final Control[] controls = ldapContext.getResponseControls();

            // Retrieve the paged result cookie if there is one
            if (controls != null) {
                for (final Control control : controls) {
                    if (control instanceof PagedResultsResponseControl) {
                        final byte[] cookie = ((PagedResultsResponseControl) control).getCookie();
                        if (cookie != null) {
                            // Prepare for next page
                            ldapContext.setRequestControls(new Control[] {
                                    new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
                            return true;
                        }
                    }
                }
            }
        } catch (final NamingException nx) {
            throw new AuthenticationException("Unable to connect to LDAP Server; check LDAP configuration", nx);
        } catch (final IOException e) {
            throw new AuthenticationException(
                    "Unable to encode LDAP v3 request controls; check LDAP configuration", e);
        }

    }
    return false;
}

From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.LDAPInitialDirContextFactoryImpl.java

protected InitialDirContext buildInitialDirContext(final Map<String, String> config, final int pageSize,
        final AuthenticationDiagnostic diagnostic) throws AuthenticationException {
    final AuthenticationDiagnostic effectiveDiagnostic = diagnostic != null ? diagnostic
            : new AuthenticationDiagnostic();

    final String securityPrincipal = config.get(Context.SECURITY_PRINCIPAL);
    final String providerURL = config.get(Context.PROVIDER_URL);

    if (this.isSSLSocketFactoryRequired(config)) {
        final KeyStore trustStore = this.initTrustStore();
        ThreadSafeSSLSocketFactory.initTrustedSSLSocketFactory(trustStore);
        config.put("java.naming.ldap.factory.socket", ThreadSafeSSLSocketFactory.class.getName());
    }//from   ww  w.  j  av  a 2  s.  co  m

    try {
        // If a page size has been requested, use LDAP v3 paging
        if (pageSize > 0) {
            final InitialLdapContext ctx = new InitialLdapContext(new Hashtable<>(config), null);
            ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.CRITICAL) });
            return ctx;
        } else {
            final InitialDirContext ret = new InitialDirContext(new Hashtable<>(config));
            final Object[] args = { providerURL, securityPrincipal };
            effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
            return ret;
        }
    } catch (final javax.naming.AuthenticationException ax) {
        final Object[] args1 = { securityPrincipal };
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_AUTHENTICATION, false, args1);

        // wrong user/password - if we get this far the connection is O.K
        final Object[] args2 = { securityPrincipal, ax.getLocalizedMessage() };
        throw new AuthenticationException("authentication.err.authentication", effectiveDiagnostic, args2, ax);
    } catch (final CommunicationException ce) {
        final Object[] args1 = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args1);

        final StringBuffer message = new StringBuffer();

        message.append(ce.getClass().getName() + ", " + ce.getMessage());

        Throwable cause = ce.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.communication", effectiveDiagnostic, args, ce);
    } catch (final NamingException nx) {
        final Object[] args = { providerURL };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTING, false, args);

        final StringBuffer message = new StringBuffer();

        message.append(nx.getClass().getName() + ", " + nx.getMessage());

        Throwable cause = nx.getCause();
        while (cause != null) {
            message.append(", ");
            message.append(cause.getClass().getName() + ", " + cause.getMessage());
            cause = cause.getCause();
        }

        // failed to connect
        final Object[] args1 = { providerURL, message.toString() };
        throw new AuthenticationException("authentication.err.connection", effectiveDiagnostic, args1, nx);
    } catch (final IOException e) {
        final Object[] args = { providerURL, securityPrincipal };
        effectiveDiagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_CONNECTED, true, args);

        throw new AuthenticationException("Unable to encode LDAP v3 request controls", e);
    }
}

From source file:com.aurel.track.util.LdapUtil.java

/**
 * Get all ldap groups//w  w  w  .  j av a 2s  .c om
 * 
 * @param siteBean
 * @param baseDnGroup
 * @param ldapFilterGroups
 * @param groupAttributeName
 * @param groupToMemberReferencesMap
 * @return
 * @throws Exception
 */
public static Map<String, TPersonBean> getLdapGroupsByList(String baseURL, TSiteBean siteBean,
        String groupAttributeName, Map<String, List<String>> groupToMemberReferencesMap,
        Map<String, String> groups) throws Exception {
    HashMap<String, TPersonBean> ldapGroupsMap = new HashMap<String, TPersonBean>();
    String bindDN = siteBean.getLdapBindDN();
    String bindPassword = siteBean.getLdapBindPassword();
    String groupMemberAttributName = ldapMap.get(LDAP_CONFIG.GROUP_MEMBER);
    if (groupMemberAttributName == null) {
        LOGGER.debug(
                "No groupMember attribute defined in quartz-jobs.xml. Fall back to " + DEFAULT_GROUP_MEMBER);
        groupMemberAttributName = DEFAULT_GROUP_MEMBER;
    }
    LdapContext baseContext = getInitialContext(baseURL, bindDN, bindPassword);
    if (baseContext == null) {
        LOGGER.warn("Context is null for baseURL " + baseURL);
        return ldapGroupsMap;
    }
    for (Map.Entry<String, String> groupEntry : groups.entrySet()) {
        String groupName = groupEntry.getKey();
        String groupDN = groupEntry.getValue();
        int index = groupDN.indexOf(",");
        if (index != -1) {
            String searchPart = groupDN.substring(0, index);
            String searchStr = "(" + searchPart + ")";
            String parentDNPart = groupDN.substring(index + 1);
            LdapContext context = (LdapContext) baseContext.lookup(parentDNPart);
            if (context == null) {
                LOGGER.warn("Context is null after lookup for " + parentDNPart);
                continue;
            }
            int recordCount = 0;
            SearchControls ctls = null;
            try {
                // Activate paged results
                int pageSize = 5;
                byte[] cookie = null;
                context.setRequestControls(
                        new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
                int total;
                // Control the search
                ctls = new SearchControls();
                ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                ctls.setCountLimit((ApplicationBean.getInstance().getMaxNumberOfFullUsers()
                        + ApplicationBean.getInstance().getMaxNumberOfLimitedUsers()) * 3 + 10); // Don't ask for more than we can
                                                                                                                                                                             // handle anyways
                do {
                    /* perform the search */
                    NamingEnumeration<SearchResult> results = context.search("", searchStr, ctls);
                    /*
                     * for each entry print out name + all attrs and values
                     */
                    while (results != null && results.hasMore()) {
                        SearchResult searchResult = (SearchResult) results.next();
                        // Attributes atrs = sr.getAttributes();
                        Attributes attributes = searchResult.getAttributes();
                        if (attributes == null) {
                            LOGGER.warn("No attributes found in LDAP search result " + searchResult.getName());
                            continue;
                        }
                        TPersonBean personBean = new TPersonBean();
                        try {
                            personBean.setLoginName(groupName);
                            ldapGroupsMap.put(personBean.getLoginName(), personBean);
                            Attribute memberAttribute = attributes.get(groupMemberAttributName);
                            if (memberAttribute != null) {
                                NamingEnumeration<?> members = memberAttribute.getAll();
                                while (members != null && members.hasMore()) {
                                    String memberSearchResult = (String) members.next();
                                    List<String> memberDNList = groupToMemberReferencesMap.get(groupName);
                                    if (memberDNList == null) {
                                        memberDNList = new ArrayList<String>();
                                        groupToMemberReferencesMap.put(groupName, memberDNList);
                                    }
                                    LOGGER.debug("Member found: " + memberSearchResult);
                                    memberDNList.add(memberSearchResult);
                                }
                            } else {
                                LOGGER.info("Could not find value(s) for group member attribute "
                                        + groupMemberAttributName + " for group " + groupName);
                            }
                            LOGGER.debug("LDAP entry cn: " + (String) attributes.get("cn").get());
                            LOGGER.debug("Processed group " + groupName);
                        } catch (Exception e) {
                            LOGGER.warn("Problem setting attributes from LDAP: " + e.getMessage());
                            LOGGER.warn(
                                    "This is probably a configuration error in the LDAP mapping section of quartz-jobs.xml");
                            if (LOGGER.isDebugEnabled()) {
                                LOGGER.debug("Stack trace:", e);
                            }
                        }
                        ++recordCount;
                    }
                    // Examine the paged results control response
                    Control[] controls = context.getResponseControls();
                    if (controls != null) {
                        for (int i = 0; i < controls.length; i++) {
                            if (controls[i] instanceof PagedResultsResponseControl) {
                                PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
                                total = prrc.getResultSize();
                                if (total != 0) {
                                    LOGGER.debug("***************** END-OF-PAGE " + "(total : " + total
                                            + ") *****************\n");
                                } else {
                                    LOGGER.debug("***************** END-OF-PAGE "
                                            + "(total: unknown) ***************\n");
                                }
                                cookie = prrc.getCookie();
                            }
                        }
                    } else {
                        LOGGER.debug("No controls were sent from the server");
                    }
                    // Re-activate paged results
                    context.setRequestControls(
                            new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });

                } while (cookie != null);
            } catch (SizeLimitExceededException sle) {
                if (recordCount < ctls.getCountLimit()) {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the LDAP server.");
                    LOGGER.error("Size limit exceeded error occurred after record " + recordCount + " with "
                            + sle.getMessage());
                    LOGGER.error(
                            "You have to ask your LDAP server admin to increase the limit or specify a more suitable search base or filter.");
                } else {
                    LOGGER.error("Searching LDAP asked for more entries than permitted by the Genji server ("
                            + recordCount + ").");
                    LOGGER.error(
                            "You have to get more user licenses for Genji or specify a more suitable search base or filter.");
                }
                LOGGER.error("The LDAP synchronization is most likely incomplete.");
            } catch (NamingException e) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            } catch (IOException ie) {
                LOGGER.error("PagedSearch failed.");
                LOGGER.debug(ExceptionUtils.getStackTrace(ie));
            } finally {
                context.close();
            }
        }
    }
    return ldapGroupsMap;
}