List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:org.nuxeo.ecm.directory.ldap.LDAPReference.java
/** * Remove existing statically defined links for the given target id (dynamic references remain unaltered) * * @see org.nuxeo.ecm.directory.Reference#removeLinksForTarget(String) *//*from www. j ava 2 s. c o m*/ @Override public void removeLinksForTarget(String targetId) throws DirectoryException { if (!isStatic()) { // nothing to do: dynamic references cannot be updated return; } LDAPDirectory ldapTargetDirectory = (LDAPDirectory) getTargetDirectory(); LDAPDirectory ldapSourceDirectory = (LDAPDirectory) getSourceDirectory(); String attributeId = getStaticAttributeId(); try (LDAPSession targetSession = (LDAPSession) ldapTargetDirectory.getSession(); LDAPSession sourceSession = (LDAPSession) ldapSourceDirectory.getSession()) { if (!sourceSession.isReadOnly()) { // get the dn of the target that matches targetId String targetAttributeValue; if (staticAttributeIdIsDn) { SearchResult targetLdapEntry = targetSession.getLdapEntry(targetId); if (targetLdapEntry == null) { String rdnAttribute = ldapTargetDirectory.getDescriptor().getRdnAttribute(); if (!rdnAttribute.equals(targetSession.idAttribute)) { log.warn(String.format( "cannot remove links to missing entry %s in directory %s for reference %s", targetId, ldapTargetDirectory.getName(), this)); return; } // the entry might have already been deleted, try to // re-forge it if possible (might not work if scope is // subtree) targetAttributeValue = String.format("%s=%s,%s", rdnAttribute, targetId, ldapTargetDirectory.getDescriptor().getSearchBaseDn()); } else { targetAttributeValue = pseudoNormalizeDn(targetLdapEntry.getNameInNamespace()); } } else { targetAttributeValue = targetId; } // build a LDAP query to find entries that point to the target String searchFilter = String.format("(%s=%s)", attributeId, targetAttributeValue); String sourceFilter = ldapSourceDirectory.getBaseFilter(); if (sourceFilter != null && !"".equals(sourceFilter)) { searchFilter = String.format("(&(%s)(%s))", searchFilter, sourceFilter); } SearchControls scts = new SearchControls(); scts.setSearchScope(ldapSourceDirectory.getDescriptor().getSearchScope()); scts.setReturningAttributes(new String[] { attributeId }); // find all source entries that point to the target key and // clean // those references if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP search baseDn='%s' " + " filter='%s' scope='%s' [%s]", targetId, sourceSession.searchBaseDn, searchFilter, scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results = sourceSession.dirContext .search(sourceSession.searchBaseDn, searchFilter, scts); String emptyRefMarker = ldapSourceDirectory.getDescriptor().getEmptyRefMarker(); Attributes emptyAttribute = new BasicAttributes(attributeId, emptyRefMarker); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); Attribute attr = attrs.get(attributeId); try { if (attr.size() == 1) { // the attribute holds the last reference, put // the // empty ref. marker before removing the // attribute // since empty attribute are often not allowed // by // the server schema if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='ADD_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.ADD_ATTRIBUTE, emptyAttribute); } // remove the reference to the target key attrs = new BasicAttributes(); attr = new BasicAttribute(attributeId); attr.add(targetAttributeValue); attrs.put(attr); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPReference.removeLinksForTarget(%s): LDAP modifyAttributes key='%s' " + "mod_op='REMOVE_ATTRIBUTE' attrs='%s' [%s]", targetId, result.getNameInNamespace(), attrs, this)); } sourceSession.dirContext.modifyAttributes(result.getNameInNamespace(), DirContext.REMOVE_ATTRIBUTE, attrs); } catch (SchemaViolationException e) { if (isDynamic()) { // we are editing an entry that has no static // part log.warn(String.format("cannot remove dynamic reference in field %s for target %s", getFieldName(), targetId)); } else { // this is a real schema configuration problem, // wrapup the exception throw new DirectoryException(e); } } } } finally { results.close(); } } } catch (NamingException e) { throw new DirectoryException("removeLinksForTarget failed: " + e.getMessage(), e); } }
From source file:org.springframework.ldap.core.LdapTemplate.java
/** * Perform a search operation, such as a search(), list() or listBindings(). * This method handles all the plumbing; getting a readonly context; looping * through the NamingEnumeration and closing the context and enumeration. It * also calls the supplied DirContextProcessor before and after the search, * respectively. This enables custom pre-processing and post-processing, * like for example when handling paged results or other search controls. * <p>//from ww w .ja va 2s . c om * The actual list is delegated to the {@link SearchExecutor} and each * {@link NameClassPair} (this might be a NameClassPair or a subclass * thereof) is passed to the CallbackHandler. Any encountered * NamingException will be translated using the NamingExceptionTranslator. * * @param se the SearchExecutor to use for performing the actual list. * @param handler the NameClassPairCallbackHandler to which each found entry * will be passed. * @param processor DirContextProcessor for custom pre- and post-processing. * Must not be <code>null</code>. If no custom processing should take place, * please use e.g. * {@link #search(SearchExecutor, NameClassPairCallbackHandler)}. * @throws NamingException if any error occurs. Note that a * NameNotFoundException will be ignored. Instead this is interpreted that * no entries were found. */ public void search(SearchExecutor se, NameClassPairCallbackHandler handler, DirContextProcessor processor) { DirContext ctx = contextSource.getReadOnlyContext(); NamingEnumeration results = null; RuntimeException ex = null; try { processor.preProcess(ctx); results = se.executeSearch(ctx); while (results.hasMore()) { NameClassPair result = (NameClassPair) results.next(); handler.handleNameClassPair(result); } } catch (NameNotFoundException e) { // It is possible to ignore errors caused by base not found if (ignoreNameNotFoundException) { log.warn("Base context not found, ignoring: " + e.getMessage()); } else { ex = LdapUtils.convertLdapException(e); } } catch (PartialResultException e) { // Workaround for AD servers not handling referrals correctly. if (ignorePartialResultException) { log.debug("PartialResultException encountered and ignored", e); } else { ex = LdapUtils.convertLdapException(e); } } catch (javax.naming.NamingException e) { ex = LdapUtils.convertLdapException(e); } finally { try { processor.postProcess(ctx); } catch (javax.naming.NamingException e) { if (ex == null) { ex = LdapUtils.convertLdapException(e); } else { // We already had an exception from above and should ignore // this one. log.debug("Ignoring Exception from postProcess, " + "main exception thrown instead", e); } } closeContextAndNamingEnumeration(ctx, results); // If we got an exception it should be thrown. if (ex != null) { throw ex; } } }
From source file:org.josso.gateway.identity.service.store.ldap.LDAPIdentityStore.java
/** * Get user UID attribute for the given certificate. * * @param lookupValue value used for credentials lookup * @param certificate user certificate//from w w w.j a va 2 s. c om * @param cp credential provider * @return user UID * @throws NamingException LDAP error obtaining user UID. * @throws IOException */ protected String loadUID(String lookupValue, X509Certificate certificate, CredentialProvider cp) throws NamingException, IOException { String uidValue = null; InitialLdapContext ctx = createLdapInitialContext(false); StartTlsResponse tls = null; if (getEnableStartTls()) { tls = startTls(ctx); } String schemeName = null; if (cp instanceof AuthenticationScheme) { schemeName = ((AuthenticationScheme) cp).getName(); } String principalLookupAttrName = this.getPrincipalLookupAttributeID(); if (principalLookupAttrName == null || principalLookupAttrName.trim().equals("") || !"strong-authentication".equals(schemeName)) { principalLookupAttrName = this.getPrincipalUidAttributeID(); } String principalUidAttrName = this.getPrincipalUidAttributeID(); String certificateAttrName = this.getUserCertificateAtrributeID(); String usersCtxDN = this.getUsersCtxDN(); try { // NamingEnumeration answer = ctx.search(usersCtxDN, matchAttrs, principalAttr); // This gives more control over search behavior : NamingEnumeration answer = ctx.search(usersCtxDN, "(&(" + principalLookupAttrName + "={0})(" + certificateAttrName + "={1}))", new Object[] { lookupValue, certificate.getEncoded() }, getSearchControls()); while (answer.hasMore()) { SearchResult sr = (SearchResult) answer.next(); Attributes attrs = sr.getAttributes(); Attribute uidAttr = attrs.get(principalUidAttrName); if (uidAttr == null) { logger.warn("Invalid user uid attribute '" + principalUidAttrName + "'"); continue; } uidValue = uidAttr.get().toString(); if (uidValue != null) { if (logger.isDebugEnabled()) logger.debug("Found user " + principalUidAttrName + "=" + uidValue); } else { if (logger.isDebugEnabled()) logger.debug("User not found for certificate '" + certificate.getSubjectX500Principal().getName() + "'"); } } } catch (NamingException e) { if (logger.isDebugEnabled()) logger.debug("Failed to locate user", e); } catch (CertificateEncodingException e) { if (logger.isDebugEnabled()) logger.debug("Certificate encoding exception", e); } finally { // Close the context to release the connection if (tls != null) { tls.close(); } ctx.close(); } return uidValue; }
From source file:com.adito.ldap.LdapUserDatabase.java
/** * (non-Javadoc)/*from w ww . j av a2 s. com*/ * * @see com.adito.security.DefaultUserDatabase#deleteRole(java.lang.String) */ public void deleteRole(String rolename) throws Exception { if (!supportsAccountCreation()) { throw new UnsupportedOperationException("User database is read-only"); } LdapTemplate ldapTemplate = new LdapTemplate(); ldapTemplate.setContextSource(ldapContextSource); String dn = ((LdapGroup) getRole(rolename)).getDn(); int ind = dn.indexOf(baseDn); String rdn = dn.substring(0, ind - 1); //take the name of user'member of this group NamingEnumeration e = (NamingEnumeration) ldapTemplate.lookup(rdn, new AttributesMapper() { public Object mapFromAttributes(Attributes attrs) throws NamingException { return attrs.get(MEMBER_ATTRIBUTE).getAll(); } }); //delete the group in database ldapTemplate.unbind(rdn); groupContainer.removeGroup((LdapGroup) getRole(rolename)); // delete the group in Ldapuser for (; e.hasMore();) { LdapUser u = getAccountFromDN(e.next().toString()); u.setRoles(getGroupsForUser(u.getDn())); userContainer.storePrincipal(u); } }
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 {/*from ww w .j ava 2 s .c om*/ 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.nuxeo.ecm.directory.ldap.LDAPSession.java
protected SearchResult getLdapEntry(String id, boolean fetchAllAttributes) throws NamingException { if (StringUtils.isEmpty(id)) { log.warn(//w ww . j a v a2 s. co m "The application should not " + "query for entries with an empty id " + "=> return no results"); return null; } String filterExpr; String baseFilter = getDirectory().getBaseFilter(); if (baseFilter.startsWith("(")) { filterExpr = String.format("(&(%s={0})%s)", idAttribute, baseFilter); } else { filterExpr = String.format("(&(%s={0})(%s))", idAttribute, baseFilter); } String[] filterArgs = { id }; SearchControls scts = getDirectory().getSearchControls(fetchAllAttributes); if (log.isDebugEnabled()) { log.debug(String.format( "LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' " + " args='%s' scope='%s' [%s]", id, fetchAllAttributes, searchBaseDn, filterExpr, id, scts.getSearchScope(), this)); } NamingEnumeration<SearchResult> results; try { results = dirContext.search(searchBaseDn, filterExpr, filterArgs, scts); } catch (NameNotFoundException nnfe) { // sometimes ActiveDirectory have some query fail with: LDAP: // error code 32 - 0000208D: NameErr: DSID-031522C9, problem // 2001 (NO_OBJECT). // To keep the application usable return no results instead of // crashing but log the error so that the AD admin // can fix the issue. log.error("Unexpected response from server while performing query: " + nnfe.getMessage(), nnfe); return null; } if (!results.hasMore()) { log.debug("Entry not found: " + id); return null; } SearchResult result = results.next(); try { String dn = result.getNameInNamespace(); if (results.hasMore()) { result = results.next(); String dn2 = result.getNameInNamespace(); String msg = String.format("Unable to fetch entry for '%s': found more than one match," + " for instance: '%s' and '%s'", id, dn, dn2); log.error(msg); // ignore entries that are ambiguous while giving enough info // in the logs to let the LDAP admin be able to fix the issue return null; } if (log.isDebugEnabled()) { log.debug(String.format( "LDAPSession.getLdapEntry(%s, %s): LDAP search base='%s' filter='%s' " + " args='%s' scope='%s' => found: %s [%s]", id, fetchAllAttributes, searchBaseDn, filterExpr, id, scts.getSearchScope(), dn, this)); } } catch (UnsupportedOperationException e) { // ignore unsupported operation thrown by the Apache DS server in // the tests in embedded mode } return result; }
From source file:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * * @param callback//from w w w . j a va2s . co m * the callback * @param searchBase * the base DN for the search * @param query * the query * @param returningAttributes * the attributes to include in search results * @throws org.alfresco.error.AlfrescoRuntimeException */ private void processQuery(SearchCallback callback, String searchBase, String query, String[] returningAttributes) { SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(returningAttributes); if (LDAPMultiBaseUserRegistry.logger.isDebugEnabled()) { LDAPMultiBaseUserRegistry.logger.debug("Processing query"); LDAPMultiBaseUserRegistry.logger.debug("Search base: " + searchBase); LDAPMultiBaseUserRegistry.logger.debug(" Return result limit: " + searchControls.getCountLimit()); LDAPMultiBaseUserRegistry.logger.debug(" DerefLink: " + searchControls.getDerefLinkFlag()); LDAPMultiBaseUserRegistry.logger .debug(" Return named object: " + searchControls.getReturningObjFlag()); LDAPMultiBaseUserRegistry.logger.debug(" Time limit for search: " + searchControls.getTimeLimit()); LDAPMultiBaseUserRegistry.logger .debug(" Attributes to return: " + returningAttributes.length + " items."); for (String ra : returningAttributes) { LDAPMultiBaseUserRegistry.logger.debug(" Attribute: " + ra); } } InitialDirContext ctx = null; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(this.queryBatchSize); do { searchResults = ctx.search(searchBase, query, searchControls); while (searchResults.hasMore()) { result = searchResults.next(); callback.process(result); // Close the contexts, see ALF-20682 Context resultCtx = (Context) result.getObject(); if (resultCtx != null) { resultCtx.close(); } result = null; } } while (this.ldapInitialContextFactory.hasNextPage(ctx, this.queryBatchSize)); } catch (NamingException e) { Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } catch (ParseException e) { Object[] params = { e.getLocalizedMessage() }; throw new AlfrescoRuntimeException("synchronization.err.ldap.search", params, e); } finally { if (result != null) { try { Context resultCtx = (Context) result.getObject(); if (resultCtx != null) { resultCtx.close(); } } catch (Exception e) { logger.debug("error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (Exception e) { logger.debug("error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { } } } }
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 w w . j av a2 s . c om 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:com.jsmartframework.web.manager.BeanHandler.java
private void lookupInContext(Context context, String prefix) { try {/*from w w w. j a va 2 s . co m*/ prefix += "/"; NamingEnumeration<Binding> bindList = context.listBindings(""); while (bindList.hasMore()) { Binding bind = bindList.next(); if (bind != null) { if (bind.getObject() instanceof Context) { lookupInContext((Context) bind.getObject(), prefix + bind.getName()); } String[] binds = bind.getName().split("!"); if (binds.length > 1) { try { jndiMapping.put(Class.forName(binds[1]), prefix + binds[0]); } catch (Throwable ex) { LOGGER.log(Level.WARNING, "Class could not be found for EJB mapping: " + ex.getMessage()); } } } } } catch (Throwable ex) { LOGGER.log(Level.WARNING, "Bindings could not be found for EJB context: " + ex.getMessage()); } }
From source file:com.jsmartframework.web.manager.BeanHandler.java
private void initJndiMapping() { try {/*from ww w. j a va 2 s. c om*/ String lookupName = CONFIG.getContent().getEjbLookup(); initialContext = new InitialContext(); // For glassfish implementation NamingEnumeration<Binding> bindList = initialContext.listBindings(""); while (bindList.hasMore()) { Binding bind = bindList.next(); if (bind != null && ("java:" + lookupName).equals(bind.getName()) && bind.getObject() instanceof Context) { lookupInContext((Context) bind.getObject(), "java:" + lookupName); } } // For Jboss implementation if (jndiMapping.isEmpty()) { lookupInContext((Context) initialContext.lookup("java:" + lookupName), "java:" + lookupName); } } catch (Exception ex) { LOGGER.log(Level.WARNING, "JNDI for EJB mapping could not be initialized: " + ex.getMessage()); } }