Java Code Examples for javax.naming.directory.DirContext#close()

The following examples show how to use javax.naming.directory.DirContext#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DirContextPoolableObjectFactory.java    From spring-ldap with Apache License 2.0 6 votes vote down vote up
/**
 * @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);
    }
}
 
Example 2
Source File: DNS.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 3
Source File: LdapExternalUidTranslation.java    From unitime with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: LdapUserAuthenticator.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
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);
  }
 
Example 5
Source File: LdapConnectionHandler.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void safeClose(DirContext d) {
    if (d != null) {
        try {
            d.close();
        } catch (Exception ignored) {
        }
    }
}
 
Example 6
Source File: LDAPManager.java    From Benchmark with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
	}
}
 
Example 7
Source File: LdapTestUtils.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * 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.
        }
    }
}
 
Example 8
Source File: LdapContextSourceIntegrationTest.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
@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
			}
		}
	}
}
 
Example 9
Source File: DisconnectNPETest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void cleanupContext(DirContext context) {
    if (context != null) {
        try {
            context.close();
        } catch (NamingException e) {
            // ignore
        }
    }
}
 
Example 10
Source File: LdapTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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();
}
 
Example 11
Source File: LdapClient.java    From iaf with Apache License 2.0 5 votes vote down vote up
public String searchObjectForSingleAttributeWithCache(String objectDN, String baseDn, String attribute) throws NamingException {
   	DirContext context=getContext();
   	try {
   		return searchObjectForSingleAttributeWithCache(context, objectDN, baseDn, attribute);
   	} finally {
   		context.close();
   	}
}
 
Example 12
Source File: LdapTestUtils.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * 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
        }
    }
}
 
Example 13
Source File: LdapConnectionManagerService.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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();
}
 
Example 14
Source File: DisconnectNPETest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void cleanupContext(DirContext context) {
    if (context != null) {
        try {
            context.close();
        } catch (NamingException e) {
            // ignore
        }
    }
}
 
Example 15
Source File: LdapUtil.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * 关闭LDAP连接
 */
public static void close(DirContext dc) {
	if (dc != null) {
		try {
			dc.close();
		} catch (NamingException e) {
			LogUtil.error("NamingException in close():" + e);
		}
	}
}
 
Example 16
Source File: JndiResourceResolverFactory.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
private static void closeThenThrow(DirContext ctx, NamingException e) throws NamingException {
  try {
    ctx.close();
  } catch (NamingException ignored) {
    // ignore
  }
  throw e;
}
 
Example 17
Source File: LdapManager.java    From Openfire with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 18
Source File: PooledContextSourceTest.java    From spring-ldap with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 19
Source File: LdapExternalUidLookup.java    From unitime with Apache License 2.0 4 votes vote down vote up
@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();
	}
}
 
Example 20
Source File: OpenLdapDirectoryProvider.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
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;
	}
}