Example usage for javax.naming.directory SearchControls setSearchScope

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

Introduction

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

Prototype

public void setSearchScope(int scope) 

Source Link

Document

Sets the search scope to one of: OBJECT_SCOPE, ONELEVEL_SCOPE, SUBTREE_SCOPE.

Usage

From source file:org.tolven.gatekeeper.bean.LdapBean.java

private List<TolvenPerson> findTolvenPerson(LdapContext ctx, String peopleBaseName, String principalLdapName,
        String realm, int maxResults, int timeLimit) {
    NamingEnumeration<SearchResult> namingEnum = null;
    SearchControls ctls = new SearchControls();
    ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    ctls.setCountLimit(maxResults);//from  www . j a v a 2 s .c  o m
    ctls.setTimeLimit(timeLimit);
    ArrayList<TolvenPerson> searchResults = new ArrayList<TolvenPerson>(10);
    try {
        namingEnum = ctx.search(peopleBaseName, principalLdapName, ctls);
        while (namingEnum.hasMore()) {
            SearchResult rslt = namingEnum.next();
            searchResults.add(new TolvenPerson(rslt));
        }
    } catch (GatekeeperSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException(
                "Could not search for TolvenPerson: " + principalLdapName + " in realm: " + realm + ": ", ex);
    }
    return searchResults;
}

From source file:org.tolven.gatekeeper.bean.LdapBean.java

/**
 * Find a TolvenPerson// ww  w. java2s .  c  o  m
 * 
 * @param uid
 * @param realm
 * @return
 */
@Override
public TolvenPerson findTolvenPerson(String uid, String realm) {
    LdapContext ctx = null;
    try {
        LdapRealmContext ldapRealmContext = getLdapRealmContext(realm);
        ctx = getLadpContext(ldapRealmContext.getAnonymousUser(),
                ldapRealmContext.getAnonymousUserPassword().toCharArray(), realm);
        SearchControls ctls = new SearchControls();
        ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctls.setCountLimit(1);
        String principalLdapName = ldapRealmContext.getPrincipalName(uid);
        String basePeopleName = ldapRealmContext.getBasePeopleName();
        List<TolvenPerson> tolvenPersons = findTolvenPerson(ctx, basePeopleName, principalLdapName, realm, 1,
                1000);
        if (tolvenPersons.isEmpty()) {
            return null;
        } else {
            return tolvenPersons.get(0);
        }
    } catch (GatekeeperSecurityException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new RuntimeException("Could not find user " + uid + " in realm " + realm, ex);
    } finally {
        close(ctx, realm);
    }
}

From source file:org.tolven.ldapmgr.LDAPMgrPlugin.java

public void updateSchemas() {
    DirContext dirContext = null;
    try {//from ww w  .ja v  a  2 s .c  o  m
        dirContext = getContext();
        SearchControls controls = new SearchControls();
        controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        controls.setCountLimit(1);
        updateSuffix(dirContext);
        updateGroups(dirContext, controls);
        updatePeople(dirContext, controls);
        updateRootDN(dirContext, controls);
        updateUsers(dirContext, controls);
    } finally {
        if (dirContext != null) {
            try {
                dirContext.close();
            } catch (NamingException ex) {
                throw new RuntimeException("Could not close the LDAP context", ex);
            }
        }
    }
}

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 .  j a v a  2 s.c  om*/
 * @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:org.wso2.carbon.appfactory.userstore.AppFactoryTenantManager.java

protected NamingEnumeration searchForObject(String searchFilter, String returnedAtts[], DirContext dirContext,
        String searchBase) throws UserStoreException {
    SearchControls searchCtls;
    searchCtls = new SearchControls();
    searchCtls.setSearchScope(2);
    if (returnedAtts != null && returnedAtts.length > 0)
        searchCtls.setReturningAttributes(returnedAtts);
    try {//from   w  w w  .j  av a  2  s .com
        return dirContext.search(searchBase, searchFilter, searchCtls);
    } catch (NamingException e) {
        log.error("Search failed.", e);
        throw new UserStoreException(e.getMessage());
    }

}

From source file:org.wso2.carbon.appfactory.userstore.internal.OTLDAPUtil.java

public static NamingEnumeration<SearchResult> searchForUser(String searchFilter, String[] returnedAtts,
        DirContext dirContext, String userSearchBase) throws UserStoreException {
    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    if (returnedAtts != null && returnedAtts.length > 0) {
        searchCtls.setReturningAttributes(returnedAtts);
    }//from w  w w  . ja v  a2  s  .c  om
    try {
        return dirContext.search(userSearchBase, searchFilter, searchCtls);
    } catch (NamingException e) {
        log.error("Search failed.", e);
        throw new UserStoreException(e.getMessage());
    }
}

From source file:org.wso2.carbon.appfactory.userstore.OTAppFactoryUserStore.java

@Override
public String[] doListUsers(String filter, int maxItemLimit) throws UserStoreException {
    String[] userNames = new String[0];

    if (maxItemLimit == 0) {
        return userNames;
    }//from  w  w  w .j a  v a 2 s.c  o  m

    int givenMax = Integer
            .parseInt(realmConfig.getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_MAX_USER_LIST));

    if (maxItemLimit < 0 || maxItemLimit > givenMax) {
        maxItemLimit = givenMax;
    }

    SearchControls searchCtls = new SearchControls();
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchCtls.setCountLimit(maxItemLimit);

    if (filter.contains("?") || filter.contains("**")) {
        throw new UserStoreException(
                "Invalid character sequence entered for user serch. Please enter valid sequence.");
    }

    StringBuffer searchFilter = null;
    searchFilter = new StringBuffer(realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_LIST_FILTER));
    String searchBase = realmConfig.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String userNameProperty = realmConfig.getUserStoreProperty(LDAPConstants.USER_NAME_ATTRIBUTE);
    StringBuffer buff = new StringBuffer();
    buff.append("(&").append(searchFilter).append("(").append(userNameProperty).append("=").append(filter)
            .append("))");

    String serviceNameAttribute = "sn";
    String mailAttribute = "mail";
    String returnedAtts[] = { userNameProperty, serviceNameAttribute, mailAttribute };

    searchCtls.setReturningAttributes(returnedAtts);
    DirContext dirContext = null;
    NamingEnumeration<SearchResult> answer = null;
    String[] allUserNames = null;
    try {
        dirContext = connectionSource.getContext();
        answer = dirContext.search(searchBase, buff.toString(), searchCtls);
        List<String> list = new ArrayList<String>();
        int i = 0;
        while (answer.hasMoreElements() && i < maxItemLimit) {
            SearchResult sr = (SearchResult) answer.next();
            if (sr.getAttributes() != null) {
                Attribute attr = sr.getAttributes().get(mailAttribute);

                /*
                 * If this is a service principle, just ignore and iterate rest of the array.
                 * The entity is a service if value of surname is Service
                 */
                Attribute attrSurname = sr.getAttributes().get(serviceNameAttribute);

                if (attrSurname != null) {
                    String serviceName = (String) attrSurname.get();
                    if (serviceName != null
                            && serviceName.equals(LDAPConstants.SERVER_PRINCIPAL_ATTRIBUTE_VALUE)) {
                        continue;
                    }
                }

                if (attr != null) {
                    String name = (String) attr.get();
                    //append the domain if exist
                    String domain = userRealm.getRealmConfiguration()
                            .getUserStoreProperty(UserCoreConstants.RealmConfig.PROPERTY_DOMAIN_NAME);
                    if (domain != null) {
                        domain = domain + "/";
                        name = domain + name;
                    }
                    list.add(name);
                    i++;
                }
            }
        }
        userNames = list.toArray(new String[list.size()]);
        //get secondary user lists
        UserStoreManager secUserManager = this.getSecondaryUserStoreManager();
        if (secUserManager != null) {
            String[] secUserNames = secUserManager.listUsers(filter, maxItemLimit);
            allUserNames = UserCoreUtil.combineArrays(userNames, secUserNames);
        } else {
            allUserNames = userNames;
        }
        Arrays.sort(allUserNames);
    } catch (NamingException e) {
        log.error(e.getMessage(), e);
        throw new UserStoreException(e.getMessage(), e);
    } finally {
        JNDIUtil.closeNamingEnumeration(answer);
        JNDIUtil.closeContext(dirContext);
    }
    return allUserNames;
}

From source file:org.wso2.carbon.connector.ldap.SearchEntry.java

private NamingEnumeration<SearchResult> searchInUserBase(String dn, String searchFilter,
        String[] returningAttributes, int searchScope, DirContext rootContext) throws NamingException {
    String userBase = dn;/*from  w w w .j av  a  2s. c  o  m*/
    SearchControls userSearchControl = new SearchControls();
    userSearchControl.setReturningAttributes(returningAttributes);
    userSearchControl.setSearchScope(searchScope);
    NamingEnumeration<SearchResult> userSearchResults;
    userSearchResults = rootContext.search(userBase, searchFilter, userSearchControl);
    return userSearchResults;

}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public boolean isExistingServiceUid(String uid) throws DirectoryServerManagerException {

    DirContext dirContext;/*w  w  w.j  av  a 2  s. c  o  m*/
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        log.error("Unable to retrieve directory context.", e);
        throw new DirectoryServerManagerException("Unable to retrieve directory context.", e);
    }

    //first search the existing user entry.
    String searchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String filter = "(&(" + LDAPServerManagerConstants.LDAP_UID + "=" + uid + ")"
            + getServerPrincipleIncludeString() + ")";

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_UID });

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, filter,
                searchControls);
        return namingEnumeration.hasMore();

    } catch (NamingException e) {
        log.error("Unable to check whether service exists in directory server. UID - " + uid, e);
        throw new DirectoryServerManagerException("Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}

From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java

public boolean isExistingServicePrinciple(String servicePrinciple) throws DirectoryServerManagerException {

    DirContext dirContext;//from  w w  w. ja  va 2  s.  c o m
    try {
        dirContext = this.connectionSource.getContext();
    } catch (UserStoreException e) {
        log.error("Unable to retrieve directory context.", e);
        throw new DirectoryServerManagerException("Unable to retrieve directory context.", e);
    }

    //first search the existing user entry.
    String searchBase = realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE);

    String filter = getServicePrincipleFilter(servicePrinciple);

    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_UID });

    try {
        NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, filter,
                searchControls);
        return namingEnumeration.hasMore();

    } catch (NamingException e) {
        String message = "Unable to search entry with search base " + searchBase + ", filter -" + filter;
        log.error(message, e);
        throw new DirectoryServerManagerException("Can not access the directory service", e);
    } finally {
        try {
            JNDIUtil.closeContext(dirContext);
        } catch (UserStoreException e) {
            log.error("Unable to close directory context.", e);
        }
    }
}