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() 

Source Link

Document

Constructs a search constraints using defaults.

Usage

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTest.java

/**
 * Search for all users starting at <code>ou=roles</code>, looking for objects with
 * <code>objectClass=organizationalRole</code>, and extracting the <code>uid</code> token of the
 * <code>roleOccupant</code> attribute.
 *//* www .j ava 2 s.  co m*/
@Test
public void testGetAllUserNames3() {
    SearchControls con3 = new SearchControls();
    con3.setReturningAttributes(new String[] { "roleOccupant" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramsFactory = new LdapSearchParamsFactoryImpl("ou=roles", //$NON-NLS-1$
            "(objectClass=organizationalRole)", con3); //$NON-NLS-1$

    Transformer transformer3 = new SearchResultToAttrValueList("roleOccupant", "uid"); //$NON-NLS-1$ //$NON-NLS-2$

    LdapSearch allUsernamesSearch = new GenericLdapSearch(getContextSource(), paramsFactory, transformer3);

    DefaultLdapUserRoleListService userRoleListService = getDefaultLdapUserRoleListService();

    userRoleListService.setAllUsernamesSearch(allUsernamesSearch);

    List res = userRoleListService.getAllUsers();

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("tiffany")); //$NON-NLS-1$
    assertTrue(res.contains("admin")); //$NON-NLS-1$

    if (logger.isDebugEnabled()) {
        logger.debug("results of getAllUserNames3(): " + res); //$NON-NLS-1$
    }
}

From source file:org.dcm4che3.conf.dicom.ldap.LdapConfigUtils.java

static NamingEnumeration<SearchResult> searchSubcontextWithClass(
        LdapConfigurationStorage ldapConfigurationStorage, String childObjClass, String dn)
        throws NamingException {
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(1);//from  www  . ja v  a  2s  . c o m
    ctls.setReturningObjFlag(false);
    return ldapConfigurationStorage.getLdapCtx().search(dn, "(objectclass=" + childObjClass + ")", ctls);
}

From source file:net.jolm.JolmLdapTemplate.java

private SearchControls getDefaultSearchControls(int searchScope, boolean returnObjFlag, String[] attributes) {
    SearchControls controls = new SearchControls();

    controls.setSearchScope(searchScope);
    controls.setReturningObjFlag(returnObjFlag);
    controls.setReturningAttributes(attributes);
    controls.setTimeLimit(this.searchTimeoutInMs);

    return controls;
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Se conecta a la url indicada y se descarga las crls. No se esta usando
 * *******************!!! En desarrollo, no funciona
 * //from  ww w.jav  a2 s.co  m
 * @param hostURL
 * @return
 * @throws CRLException
 *             No se ha podido recuperar el listado
 * @throws CertificateParsingException
 */
@SuppressWarnings("unchecked")
private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509)
        throws CRLException, CertificateParsingException {
    // ************************
    // recupero las propiedades para realizar la busqueda en LDAP.
    // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase
    // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1}
    Map<String, String> propiedades = new HashMap<String, String>();
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: "
                + certificadoX509.getIssuerDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)
        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            log.debug("   El certificado NO tiene punto de distribucin de CRL ");
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();

            X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades);

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }

    // comprobamos la configuracin
    if (isSomeFNMTValorNull()) {
        throw new CRLException(
                "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :"
                        + Constantes.CONEXION_LDAP_CRL_FNMT);
    }

    String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN();
    log.debug("Buscando en el LDAP " + CN);

    // **********************************************
    // Nos conectamos al LDAP para recuperar la CRLs.

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, fnmtLDAPHostURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial);
    env.put(Context.REFERRAL, "follow");

    try {
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls));

        log.debug("Se ha logrado conectar al LDAP");

        if (namings.hasMore()) {
            log.debug("Recuperando el contenido de la CRLs");
            // recupero el resultado
            SearchResult resultado = ((SearchResult) namings.next());

            // recupero todos los atributos del resultado
            Attributes avals = resultado.getAttributes();

            // recupero los bytes.
            byte[] bytes;
            if ((avals.get("certificateRevocationList;binary")) != null) {
                log.debug("Atributos deben estar en binario");
                Attribute atributo = (avals.get("certificateRevocationList;binary"));
                bytes = ((byte[]) atributo.get());
            } else {
                log.debug("Atributos en exadecimal En Hexadecimal");
                Attribute atributo = (avals.get("certificateRevocationList"));
                bytes = ((byte[]) atributo.get());
                log.debug("Por implementar");
            }

            if (bytes != null) {
                ByteArrayInputStream io = new ByteArrayInputStream(bytes);
                return io;
            }
        }
    } catch (NamingException e) {
        log.error("No se puede conectar al LDAP!!", e);
    }
    return null;
}

From source file:it.infn.ct.security.utilities.LDAPUtils.java

public static LDAPUser getUser(String cn) {
    LDAPUser user = null;// w ww  . ja v  a2 s  .  c  o  m
    NamingEnumeration results = null;
    DirContext ctx = null;
    try {
        ctx = getContext();
        SearchControls controls = new SearchControls();
        String retAttrs[] = { "cn", "sn", "givenName", "title", "registeredAddress", "mail", "memberOf",
                "createTimestamp" };
        controls.setReturningAttributes(retAttrs);
        controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
        ResourceBundle rb = ResourceBundle.getBundle("ldap");

        results = ctx.search(rb.getString("peopleRoot"), "(cn=" + cn + ")", controls);
        if (results.hasMore()) {
            SearchResult searchResult = (SearchResult) results.next();
            Attributes attributes = searchResult.getAttributes();
            user = new LDAPUser();

            if (attributes.get("cn") != null)
                user.setUsername((String) attributes.get("cn").get());
            if (attributes.get("sn") != null)
                user.setSurname((String) attributes.get("sn").get());
            if (attributes.get("givenName") != null)
                user.setGivenname((String) attributes.get("givenName").get());
            if (attributes.get("title") != null)
                user.setTitle((String) attributes.get("title").get());
            if (attributes.get("registeredAddress") != null)
                user.setPreferredMail((String) attributes.get("registeredAddress").get(0));
            if (attributes.get("mail") != null) {
                String mails = "";
                for (int i = 0; i < attributes.get("mail").size(); i++) {
                    if (i != 0)
                        mails = mails + ", ";
                    mails = mails + (String) attributes.get("mail").get(i);
                }
                user.setAdditionalMails(mails);
            }
            if (attributes.get("memberOf") != null) {
                for (int i = 0; i < attributes.get("memberOf").size(); i++) {
                    user.addGroup((String) attributes.get("memberOf").get(i));
                }
            }

            if (attributes.get("createTimestamp") != null) {
                String time = (String) attributes.get("createTimestamp").get();
                DateFormat ldapData = new SimpleDateFormat("yyyyMMddHHmmss");
                user.setCreationTime(ldapData.parse(time));
            }

        }
    } catch (NameNotFoundException ex) {
        _log.error(ex);
    } catch (NamingException e) {
        _log.error(e);
    } catch (ParseException ex) {
        _log.error(ex);
    } finally {
        if (results != null) {
            try {
                results.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Exception e) {
                // Never mind this.
            }
        }
    }

    return user;
}

From source file:org.swordess.ldap.odm.core.SessionImpl.java

@Override
public List<Map<String, Object>> search(Class<?> clazz, String filter, String[] returningAttrs) {
    if (null == filter) {
        return null;
    }/*from  w  w  w.jav a2  s .  co m*/

    LogUtils.debug(LOG, String.format("search %s with filter=%s, returningAttrs=%s", clazz.getName(), filter,
            Arrays.toString(returningAttrs)));

    SearchControls ctrl = new SearchControls();
    ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctrl.setReturningAttributes(returningAttrs);

    try {
        List<Map<String, Object>> retVal = new ArrayList<Map<String, Object>>();
        NamingEnumeration<SearchResult> results = ctx.search(EntityMetaData.get(clazz).context(), filter, ctrl);
        while (results.hasMore()) {
            try {
                SearchResult result = results.next();
                retVal.add(fromAttributesToMap(clazz, result.getAttributes()));
            } catch (NamingException e) {
                LogUtils.error(LOG, "Unable to construct the map", e);
            }
        }
        return retVal;
    } catch (NamingException e) {
        throw new SessionException(e.getMessage(), e);
    }
}

From source file:org.eclipse.skalli.core.user.ldap.LDAPClient.java

@SuppressWarnings("nls")
private SearchControls getSearchControls() {
    SearchControls sc = new SearchControls();
    if ("base".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.OBJECT_SCOPE);
    } else if ("onelevel".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.ONELEVEL_SCOPE);
    } else if ("subtree".equalsIgnoreCase(config.getSearchScope())) {
        sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
    }//from  ww  w .j a  v  a 2  s  . c o  m
    sc.setReturningAttributes(LDAPAttributeNames.getAll());
    return sc;
}

From source file:org.pentaho.test.platform.plugin.services.security.userrole.ldap.DefaultLdapUserRoleListServiceTests.java

/**
 * Search for all users starting at <code>ou=users</code>, looking for objects with
 * <code>businessCategory=cn={0}*</code>, and returning the <code>uid</code> attribute. This search implies that the
 * schema is setup such that a user's roles come from one of the user's attributes.
 *//*from  w  w  w  . j  a  va2s  . co  m*/
@Test
public void testGetUsernamesInRole1() {
    SearchControls con1 = new SearchControls();
    con1.setReturningAttributes(new String[] { "uid" }); //$NON-NLS-1$

    LdapSearchParamsFactory paramFactory = new LdapSearchParamsFactoryImpl("ou=users", //$NON-NLS-1$
            "(businessCategory=cn={0}*)", con1); //$NON-NLS-1$

    Transformer transformer1 = new SearchResultToAttrValueList("uid"); //$NON-NLS-1$

    GrantedAuthorityToString transformer2 = new GrantedAuthorityToString();

    LdapSearch usernamesInRoleSearch = new GenericLdapSearch(getContextSource(), paramFactory, transformer1,
            transformer2);

    DefaultLdapUserRoleListService userRoleListService = new DefaultLdapUserRoleListService();

    userRoleListService.setUsernamesInRoleSearch(usernamesInRoleSearch);

    List<String> res = userRoleListService.getUsersInRole(null, "DEV"); //$NON-NLS-1$

    assertTrue(res.contains("pat")); //$NON-NLS-1$
    assertTrue(res.contains("tiffany")); //$NON-NLS-1$

    if (logger.isDebugEnabled()) {
        logger.debug("results of getUsernamesInRole1(): " + res); //$NON-NLS-1$
    }
}

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

public T findById(final DirContext ctx, final Object id, final String... organizationalUnits)
        throws NamingException {
    NamingEnumeration<?> results = null;
    final SearchControls controls = new SearchControls();
    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    final String searchBase = getSearchBase(organizationalUnits);
    final String args = "(&(objectClass=" + getObjectClass() + ")(" + getIdAttrId() + "=" + buildId(id) + "))";
    results = ctx.search(searchBase, args, controls);
    if (results.hasMore() == false) {
        return null;
    }/*from  w ww  . j  a v a 2  s.  co  m*/
    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() + "." + id);
    }
    return mapToObject(dn, searchBase, attributes);
}

From source file:ru.efo.security.ADUserDetailsService.java

private void describeRoles(DirContext context, Attribute memberOf, Set<String> groups, Set<String> roles)
        throws NamingException {
    if (memberOf != null) {
        for (int i = 0; i < memberOf.size(); i++) {
            Attribute attr = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }).get("CN");
            if (attr != null) {
                final String role = attr.get().toString();
                if (rolesMapping != null) {
                    for (String key : rolesMapping.keySet()) {
                        if (role.matches(rolesMapping.get(key))) {
                            if (logger.isLoggable(Level.FINE)) {
                                if (!roles.contains(key)) {
                                    logger.log(Level.FINE, "Role: " + key);
                                }//from  ww  w .j a v  a  2  s  . c o  m
                            }
                            roles.add(key);
                        }
                    }
                } else {
                    final String roleWithPrefix = (rolePrefix == null ? "" : rolePrefix)
                            + role.toUpperCase().replaceAll("(\\s|-)+", "_");
                    if (logger.isLoggable(Level.FINE)) {
                        if (!roles.contains(role)) {
                            logger.log(Level.FINE, "Role: " + roleWithPrefix);
                        }
                    }
                    roles.add(roleWithPrefix);
                }
                groups.add(role);

                if (recursiveRoleSearch) {
                    SearchControls controls = new SearchControls();
                    controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                    NamingEnumeration<SearchResult> renum = context.search(
                            groupSearchBase != null ? groupSearchBase : userSearchBase, "(CN=" + role + ")",
                            controls);
                    if (renum.hasMore()) {
                        SearchResult searchResult = renum.next();
                        attr = searchResult.getAttributes().get("memberOf");
                        describeRoles(context, attr, groups, roles);
                    }
                }
            }
        }
    }
}