javax.naming.directory.DirContext#close ( )源码实例Demo

下面列出了javax.naming.directory.DirContext#close ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * @see org.apache.commons.pool.BaseKeyedPoolableObjectFactory#destroyObject(java.lang.Object,
 *      java.lang.Object)
 */
public void destroyObject(Object key, Object obj) throws Exception {
    Assert.isTrue(obj instanceof DirContext,
            "The Object to validate must be of type '" + DirContext.class
                    + "'");

    try {
        final DirContext dirContext = (DirContext) obj;
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Closing " + key + " DirContext='"
                    + dirContext + "'");
        }
        dirContext.close();
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Closed " + key + " DirContext='"
                    + dirContext + "'");
        }
    } catch (Exception e) {
        this.logger.warn(
                "An exception occured while closing '" + obj + "'", e);
    }
}
 
源代码2 项目: unitime   文件: LdapExternalUidTranslation.java
public String ext2uid(String puid) {
    try {
        DirContext ctx = null;
        try {
            ctx = getDirContext();
            Attributes attributes = ctx.getAttributes(
            		ApplicationProperties.getProperty("tmtbl.authenticate.ldap.ext2uid").replaceAll("%", puid),
            		new String[] {
            			ApplicationProperties.getProperty("tmtbl.authenticate.ldap.login", "uid")
            		});
            if (attributes!=null) {
                Attribute uid = attributes.get(ApplicationProperties.getProperty("tmtbl.authenticate.ldap.login", "uid"));
                if (uid!=null) return (String)uid.get();
            }
        } finally {
            if (ctx!=null) ctx.close();
        }
    } catch (Exception e) {
        Debug.error("Unable to translate ext to uid, "+e.getMessage());
    }
    return null;
}
 
源代码3 项目: RDFS   文件: DNS.java
/**
 * Returns the hostname associated with the specified IP address by the
 * provided nameserver.
 * 
 * @param hostIp
 *            The address to reverse lookup
 * @param ns
 *            The host name of a reachable DNS server
 * @return The host name associated with the provided IP
 * @throws NamingException
 *             If a NamingException is encountered
 */
public static String reverseDns(InetAddress hostIp, String ns)
  throws NamingException {
  //
  // Builds the reverse IP lookup form
  // This is formed by reversing the IP numbers and appending in-addr.arpa
  //
  String[] parts = hostIp.getHostAddress().split("\\.");
  String reverseIP = parts[3] + "." + parts[2] + "." + parts[1] + "."
    + parts[0] + ".in-addr.arpa";

  DirContext ictx = new InitialDirContext();
  Attributes attribute =
    ictx.getAttributes("dns://"               // Use "dns:///" if the default
                       + ((ns == null) ? "" : ns) + 
                       // nameserver is to be used
                       "/" + reverseIP, new String[] { "PTR" });
  ictx.close();
  
  return attribute.get("PTR").get().toString();
}
 
private static void closeThenThrow(DirContext ctx, NamingException e) throws NamingException {
  try {
    ctx.close();
  } catch (NamingException ignored) {
    // ignore
  }
  throw e;
}
 
源代码5 项目: jeecg   文件: LdapUtil.java
/**
 * 关闭LDAP连接
 */
public static void close(DirContext dc) {
	if (dc != null) {
		try {
			dc.close();
		} catch (NamingException e) {
			LogUtil.error("NamingException in close():" + e);
		}
	}
}
 
源代码6 项目: dragonwell8_jdk   文件: DisconnectNPETest.java
private void cleanupContext(DirContext context) {
    if (context != null) {
        try {
            context.close();
        } catch (NamingException e) {
            // ignore
        }
    }
}
 
private void verifyIdentity(final Config configuration, String bindDn, String bindCredential) throws NamingException {
    Hashtable<String, String> connectionProperties = getConnectionOnlyProperties(configuration);
    connectionProperties.put(Context.SECURITY_PRINCIPAL, bindDn);
    connectionProperties.put(Context.SECURITY_CREDENTIALS, bindCredential);

    /* WFCORE-2647: originally, we always used a trust only SSLContext got via getSSLContext(true) here
     * as we did not want to authenticate using a pre-defined key in a KeyStore.
     * However, there are LDAP servers, such as OpenLDAP who expect the client cert on every request
     * and hence we had to make the setting configurable. */
    final boolean trustOnly = !configuration.isAlwaysSendClientCert();
    SECURITY_LOGGER.tracef("Using a %s SSL context to authenticate user %s", trustOnly ? "trustOnly" : "fullSSLContext", bindDn);
    DirContext context = getConnection(connectionProperties, getSSLContext(trustOnly));
    context.close();
}
 
源代码8 项目: spring-ldap   文件: LdapTestUtils.java
/**
 * Clear the directory sub-tree starting with the node represented by the
 * supplied distinguished name.
 *
 * @param contextSource the ContextSource to use for getting a DirContext.
 * @param name          the distinguished name of the root node.
 * @throws NamingException if anything goes wrong removing the sub-tree.
 */
public static void clearSubContexts(ContextSource contextSource, Name name) throws NamingException {
    DirContext ctx = null;
    try {
        ctx = contextSource.getReadWriteContext();
        clearSubContexts(ctx, name);
    } finally {
        try {
            ctx.close();
        } catch (Exception e) {
            // Never mind this
        }
    }
}
 
源代码9 项目: iaf   文件: LdapClient.java
public String searchObjectForSingleAttributeWithCache(String objectDN, String baseDn, String attribute) throws NamingException {
   	DirContext context=getContext();
   	try {
   		return searchObjectForSingleAttributeWithCache(context, objectDN, baseDn, attribute);
   	} finally {
   		context.close();
   	}
}
 
源代码10 项目: gemfirexd-oss   文件: LdapUserAuthenticator.java
public Principal authenticate(Properties props, DistributedMember member) {

    String userName = props.getProperty(UserPasswordAuthInit.USER_NAME);
    if (userName == null) {
      throw new AuthenticationFailedException(
          "LdapUserAuthenticator: user name property ["
              + UserPasswordAuthInit.USER_NAME + "] not provided");
    }
    String passwd = props.getProperty(UserPasswordAuthInit.PASSWORD);
    if (passwd == null) {
      passwd = "";
    }

    Properties env = new Properties();
    env
        .put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, this.ldapUrlScheme + this.ldapServer + '/'
        + this.basedn);
    String fullentry = "uid=" + userName + "," + this.basedn;
    env.put(Context.SECURITY_PRINCIPAL, fullentry);
    env.put(Context.SECURITY_CREDENTIALS, passwd);
    try {
      DirContext ctx = new InitialDirContext(env);
      ctx.close();
    }
    catch (Exception e) {
      //TODO:hitesh need to add getCause message
      throw new AuthenticationFailedException(
          "LdapUserAuthenticator: Failure with provided username, password "
              + "combination for user name: " + userName);
    }
    return new UsernamePrincipal(userName);
  }
 
源代码11 项目: wildfly-core   文件: LdapTestCase.java
@Test
public void testDirContextSsl() throws Exception {
    ServiceName serviceNameDirContext = Capabilities.DIR_CONTEXT_RUNTIME_CAPABILITY.getCapabilityServiceName("DirContextSsl");
    ExceptionSupplier<DirContext, NamingException> dirContextSup = (DirContextSupplier) services.getContainer().getService(serviceNameDirContext).getValue();
    DirContext dirContext = dirContextSup.get();
    Assert.assertNotNull(dirContext);
    Assert.assertEquals("org.wildfly.security.auth.realm.ldap.DelegatingLdapContext", dirContext.getClass().getName());
    dirContext.close();
}
 
源代码12 项目: jdk8u_jdk   文件: DisconnectNPETest.java
private void cleanupContext(DirContext context) {
    if (context != null) {
        try {
            context.close();
        } catch (NamingException e) {
            // ignore
        }
    }
}
 
@Test
   @Category(NoAdTest.class)
public void testGetContext() throws NamingException {
	DirContext ctx = null;
	try {
		String expectedPrincipal = "cn=Some Person,ou=company1,ou=Sweden," + base;
		String expectedCredentials = "password";
		ctx = tested.getContext(expectedPrincipal, expectedCredentials);
		assertThat(ctx).isNotNull();
		// Double check to see that we are authenticated, and that we did not receive
		// a connection eligible for connection pooling.
		Hashtable environment = ctx.getEnvironment();
           assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse();
		assertThat(environment.get(Context.SECURITY_PRINCIPAL)).isEqualTo(expectedPrincipal);
		assertThat(environment.get(Context.SECURITY_CREDENTIALS)).isEqualTo(expectedCredentials);
	}
	finally {
		// Always clean up.
		if (ctx != null) {
			try {
				ctx.close();
			}
			catch (Exception e) {
				// Never mind this
			}
		}
	}
}
 
源代码14 项目: spring-ldap   文件: LdapTestUtils.java
/**
 * Load an Ldif file into an LDAP server.
 *
 * @param contextSource ContextSource to use for getting a DirContext to
 *                      interact with the LDAP server.
 * @param ldifFile      a Resource representing a valid LDIF file.
 * @throws IOException if the Resource cannot be read.
 */
public static void loadLdif(ContextSource contextSource, Resource ldifFile) throws IOException {
    DirContext context = contextSource.getReadWriteContext();
    try {
        loadLdif(context, ldifFile);
    } finally {
        try {
            context.close();
        } catch (Exception e) {
            // This is not the exception we are interested in.
        }
    }
}
 
源代码15 项目: Benchmark   文件: LDAPManager.java
/**
 * Search LDAPPerson by name
 * 
 * @param person
 *            to search
 * @return true if record found
 */
@SuppressWarnings("unused")
private boolean search(LDAPPerson person) {
	try {

		DirContext ctx = getDirContext();
		String base = "ou=users,ou=system";

		SearchControls sc = new SearchControls();
		sc.setSearchScope(SearchControls.SUBTREE_SCOPE);

		String filter = "(&(objectclass=person)(uid=" + ESAPI_Encoder.encodeForLDAP(person.getName()) + "))";

		NamingEnumeration<SearchResult> results = ctx.search(base, filter, sc);

		while (results.hasMore()) {
			SearchResult sr = (SearchResult) results.next();
			Attributes attrs = sr.getAttributes();

			Attribute attr = attrs.get("uid");
			if (attr != null) {
				// logger.debug("record found " + attr.get());
				// System.out.println("record found " + attr.get());
			}
		}
		ctx.close();

		return true;
	} catch (Exception e) {
		System.out.println("LDAP error search: ");
		// logger.error(e, e);
		e.printStackTrace();
		return false;
	}
}
 
源代码16 项目: wildfly-core   文件: LdapConnectionHandler.java
private void safeClose(DirContext d) {
    if (d != null) {
        try {
            d.close();
        } catch (Exception ignored) {
        }
    }
}
 
源代码17 项目: Openfire   文件: LdapManager.java
/**
 * Check if the given DN matches the group search filter
 *
 * @param dn the absolute DN of the node to check
 * @return true if the given DN is matching the group filter. false oterwise.
 * @throws NamingException if the search for the dn fails.
 */
public boolean isGroupDN(LdapName dn) throws NamingException {
    Log.debug("LdapManager: Trying to check if DN is a group. DN: {}, Base DN: {} ...", dn, baseDN);

    // is it a sub DN of the base DN?
    if (!dn.startsWith(baseDN)
        && (alternateBaseDN == null || !dn.startsWith(alternateBaseDN))) {
        if (Log.isDebugEnabled()) {
            Log.debug("LdapManager: DN ({}) does not fit to baseDN ({},{})", dn, baseDN, alternateBaseDN);
        }
        return false;
    }

    DirContext ctx = null;
    try {
        Log.debug("LdapManager: Starting LDAP search to check group DN: {}", dn);
        // Search for the group in the node with the given DN.
        // should return the group object itself if is matches the group filter
        ctx = getContext(dn);
        // only search the object itself.
        SearchControls constraints = new SearchControls();
        constraints.setSearchScope(SearchControls.OBJECT_SCOPE);
        constraints.setReturningAttributes(new String[]{});
        String filter = MessageFormat.format(getGroupSearchFilter(), "*");
        NamingEnumeration<SearchResult> answer = ctx.search("", filter, constraints);

        Log.debug("LdapManager: ... group check search finished for DN: {}", dn);

        boolean result = (answer != null && answer.hasMoreElements());

        if (answer != null) {
            answer.close();
        }
        Log.debug("LdapManager: DN is group: {}? {}!", dn, result);
        return result;
    }
    catch (final Exception e) {
        Log.debug("LdapManager: Exception thrown when checking if DN is a group {}", dn, e);
        throw e;
    }
    finally {
        try {
            if (ctx != null)
                ctx.close();
        }
        catch (Exception ex) {
            Log.debug("An exception occurred while trying to close a LDAP context after trying to verify that DN '{}' is a group.", dn, ex);
        }
    }
}
 
源代码18 项目: unitime   文件: LdapExternalUidLookup.java
@Override
public UserInfo doLookup(String searchId) throws Exception {
	
	String query = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.identify");
	if (query == null) return null;
	
       DirContext ctx = null;
       try {
           ctx = getDirContext();
           
   		String idAttributeName = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.externalId","uid");
   		String loginAttributeName = ApplicationProperties.getProperty("tmtbl.authenticate.ldap.login", "uid");
   		Attributes attributes = ctx.getAttributes(query.replaceAll("%", searchId), new String[] {idAttributeName, loginAttributeName, "cn", "givenName", "sn", "mail"});
           Attribute idAttribute = attributes.get(idAttributeName);
           if (idAttribute == null) return null;
           
       	UserInfo user = new UserInfo();
       	user.setExternalId((String)idAttribute.get());
       	user.setUserName((String)attributes.get(loginAttributeName).get());
       	if (attributes.get("cn") != null)
       		user.setName((String)attributes.get("cn").get());
       	if (attributes.get("givenName") != null)
       		user.setFirstName((String)attributes.get("givenName").get());
       	if (attributes.get("cn") != null)
       		user.setName((String)attributes.get("cn").get());
       	if (attributes.get("sn") != null)
       		user.setLastName((String)attributes.get("sn").get());
       	if (attributes.get("mail") != null) {
       		user.setEmail((String)attributes.get("mail").get());
       	} else {
           	String email = user.getUserName() + "@";
           	for (String x: query.split(","))
           		if (x.startsWith("dc=")) email += (email.endsWith("@") ? "" : ".") + x.substring(3);
           	if (!email.endsWith("@")) user.setEmail(email);
       	}
       	
       	return user;			
	} finally {
		if (ctx != null) ctx.close();
	}
}
 
源代码19 项目: spring-ldap   文件: PooledContextSourceTest.java
@Test
public void testGetReadOnlyContextPool() throws Exception {
    DirContext secondDirContextMock = mock(DirContext.class);
    
    when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock, secondDirContextMock);

    final PooledContextSource PooledContextSource = new PooledContextSource(null);
    PooledContextSource.setContextSource(contextSourceMock);

    //Get a context
    final DirContext readOnlyContext1 = PooledContextSource.getReadOnlyContext();
    assertThat(readOnlyContext1).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic
    assertThat(PooledContextSource.getNumActive()).isEqualTo(1);
    assertThat(PooledContextSource.getNumIdle()).isEqualTo(0);
    
    //Close the context
    readOnlyContext1.close();
    assertThat(PooledContextSource.getNumActive()).isEqualTo(0);
    assertThat(PooledContextSource.getNumIdle()).isEqualTo(1);
    
    //Get the context again
    final DirContext readOnlyContext2 = PooledContextSource.getReadOnlyContext();
    assertThat(readOnlyContext2).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic
    assertThat(PooledContextSource.getNumActive()).isEqualTo(1);
    assertThat(PooledContextSource.getNumIdle()).isEqualTo(0);
    
    //Get a new context
    final DirContext readOnlyContext3 = PooledContextSource.getReadOnlyContext();
    assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); //Order reversed because the 'wrapper' has the needed equals logic
    assertThat(PooledContextSource.getNumActive()).isEqualTo(2);
    assertThat(PooledContextSource.getNumIdle()).isEqualTo(0);

    //Close context
    readOnlyContext2.close();
    assertThat(PooledContextSource.getNumActive()).isEqualTo(1);
    assertThat(PooledContextSource.getNumIdle()).isEqualTo(1);
    
    //Close context
    readOnlyContext3.close();
    assertThat(PooledContextSource.getNumActive()).isEqualTo(0);
    assertThat(PooledContextSource.getNumIdle()).isEqualTo(2);
}
 
源代码20 项目: sakai   文件: OpenLdapDirectoryProvider.java
protected boolean userExists(String id)
{
	env.put(Context.SECURITY_AUTHENTICATION, "simple");
	env.put(Context.SECURITY_CREDENTIALS, "secret");

	try
	{
		DirContext ctx = new InitialDirContext(env);

		/*
		 * Setup subtree scope to tell LDAP to recursively descend directory structure during searches.
		 */
		SearchControls searchControls = new SearchControls();
		searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

		/*
		 * Setup the directory entry attributes we want to search for. In this case it is the user's ID.
		 */

		String filter = "(&(objectclass=person)(uid=" + escapeSearchFilterTerm(id) + "))";

		/* Execute the search, starting at the directory level of Users */

		NamingEnumeration hits = ctx.search(getBasePath(), filter, searchControls);

		/* All we need to know is if there were any hits at all. */

		if (hits.hasMore())
		{
			hits.close();
			ctx.close();
			return true;
		}
		else
		{
			hits.close();
			ctx.close();
			return false;
		}
	}
	catch (Exception e)
	{
		log.error(e.getMessage(), e);
		return false;
	}
}