List of usage examples for javax.naming.directory InitialDirContext close
public void close() throws NamingException
From source file:org.apache.archiva.redback.rest.services.LdapGroupMappingServiceTest.java
@Override public void stopServer() throws Exception { // cleanup ldap entries InitialDirContext context = apacheDs.getAdminContext(); for (String group : this.groups) { context.unbind(createGroupDn(group)); }//ww w . ja v a2 s.c o m context.unbind(suffix); context.close(); apacheDs.stopServer(); super.stopServer(); }
From source file:org.apache.archiva.redback.common.ldap.role.TestLdapRoleMapper.java
@After public void tearDown() throws Exception { // clear cache //ldapCacheService.removeAllUsers(); InitialDirContext context = apacheDs.getAdminContext(); for (String uid : users) { context.unbind(createDn(uid));/* w w w. j a v a2s .c o m*/ } for (Map.Entry<String, List<String>> group : usersPerGroup.entrySet()) { context.unbind(createGroupDn(group.getKey())); } context.unbind(suffix); context.close(); ldapConnection.close(); apacheDs.stopServer(); super.tearDown(); }
From source file:de.acosix.alfresco.mtsupport.repo.auth.ldap.EnhancedLDAPUserRegistry.java
protected void commonAfterQueryCleanup(final NamingEnumeration<SearchResult> searchResults, final SearchResult result, final InitialDirContext ctx) { if (result != null) { try {/*from w ww.j av a 2 s . c o m*/ this.commonCloseSearchResult(result); } catch (final NamingException e) { LOGGER.debug("Error when closing result block context", e); } } if (searchResults != null) { try { searchResults.close(); } catch (final NamingException e) { LOGGER.debug("Error when closing searchResults context", e); } } if (ctx != null) { try { ctx.close(); } catch (final NamingException e) { LOGGER.debug("Error when closing ldap context", e); } } }
From source file:com.clustercontrol.port.protocol.ReachAddressDNS.java
/** * DNS????????/*from w ww . j a v a2 s . com*/ * * @param addressText * @return DNS */ /* * (non-Javadoc) * * @see * com.clustercontrol.port.protocol.ReachAddressProtocol#isRunning(java. * lang.String) */ @Override protected boolean isRunning(String addressText) { m_message = ""; m_messageOrg = ""; m_response = -1; boolean isReachable = false; try { long start = 0; // long end = 0; // boolean retry = true; // ????(true:??false:???) StringBuffer bufferOrg = new StringBuffer(); // String result = ""; InetAddress address = InetAddress.getByName(addressText); String addressStr = address.getHostAddress(); if (address instanceof Inet6Address) { addressStr = "[" + addressStr + "]"; } bufferOrg.append("Monitoring the DNS Service of " + address.getHostName() + "[" + address.getHostAddress() + "]:" + m_portNo + ".\n\n"); Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); props.put(Context.PROVIDER_URL, "dns://" + addressStr + ":" + m_portNo); props.put("com.sun.jndi.dns.timeout.initial", String.valueOf(m_timeout)); props.put("com.sun.jndi.dns.timeout.retries", "1"); InitialDirContext idctx = null; String hostname = HinemosPropertyUtil.getHinemosPropertyStr("monitor.port.protocol.dns", "localhost"); m_log.debug("The hostname from which to retrieve attributes is " + hostname); for (int i = 0; i < m_sentCount && retry; i++) { try { bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: "); start = HinemosTime.currentTimeMillis(); idctx = new InitialDirContext(props); Attributes attrs = idctx.getAttributes(hostname); end = HinemosTime.currentTimeMillis(); bufferOrg.append("\n"); NamingEnumeration<? extends Attribute> allAttr = attrs.getAll(); while (allAttr.hasMore()) { Attribute attr = allAttr.next(); bufferOrg.append("Attribute: " + attr.getID() + "\n"); NamingEnumeration<?> values = attr.getAll(); while (values.hasMore()) bufferOrg.append("Value: " + values.next() + "\n"); } bufferOrg.append("\n"); m_response = end - start; if (m_response > 0) { if (m_response < m_timeout) { result = result + ("Response Time = " + m_response + "ms"); } else { m_response = m_timeout; result = result + ("Response Time = " + m_response + "ms"); } } else { result = result + ("Response Time < 1ms"); } retry = false; isReachable = true; } catch (NamingException e) { result = (e.getMessage() + "[NamingException]"); retry = true; isReachable = false; } catch (Exception e) { result = (e.getMessage() + "[Exception]"); retry = true; isReachable = false; } finally { bufferOrg.append(result + "\n"); try { if (idctx != null) { idctx.close(); } } catch (NamingException e) { m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e); } } if (i < m_sentCount - 1 && retry) { try { Thread.sleep(m_sentInterval); } catch (InterruptedException e) { break; } } } m_message = result + "(DNS/" + m_portNo + ")"; m_messageOrg = bufferOrg.toString(); return isReachable; } catch (UnknownHostException e) { m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + e.getMessage()); m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage() + ")"; return false; } }
From source file:com.alfaariss.oa.engine.user.provisioning.storage.external.jndi.JNDIExternalStorage.java
/** * Starts the JNDI object./*from w ww.j ava 2s .co m*/ * @see IStorage#start(IConfigurationManager, org.w3c.dom.Element) */ public void start(IConfigurationManager oConfigurationManager, Element eConfig) throws UserException { InitialDirContext context = null; try { Element eResource = oConfigurationManager.getSection(eConfig, "resource"); if (eResource == null) { _logger.error("No 'resource' section found in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } Element eDN = oConfigurationManager.getSection(eResource, "dn"); if (eDN == null) { _logger.error("No 'dn' section found in 'resource' section in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } _sDNBase = oConfigurationManager.getParam(eDN, "base"); if (_sDNBase == null) { _logger.error("No 'dn' item found in 'base' section in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } _sDNUser = oConfigurationManager.getParam(eDN, "user"); _sFilter = oConfigurationManager.getParam(eDN, "filter"); if (_sFilter != null && _sDNUser != null) { _logger.error( "Invalid configuration: Both 'user' and 'filter' item found in 'base' section in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } else if (_sFilter != null) { _logger.info("Using search filter: " + _sFilter); } else if (_sDNUser != null) { _logger.info("Generating search filter with user: " + _sDNUser); } else { _logger.error("No 'user' or 'filter' item found in 'base' section in configuration"); throw new UserException(SystemErrors.ERROR_CONFIG_READ); } _htJNDIEnvironment = readJNDIContext(oConfigurationManager, eResource); //test connection context = new InitialDirContext(_htJNDIEnvironment); } catch (UserException e) { throw e; } catch (Exception e) { _logger.error("Could not create object", e); throw new UserException(SystemErrors.ERROR_INTERNAL); } finally { //Close context try { if (context != null) context.close(); } catch (NamingException e) { _logger.error("Could not close initial context", e); } } }
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 v a 2s . c o 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:dk.magenta.ldap.LDAPMultiBaseUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }//from ww w . ja v a 2s .c o m SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); InitialDirContext ctx = null; for (String userSearchBase : this.userSearchBases) { String query = userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPMultiBaseUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); } if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.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) { logger.debug("error when closing ldap context", e); } } // failed to search // Object[] args = {e.getLocalizedMessage()}; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic); }
From source file:org.alfresco.repo.security.authentication.ldap.LDAPInitialDirContextFactoryImpl.java
public static void main(String[] args) { // ....build a pyramid selling scheme ..... // A group has three user members and 2 group members .... and off we go .... // We make the people and groups to represent this and stick them into LDAP ...used to populate a test data base for user and groups int userMembers = Integer.parseInt(args[3]); ApplicationContext applicationContext = ApplicationContextHelper.getApplicationContext(); LDAPInitialDirContextFactory factory = (LDAPInitialDirContextFactory) applicationContext .getBean("ldapInitialDirContextFactory"); InitialDirContext ctx = null; try {//from w w w . j av a2s . co m ctx = factory.getInitialDirContext("cn=" + args[0] + "," + args[2], args[1]); /* Values we'll use in creating the entry */ Attribute objClasses = new BasicAttribute("objectclass"); objClasses.add("top"); objClasses.add("person"); objClasses.add("organizationalPerson"); objClasses.add("inetOrgPerson"); for (int i = 0; i < userMembers; i++) { Attribute cn = new BasicAttribute("cn", "User" + i + " TestUser"); Attribute sn = new BasicAttribute("sn", "TestUser"); Attribute givenNames = new BasicAttribute("givenName", "User" + i); Attribute telephoneNumber = new BasicAttribute("telephoneNumber", "123"); Attribute uid = new BasicAttribute("uid", "User" + i); Attribute mail = new BasicAttribute("mail", "woof@woof"); Attribute o = new BasicAttribute("o", "Alfresco"); Attribute userPassword = new BasicAttribute("userPassword", "bobbins"); /* Specify the DN we're adding */ String dn = "cn=User" + i + " TestUser," + args[2]; Attributes orig = new BasicAttributes(); orig.put(objClasses); orig.put(cn); orig.put(sn); orig.put(givenNames); orig.put(telephoneNumber); orig.put(uid); orig.put(mail); orig.put(o); orig.put(userPassword); try { ctx.destroySubcontext(dn); } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } ctx.createSubcontext(dn, orig); } } catch (NamingException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (ctx != null) { try { ctx.close(); } catch (NamingException e) { e.printStackTrace(); } } } }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
public String resolveDistinguishedName(String userId, AuthenticationDiagnostic diagnostic) throws AuthenticationException { if (logger.isDebugEnabled()) { logger.debug("resolveDistinguishedName userId:" + userId); }//from w w w.j a va2s. com SearchControls userSearchCtls = new SearchControls(); userSearchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Although we don't actually need any attributes, we ask for the UID for compatibility with Sun Directory Server. See ALF-3868 userSearchCtls.setReturningAttributes(new String[] { this.userIdAttributeName }); String query = this.userSearchBase + "(&" + this.personQuery + "(" + this.userIdAttributeName + "= userId))"; NamingEnumeration<SearchResult> searchResults = null; SearchResult result = null; InitialDirContext ctx = null; try { ctx = this.ldapInitialContextFactory.getDefaultIntialDirContext(diagnostic); // Execute the user query with an additional condition that ensures only the user with the required ID is // returned. Force RFC 2254 escaping of the user ID in the filter to avoid any manipulation searchResults = ctx.search(this.userSearchBase, "(&" + this.personQuery + "(" + this.userIdAttributeName + "={0}))", new Object[] { userId }, userSearchCtls); if (searchResults.hasMore()) { result = searchResults.next(); Attributes attributes = result.getAttributes(); Attribute uidAttribute = attributes.get(this.userIdAttributeName); if (uidAttribute == null) { if (this.errorOnMissingUID) { throw new AlfrescoRuntimeException( "User returned by user search does not have mandatory user id attribute " + attributes); } else { LDAPUserRegistry.logger .warn("User returned by user search does not have mandatory user id attribute " + attributes); } } // MNT:2597 We don't trust the LDAP server's treatment of whitespace, accented characters etc. We will // only resolve this user if the user ID matches else if (userId.equalsIgnoreCase((String) uidAttribute.get(0))) { String name = result.getNameInNamespace(); // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; return name; } // Close the contexts, see ALF-20682 Context context = (Context) result.getObject(); if (context != null) { context.close(); } result = null; } Object[] args = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_LOOKUP_USER, false, args); throw new AuthenticationException("authentication.err.connection.ldap.user.notfound", args, diagnostic); } catch (NamingException e) { // Connection is good here - AuthenticationException would be thrown by ldapInitialContextFactory Object[] args1 = { userId, query }; diagnostic.addStep(AuthenticationDiagnostic.STEP_KEY_LDAP_SEARCH, false, args1); // failed to search Object[] args = { e.getLocalizedMessage() }; throw new AuthenticationException("authentication.err.connection.ldap.search", diagnostic, args, e); } finally { if (result != null) { try { Context context = (Context) result.getObject(); if (context != null) { context.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) { logger.debug("error when closing ldap context", e); } } } }
From source file:org.alfresco.repo.security.sync.ldap.LDAPUserRegistry.java
/** * Invokes the given callback on each entry returned by the given query. * /*from www . j a v a 2 s . com*/ * @param callback * the callback * @param searchBase * the base DN for the search * @param query * the query * @param returningAttributes * the attributes to include in search results * @throws 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 (LDAPUserRegistry.logger.isDebugEnabled()) { LDAPUserRegistry.logger.debug("Processing query"); LDAPUserRegistry.logger.debug("Search base: " + searchBase); LDAPUserRegistry.logger.debug(" Return result limit: " + searchControls.getCountLimit()); LDAPUserRegistry.logger.debug(" DerefLink: " + searchControls.getDerefLinkFlag()); LDAPUserRegistry.logger.debug(" Return named object: " + searchControls.getReturningObjFlag()); LDAPUserRegistry.logger.debug(" Time limit for search: " + searchControls.getTimeLimit()); LDAPUserRegistry.logger.debug(" Attributes to return: " + returningAttributes.length + " items."); for (String ra : returningAttributes) { LDAPUserRegistry.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); } searchResults = null; } if (ctx != null) { try { ctx.close(); } catch (NamingException e) { } } try { callback.close(); } catch (NamingException e) { } } }