List of usage examples for javax.naming.directory SearchControls setSearchScope
public void setSearchScope(int scope)
From source file:org.lsc.jndi.JndiServices.java
private SearchResult doGetEntry(final String base, final String filter, final SearchControls sc, final int scope) throws NamingException { //sanity checks String searchBase = base == null ? "" : base; String searchFilter = filter == null ? DEFAULT_FILTER : filter; NamingEnumeration<SearchResult> ne = null; try {/* w ww.ja v a2s . co m*/ sc.setSearchScope(scope); String rewrittenBase = null; if (contextDn != null && searchBase.toLowerCase().endsWith(contextDn.toString().toLowerCase())) { if (!searchBase.equalsIgnoreCase(contextDn.toString())) { rewrittenBase = searchBase.substring(0, searchBase.toLowerCase().lastIndexOf(contextDn.toString().toLowerCase()) - 1); } else { rewrittenBase = ""; } } else { rewrittenBase = searchBase; } ne = ctx.search(rewrittenBase, searchFilter, sc); } catch (NamingException nex) { LOGGER.error("Error while looking for {} in {}: {}", new Object[] { searchFilter, searchBase, nex }); throw nex; } SearchResult sr = null; if (ne.hasMoreElements()) { sr = (SearchResult) ne.nextElement(); if (ne.hasMoreElements()) { LOGGER.error("Too many entries returned (base: \"{}\", filter: \"{}\")", searchBase, searchFilter); throw new SizeLimitExceededException("Too many entries returned (base: \"" + searchBase + "\", filter: \"" + searchFilter + "\")"); } else { return sr; } } else { // try hasMore method to throw exceptions if there are any and we didn't get our entry ne.hasMore(); } return sr; }
From source file:org.lsc.jndi.JndiServices.java
private SearchResult doReadEntry(final String base, final String filter, final boolean allowError, final SearchControls sc) throws NamingException { NamingEnumeration<SearchResult> ne = null; sc.setSearchScope(SearchControls.OBJECT_SCOPE); try {//w ww . j av a 2 s. c o m ne = ctx.search(rewriteBase(base), filter, sc); } catch (NamingException nex) { if (nex instanceof CommunicationException || nex instanceof ServiceUnavailableException) { throw nex; } if (!allowError) { LOGGER.error("Error while reading entry {}: {}", base, nex); LOGGER.debug(nex.toString(), nex); } return null; } SearchResult sr = null; if (ne.hasMore()) { sr = (SearchResult) ne.next(); if (ne.hasMore()) { LOGGER.error("Too many entries returned (base: \"{}\")", base); } else { return sr; } } return sr; }
From source file:org.lsc.jndi.JndiServices.java
private List<String> doGetDnList(final String base, final String filter, final int scope) throws NamingException { NamingEnumeration<SearchResult> ne = null; List<String> iist = new ArrayList<String>(); try {/* w w w. ja v a 2s . c o m*/ SearchControls sc = new SearchControls(); sc.setDerefLinkFlag(false); sc.setReturningAttributes(new String[] { "1.1" }); sc.setSearchScope(scope); sc.setReturningObjFlag(true); ne = ctx.search(base, filter, sc); String completedBaseDn = ""; if (base.length() > 0) { completedBaseDn = "," + base; } while (ne.hasMoreElements()) { iist.add(((SearchResult) ne.next()).getName() + completedBaseDn); } } catch (NamingException e) { LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); throw e; } return iist; }
From source file:org.lsc.jndi.JndiServices.java
private void doDeleteChildrenRecursively(String distinguishName) throws NamingException { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> ne = ctx.search(distinguishName, DEFAULT_FILTER, sc); while (ne.hasMore()) { SearchResult sr = (SearchResult) ne.next(); String childrenDn = rewriteBase(sr.getName() + "," + distinguishName); deleteChildrenRecursively(childrenDn); }/*from w w w .j ava 2 s .co m*/ ctx.destroySubcontext(new LdapName(distinguishName)); }
From source file:org.lsc.jndi.JndiServices.java
/** * Return the LDAP schema.//from w w w.ja va 2s .com * * @param attrsToReturn * list of attribute names to return (or null for all * 'standard' attributes) * @return the map of name => attribute * @throws NamingException * thrown if something goes wrong (bad */ @SuppressWarnings("unchecked") public Map<String, List<String>> getSchema(final String[] attrsToReturn) throws NamingException { Map<String, List<String>> attrsResult = new HashMap<String, List<String>>(); // connect to directory Hashtable<String, String> props = (Hashtable<String, String>) ctx.getEnvironment(); String baseUrl = (String) props.get(Context.PROVIDER_URL); baseUrl = baseUrl.substring(0, baseUrl.lastIndexOf('/')); props.put(Context.PROVIDER_URL, baseUrl); DirContext schemaCtx = new InitialLdapContext(props, null); // find schema entry SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningAttributes(new String[] { "subschemaSubentry" }); NamingEnumeration<SearchResult> schemaDnSR = schemaCtx.search("", "(objectclass=*)", sc); SearchResult sr = null; Attribute subschemaSubentry = null; String subschemaSubentryDN = null; if (schemaDnSR.hasMore()) { sr = schemaDnSR.next(); } if (sr != null) { subschemaSubentry = sr.getAttributes().get("subschemaSubentry"); } if (subschemaSubentry != null && subschemaSubentry.size() > 0) { subschemaSubentryDN = (String) subschemaSubentry.get(); } if (subschemaSubentryDN != null) { // get schema attributes from subschemaSubentryDN Attributes schemaAttrs = schemaCtx.getAttributes(subschemaSubentryDN, attrsToReturn != null ? attrsToReturn : new String[] { "*", "+" }); if (schemaAttrs != null) { for (String attr : attrsToReturn) { Attribute schemaAttr = schemaAttrs.get(attr); if (schemaAttr != null) { attrsResult.put(schemaAttr.getID(), (List<String>) Collections.list(schemaAttr.getAll())); } } } } return attrsResult; }
From source file:org.lsc.jndi.JndiServices.java
/** * Retrieve a specific attribute from an object * // ww w. j av a2s . c o m * @param objectDn * @param attribute * @return * @throws LscServiceException */ public List<String> getAttributeValues(String objectDn, String attribute) throws LscServiceException { List<String> values = null; try { // Setup search SearchControls sc = new SearchControls(); sc.setDerefLinkFlag(false); sc.setReturningAttributes(new String[] { attribute }); sc.setSearchScope(SearchControls.OBJECT_SCOPE); sc.setReturningObjFlag(true); // Retrieve attribute values SearchResult res = getEntry(objectDn, "objectClass=*", sc, SearchControls.OBJECT_SCOPE); Attribute attr = res.getAttributes().get(attribute); if (attr != null) { values = new ArrayList<String>(); NamingEnumeration<?> enu = attr.getAll(); while (enu.hasMoreElements()) { Object val = enu.next(); values.add(val.toString()); } } } catch (NamingException e) { throw new LscServiceException(e); } return values; }
From source file:org.lsc.jndi.JndiServices.java
public Map<String, LscDatasets> doGetAttrsList(final String base, final String filter, final int scope, final List<String> attrsNames) throws NamingException { // sanity checks String searchBase = base == null ? "" : rewriteBase(base); String searchFilter = filter == null ? DEFAULT_FILTER : filter; Map<String, LscDatasets> res = new LinkedHashMap<String, LscDatasets>(); if (attrsNames == null || attrsNames.size() == 0) { LOGGER.error("No attribute names to read! Check configuration."); return res; }/* www.ja v a2 s. c o m*/ String[] attributes = new String[attrsNames.size()]; attributes = attrsNames.toArray(attributes); SearchControls constraints = new SearchControls(); constraints.setDerefLinkFlag(false); constraints.setReturningAttributes(attributes); constraints.setSearchScope(scope); constraints.setReturningObjFlag(true); try { boolean requestPagedResults = false; List<Control> extControls = new ArrayList<Control>(); if (pageSize > 0) { requestPagedResults = true; LOGGER.debug("Using pagedResults control for {} entries at a time", pageSize); } if (requestPagedResults) { extControls.add(new PagedResultsControl(pageSize, Control.CRITICAL)); } if (sortedBy != null) { extControls.add(new SortControl(sortedBy, Control.CRITICAL)); } if (extControls.size() > 0) { ctx.setRequestControls(extControls.toArray(new Control[extControls.size()])); } byte[] pagedResultsResponse = null; do { NamingEnumeration<SearchResult> results = ctx.search(searchBase, searchFilter, constraints); if (results != null) { Map<String, Object> attrsValues = null; while (results.hasMoreElements()) { attrsValues = new HashMap<String, Object>(); SearchResult ldapResult = (SearchResult) results.next(); // get the value for each attribute requested for (String attributeName : attrsNames) { Attribute attr = ldapResult.getAttributes().get(attributeName); if (attr != null && attr.get() != null) { attrsValues.put(attributeName, attr.get()); } } res.put(ldapResult.getNameInNamespace(), new LscDatasets(attrsValues)); } } Control[] respCtls = ctx.getResponseControls(); if (respCtls != null) { for (Control respCtl : respCtls) { if (requestPagedResults && respCtl instanceof PagedResultsResponseControl) { pagedResultsResponse = ((PagedResultsResponseControl) respCtl).getCookie(); } } } if (requestPagedResults && pagedResultsResponse != null) { ctx.setRequestControls(new Control[] { new PagedResultsControl(pageSize, pagedResultsResponse, Control.CRITICAL) }); } } while (pagedResultsResponse != null); // clear requestControls for future use of the JNDI context if (requestPagedResults) { ctx.setRequestControls(null); } } catch (CommunicationException e) { // Avoid handling the communication exception as a generic one throw e; } catch (ServiceUnavailableException e) { // Avoid handling the service unavailable exception as a generic one throw e; } catch (NamingException e) { // clear requestControls for future use of the JNDI context ctx.setRequestControls(null); LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); } catch (IOException e) { // clear requestControls for future use of the JNDI context ctx.setRequestControls(null); LOGGER.error(e.toString()); LOGGER.debug(e.toString(), e); } return res; }
From source file:org.nuxeo.ecm.directory.ldap.ExternalLDAPDirectoryFeature.java
protected void destroyRecursively(String dn, DirContext ctx, int limit) throws NamingException { if (limit == 0) { log.warn("Reach recursion limit, stopping deletion at" + dn); return;//from ww w .j a va 2s . co m } SearchControls scts = new SearchControls(); scts.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> children = ctx.search(dn, "(objectClass=*)", scts); try { while (children.hasMore()) { SearchResult child = children.next(); String subDn = child.getName(); subDn = subDn + ',' + dn; destroyRecursively(subDn, ctx, limit); } } catch (SizeLimitExceededException e) { log.warn("SizeLimitExceededException: trying again on partial results " + dn); if (limit == -1) { limit = 100; } destroyRecursively(dn, ctx, limit - 1); } ctx.destroySubcontext(dn); }
From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectory.java
/** * Search controls that only fetch attributes defined by the schema * * @return common search controls to use for all LDAP search queries * @throws DirectoryException//w w w . j a va 2 s . com */ protected SearchControls computeSearchControls() throws DirectoryException { LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor(); SearchControls scts = new SearchControls(); // respect the scope of the configuration scts.setSearchScope(ldapDirectoryDesc.getSearchScope()); // only fetch attributes that are defined in the schema or needed to // compute LDAPReferences Set<String> attrs = new HashSet<>(); for (String fieldName : schemaFieldMap.keySet()) { if (!references.containsKey(fieldName)) { attrs.add(fieldMapper.getBackendField(fieldName)); } } attrs.add("objectClass"); for (Reference reference : getReferences()) { if (reference instanceof LDAPReference) { LDAPReference ldapReference = (LDAPReference) reference; attrs.add(ldapReference.getStaticAttributeId(fieldMapper)); attrs.add(ldapReference.getDynamicAttributeId()); // Add Dynamic Reference attributes filtering for (LDAPDynamicReferenceDescriptor dynAtt : ldapReference.getDynamicAttributes()) { attrs.add(dynAtt.baseDN); attrs.add(dynAtt.filter); } } } if (getPasswordField() != null) { // never try to fetch the password attrs.remove(getPasswordField()); } scts.setReturningAttributes(attrs.toArray(new String[attrs.size()])); scts.setCountLimit(ldapDirectoryDesc.getQuerySizeLimit()); scts.setTimeLimit(ldapDirectoryDesc.getQueryTimeLimit()); return scts; }
From source file:org.nuxeo.ecm.directory.ldap.LDAPDirectory.java
public SearchControls getSearchControls(boolean fetchAllAttributes) { if (fetchAllAttributes) { // return the precomputed scts instance return searchControls; } else {// w w w . ja v a 2s .co m // build a new ftcs instance with no attribute filtering LDAPDirectoryDescriptor ldapDirectoryDesc = getDescriptor(); SearchControls scts = new SearchControls(); scts.setSearchScope(ldapDirectoryDesc.getSearchScope()); scts.setReturningAttributes(new String[] { ldapDirectoryDesc.rdnAttribute, ldapDirectoryDesc.fieldMapping.get(getIdField()) }); return scts; } }