List of usage examples for javax.naming.directory SearchControls OBJECT_SCOPE
int OBJECT_SCOPE
To view the source code for javax.naming.directory SearchControls OBJECT_SCOPE.
Click Source Link
From source file:org.hyperic.hq.plugin.openldap.OpenLDAPMeasurementPlugin.java
/** * @return true = monitoring is enabled * @return false = monitoring is not enabled * @exception NamingException no conection *//*from www .j a va 2s .c o m*/ private boolean hasMonitoringEnabled(Metric metric) throws NamingException { NamingEnumeration enumer = null, enumerx = null, enumery = null; boolean res = false; try { String[] a = { "monitorContext" }; SearchControls cons = new SearchControls(); cons.setSearchScope(SearchControls.OBJECT_SCOPE); cons.setReturningAttributes(a); enumer = getDirContext(metric.getProperties()).search("", "(&(objectClass=*))", cons); while (enumer.hasMore() && !res) { SearchResult searchresult = (SearchResult) enumer.next(); Attributes attrs = searchresult.getAttributes(); enumerx = attrs.getIDs(); while (enumerx.hasMore()) { String id = (String) enumerx.next(); Attribute attr = attrs.get(id); res = true; } } } finally { if (enumer != null) { enumer.close(); } if (enumerx != null) { enumerx.close(); } if (enumery != null) { enumery.close(); } } log.debug("[hasMonitoringEnabled] res=" + res + " metric:" + metric); return res; }
From source file:org.jasig.portal.security.provider.SimpleLdapSecurityContext.java
/** * Authenticates the user.//from w ww. j a v a2 s. com */ public synchronized void authenticate() throws PortalSecurityException { this.isauth = false; ILdapServer ldapConn; String propFile = ctxProperties.getProperty(LDAP_PROPERTIES_CONNECTION_NAME); if (propFile != null && propFile.length() > 0) ldapConn = LdapServices.getLdapServer(propFile); else ldapConn = LdapServices.getDefaultLdapServer(); String creds = new String(this.myOpaqueCredentials.credentialstring); if (this.myPrincipal.UID != null && !this.myPrincipal.UID.trim().equals("") && this.myOpaqueCredentials.credentialstring != null && !creds.trim().equals("")) { DirContext conn = null; NamingEnumeration results = null; StringBuffer user = new StringBuffer("("); String first_name = null; String last_name = null; user.append(ldapConn.getUidAttribute()).append("="); user.append(this.myPrincipal.UID).append(")"); if (log.isDebugEnabled()) log.debug("SimpleLdapSecurityContext: Looking for " + user.toString()); try { conn = ldapConn.getConnection(); // set up search controls SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(attributes); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // do lookup if (conn != null) { try { results = conn.search(ldapConn.getBaseDN(), user.toString(), searchCtls); if (results != null) { if (!results.hasMore()) log.error("SimpleLdapSecurityContext: user not found , " + this.myPrincipal.UID); while (results != null && results.hasMore()) { SearchResult entry = (SearchResult) results.next(); StringBuffer dnBuffer = new StringBuffer(); dnBuffer.append(entry.getName()).append(", "); dnBuffer.append(ldapConn.getBaseDN()); Attributes attrs = entry.getAttributes(); first_name = getAttributeValue(attrs, ATTR_FIRSTNAME); last_name = getAttributeValue(attrs, ATTR_LASTNAME); // re-bind as user conn.removeFromEnvironment(javax.naming.Context.SECURITY_PRINCIPAL); conn.removeFromEnvironment(javax.naming.Context.SECURITY_CREDENTIALS); conn.addToEnvironment(javax.naming.Context.SECURITY_PRINCIPAL, dnBuffer.toString()); conn.addToEnvironment(javax.naming.Context.SECURITY_CREDENTIALS, this.myOpaqueCredentials.credentialstring); searchCtls = new SearchControls(); searchCtls.setReturningAttributes(new String[0]); searchCtls.setSearchScope(SearchControls.OBJECT_SCOPE); String attrSearch = "(" + ldapConn.getUidAttribute() + "=*)"; log.debug("SimpleLdapSecurityContext: Looking in " + dnBuffer.toString() + " for " + attrSearch); conn.search(dnBuffer.toString(), attrSearch, searchCtls); this.isauth = true; this.myPrincipal.FullName = first_name + " " + last_name; log.debug("SimpleLdapSecurityContext: User " + this.myPrincipal.UID + " (" + this.myPrincipal.FullName + ") is authenticated"); // Since LDAP is case-insensitive with respect to uid, force // user name to lower case for use by the portal this.myPrincipal.UID = this.myPrincipal.UID.toLowerCase(); } // while (results != null && results.hasMore()) } else { log.error("SimpleLdapSecurityContext: No such user: " + this.myPrincipal.UID); } } catch (AuthenticationException ae) { log.info("SimpleLdapSecurityContext: Password invalid for user: " + this.myPrincipal.UID); } catch (Exception e) { log.error("SimpleLdapSecurityContext: LDAP Error with user: " + this.myPrincipal.UID + "; ", e); throw new PortalSecurityException("SimpleLdapSecurityContext: LDAP Error" + e + " with user: " + this.myPrincipal.UID); } finally { ldapConn.releaseConnection(conn); } } else { log.error("LDAP Server Connection unavalable"); } } catch (final NamingException ne) { log.error("Error geting connection to LDAP server.", ne); } } else { log.error("Principal or OpaqueCredentials not initialized prior to authenticate"); } // Ok...we are now ready to authenticate all of our subcontexts. super.authenticate(); return; }
From source file:org.lsc.jndi.FullDNJndiDstService.java
/** * The simple object getter according to its identifier. * // w ww . j av a 2 s . co m * @param dn DN of the entry to be returned, which is the name returned by {@link #getListPivots()} * @param pivotAttributes Unused. * @param fromSameService are the pivot attributes provided by the same service * @return The bean, or null if not found * @throws LscServiceException May throw a {@link NamingException} if the object is not found in the * directory, or if more than one object would be returned. */ public IBean getBean(String dn, LscDatasets pivotAttributes, boolean fromSameService) throws LscServiceException { try { SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.OBJECT_SCOPE); List<String> attrs = getAttrs(); if (attrs != null) { sc.setReturningAttributes(attrs.toArray(new String[attrs.size()])); } SearchResult srObject = getJndiServices().readEntry(dn, getFilterId(), true, sc); Method method = beanClass.getMethod("getInstance", new Class[] { SearchResult.class, String.class, Class.class }); return (IBean) method.invoke(null, new Object[] { srObject, jndiServices.completeDn(dn), beanClass }); } catch (SecurityException e) { LOGGER.error( "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})", beanClass.getName(), e); LOGGER.debug(e.toString(), e); } catch (NoSuchMethodException e) { LOGGER.error( "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})", beanClass.getName(), e); LOGGER.debug(e.toString(), e); } catch (IllegalArgumentException e) { LOGGER.error( "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})", beanClass.getName(), e); LOGGER.debug(e.toString(), e); } catch (IllegalAccessException e) { LOGGER.error( "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})", beanClass.getName(), e); LOGGER.debug(e.toString(), e); } catch (InvocationTargetException e) { LOGGER.error( "Unable to get static method getInstance on {} ! This is probably a programmer's error ({})", beanClass.getName(), e); LOGGER.debug(e.toString(), e); } catch (NamingException e) { LOGGER.error("JNDI error while synchronizing {}: {} ", beanClass.getName(), e); LOGGER.debug(e.toString(), e); throw new LscServiceException(e.toString(), e); } return null; }
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 {// ww w. j a v 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
/** * Return the LDAP schema.//from w w w . jav a 2s . c o m * * @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 * /*from w w w . j a v a 2 s . co 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.nuxeo.ecm.directory.ldap.LDAPTreeReference.java
/** * Fetches single parent, cutting the dn and trying to get the given entry. * * @see org.nuxeo.ecm.directory.Reference#getSourceIdsForTarget(String) *//* w w w . j ava 2s . c o m*/ @Override public List<String> getSourceIdsForTarget(String targetId) throws DirectoryException { Set<String> sourceIds = new TreeSet<>(); String targetDn = null; // step #1: fetch the dn of the targetId entry in the target // directory by the static dn valued strategy LDAPDirectory targetDir = getTargetLDAPDirectory(); try (LDAPSession targetSession = (LDAPSession) targetDir.getSession()) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId, true); if (targetLdapEntry == null) { // no parent accessible => return empty list return EMPTY_STRING_LIST; } targetDn = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } catch (NamingException e) { throw new DirectoryException("error fetching " + targetId, e); } // step #2: search for entries that reference parent dn in the // source directory and collect its id LDAPDirectory ldapSourceDirectory = getSourceLDAPDirectory(); String parentDn = getParentDn(targetDn); String filterExpr = String.format("(&%s)", ldapSourceDirectory.getBaseFilter()); String[] filterArgs = {}; // get a copy of original search controls SearchControls sctls = ldapSourceDirectory.getSearchControls(true); sctls.setSearchScope(SearchControls.OBJECT_SCOPE); try (LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.getSourceIdsForTarget(%s): LDAP search search base='%s'" + " filter='%s' args='%s' scope='%s' [%s]", targetId, parentDn, filterExpr, StringUtils.join(filterArgs, ", "), sctls.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext.search(parentDn, filterExpr, filterArgs, sctls); try { while (results.hasMore()) { Attributes attributes = results.next().getAttributes(); // NXP-2461: check that id field is filled Attribute attr = attributes.get(sourceSession.idAttribute); if (attr != null) { Object value = attr.get(); if (value != null) { sourceIds.add(value.toString()); // only supposed to get one result anyway break; } } } } finally { results.close(); } } catch (NamingException e) { throw new DirectoryException("error during reference search for " + targetDn, e); } return new ArrayList<>(sourceIds); }
From source file:org.olat.ldap.LDAPLoginManagerImpl.java
private boolean isPagedResultControlSupported(final LdapContext ctx) { try {/*from w ww. j ava 2 s . c o m*/ final SearchControls ctl = new SearchControls(); ctl.setReturningAttributes(new String[] { "supportedControl" }); ctl.setSearchScope(SearchControls.OBJECT_SCOPE); /* search for the rootDSE object */ final NamingEnumeration<SearchResult> results = ctx.search("", "(objectClass=*)", ctl); while (results.hasMore()) { final SearchResult entry = results.next(); final NamingEnumeration<? extends Attribute> attrs = entry.getAttributes().getAll(); while (attrs.hasMore()) { final Attribute attr = attrs.next(); final NamingEnumeration<?> vals = attr.getAll(); while (vals.hasMore()) { final String value = (String) vals.next(); if (value.equals(PAGED_RESULT_CONTROL_OID)) { return true; } } } } return false; } catch (final Exception e) { logError("Exception when trying to know if the server support paged results.", e); return false; } }
From source file:org.orbeon.oxf.processor.LDAPProcessor.java
private int convertSearchScope(String scope) { if (scope != null && scope.toUpperCase().equals("SUBTREE")) { return SearchControls.SUBTREE_SCOPE; } else if (scope != null && scope.toUpperCase().equals("OBJECT")) { return SearchControls.OBJECT_SCOPE; } else if (scope != null && (scope.toUpperCase().equals("ALLLEVELS") || scope.toUpperCase().equals("ONELEVEL"))) { return SearchControls.ONELEVEL_SCOPE; } else {// w w w . ja v a2 s . c om return SearchControls.SUBTREE_SCOPE; } }
From source file:org.sipfoundry.sipxconfig.bulk.ldap.LdapManagerImpl.java
public Schema getSchema(String subschemaSubentry, LdapConnectionParams params) { try {/* w w w . ja v a 2s. com*/ SearchControls cons = new SearchControls(); // only interested in the first result cons.setCountLimit(1); // set time limit for this search to 30 sec, should be sufficient even for large LDAPs cons.setTimeLimit(30000); SchemaMapper mapper = new SchemaMapper(); cons.setReturningAttributes(mapper.getReturningAttributes()); cons.setSearchScope(SearchControls.OBJECT_SCOPE); Schema schema = (Schema) m_templateFactory.getLdapTemplate(params).search(subschemaSubentry, LdapManager.FILTER_ALL_CLASSES, cons, new SchemaMapper(), LdapManager.NULL_PROCESSOR).get(0); return schema; } catch (DataIntegrityViolationException e) { LOG.debug("Retrieving schema failed.", e); throw new UserException("searchSchema.violation.error"); } catch (UncategorizedLdapException e) { LOG.debug("Retrieving schema failed. Anonymous-binding may be disabled", e); throw new UserException("searchSchema.anonymousBinding.error"); } }