[BAEL-4806] - How to test an LDAP connection from a client: code (#11664)

* working code

* added unit test

* [BAEL-4806] - How to test an LDAP connection from a client

Ticket: http://jira.baeldung.com/browse/BAEL-4806
Draft: https://drafts.baeldung.com/wp-admin/post.php?post=125004&action=edit

* removing draft project

* applying requested changes

* 1. renaming package to comply with java conventions;
* 2. breaking class into methods to enhance readability;
* 3. creating an 'execute' method so it's not necessary to call 'main';

* requested changes

* 1. adding final keyword to constants;
* 2. using diamond operator;

* Update LdapConnectionToolManualTest.java
This commit is contained in:
Ulisses Lima 2022-01-22 15:59:45 -03:00 committed by GitHub
parent 1a2827a216
commit 7ad433dcb6
3 changed files with 237 additions and 0 deletions

View File

@ -0,0 +1,116 @@
package com.baeldung.jndi.ldap.connection.tool;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LdapConnectionTool {
private static final boolean DEBUG_MODE = Boolean.parseBoolean(System.getProperty("debug.mode", "false"));
private static final String QUERY = "query";
public static void main(String[] args) throws NamingException {
execute();
}
public static void execute() throws NamingException {
Hashtable<String, String> env = createEnvironmentFromProperties();
DirContext context = null;
try {
context = connectToServer(env);
String query = env.get(LdapConnectionTool.QUERY);
if (query != null) {
executeQuery(context, query);
}
} catch (NamingException e) {
showErrorMessage(e);
} finally {
close(context);
}
}
private static void close(DirContext context) throws NamingException {
if (context != null) {
try {
context.close();
} catch (NamingException e) {
System.out.println(e.getMessage());
if (DEBUG_MODE)
throw e;
}
}
}
private static void showErrorMessage(NamingException e) throws NamingException {
System.out.println(e.getClass() + ": " + e.getMessage());
Throwable cause = e.getRootCause();
if (cause != null) {
System.out.println(cause.getClass() + ": " + cause.getMessage());
}
if (DEBUG_MODE)
throw e;
}
private static DirContext connectToServer(Hashtable<String, String> env) throws NamingException {
String url = env.get(Context.PROVIDER_URL);
System.out.println("connecting to " + url + "...");
DirContext context = new InitialDirContext(env);
System.out.println("successfully connected to " + url);
return context;
}
private static void executeQuery(DirContext context, String query) throws NamingException {
Attributes attributes = context.getAttributes(query);
NamingEnumeration<? extends Attribute> all = attributes.getAll();
while (all.hasMoreElements()) {
Attribute next = all.next();
String key = next.getID();
Object value = next.get();
System.out.println(key + "=" + value);
}
}
private static Hashtable<String, String> createEnvironmentFromProperties() {
String factory = System.getProperty("factory", "com.sun.jndi.ldap.LdapCtxFactory");
String authType = System.getProperty("authType", "none");
String url = System.getProperty("url");
String user = System.getProperty("user");
String password = System.getProperty("password");
String query = System.getProperty(QUERY, user);
if (url == null) {
throw new IllegalArgumentException("please provide 'url' system property");
}
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
env.put("com.sun.jndi.ldap.read.timeout", "5000");
env.put("com.sun.jndi.ldap.connect.timeout", "5000");
env.put(Context.SECURITY_AUTHENTICATION, authType);
env.put(Context.PROVIDER_URL, url);
if (query != null) {
env.put(LdapConnectionTool.QUERY, query);
}
if (user != null) {
if (password == null) {
throw new IllegalArgumentException("please provide 'password' system property");
}
env.put(Context.SECURITY_PRINCIPAL, user);
env.put(Context.SECURITY_CREDENTIALS, password);
}
return env;
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.jndi.ldap.connection.tool;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import javax.naming.NamingException;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.annotations.ApplyLdifFiles;
import org.apache.directory.server.core.annotations.CreateDS;
import org.apache.directory.server.core.annotations.CreatePartition;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
import org.apache.directory.server.core.integ.FrameworkRunner;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(FrameworkRunner.class)
@CreateLdapServer(allowAnonymousAccess = true, transports = { @CreateTransport(protocol = "LDAP", address = "localhost", port = 10389) })
@CreateDS(allowAnonAccess = true, partitions = { @CreatePartition(name = "ldap-connection-tool", suffix = "dc=baeldung,dc=com") })
@ApplyLdifFiles({ "ldap-connection-tool.ldif" })
// class marked as manual test, as it has to run independently of other unit tests in the module
public class LdapConnectionToolManualTest extends AbstractLdapTestUnit {
@Before
public void init() {
System.setProperty("debug.mode", "true");
System.clearProperty("url");
System.clearProperty("user");
System.clearProperty("password");
System.clearProperty("query");
}
@Test
public void whenNoUrlProvided_thenConnectionFails() throws Exception {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> LdapConnectionTool.execute());
}
@Test
public void givenUrlProvided_whenValidUrl_thenConnectionSucceeds() throws Exception {
System.setProperty("url", "ldap://localhost:10389");
assertThatCode(() -> LdapConnectionTool.execute()).doesNotThrowAnyException();
}
@Test
public void givenUrlProvided_whenInvalidUrl_thenConnectionFails() throws Exception {
System.setProperty("url", "ldap://unkownhost:10389");
assertThatExceptionOfType(NamingException.class).isThrownBy(() -> LdapConnectionTool.execute());
}
@Test
public void givenUserProvided_whenCorrectPassword_thenConnectionSucceeds() throws Exception {
System.setProperty("url", "ldap://localhost:10389");
System.setProperty("user", "uid=gauss,dc=baeldung,dc=com");
System.setProperty("password", "password");
assertThatCode(() -> LdapConnectionTool.execute()).doesNotThrowAnyException();
}
@Test
public void givenUserProvided_whenPasswordIsNull_thenConnectionFails() throws Exception {
System.setProperty("url", "ldap://localhost:10389");
System.setProperty("user", "uid=gauss,dc=baeldung,dc=com");
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> LdapConnectionTool.execute());
}
@Test
public void whenOnlyValidQueryProvided_thenConnectionSucceeds() throws Exception {
System.setProperty("url", "ldap://localhost:10389");
System.setProperty("query", "uid=gauss,dc=baeldung,dc=com");
assertThatCode(() -> LdapConnectionTool.execute()).doesNotThrowAnyException();
}
@Test
public void givenUserProvided_whenQueryProvided_thenConnectionSucceeds() throws Exception {
System.setProperty("url", "ldap://localhost:10389");
System.setProperty("user", "uid=gauss,dc=baeldung,dc=com");
System.setProperty("password", "password");
System.setProperty("query", "uid=newton,dc=baeldung,dc=com");
assertThatCode(() -> LdapConnectionTool.execute()).doesNotThrowAnyException();
}
}

View File

@ -0,0 +1,34 @@
version: 1
dn: dc=baeldung,dc=com
objectClass: top
objectClass: dcObject
objectClass: organization
dc: baeldung
o: baeldung.com
dn: cn=admin,dc=baeldung,dc=com
objectClass: simpleSecurityObject
objectClass: organizationalRole
cn: admin
description: LDAP administrator
userPassword: password
dn: uid=newton,dc=baeldung,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: Isaac Newton
sn: Newton
uid: newton
userPassword: password
dn: uid=gauss,dc=baeldung,dc=com
objectClass: inetOrgPerson
objectClass: organizationalPerson
objectClass: person
objectClass: top
cn: Carl Friedrich Gauss
sn: Gauss
uid: gauss
userPassword: password