Legacy LDAP tests and support files deleted.

This commit is contained in:
Luke Taylor 2006-01-26 20:49:55 +00:00
parent 2b0a65983d
commit 20469b6ac9
7 changed files with 0 additions and 1100 deletions

View File

@ -1,59 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.providers.dao.ldap;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import org.acegisecurity.providers.dao.ldap.support.BaseLdapTestCase;
/** Tests to ensure the directory server we are running against is
* configured as expected.
*
* @author robert.sanders
*/
public class DirSetupTestCase extends BaseLdapTestCase {
/** Simply test the connection to the test LDAP server;
* if this test fails we know the server setup needs checked.
* @throws NamingException
*/
public void testConnection() throws NamingException {
Object obj = getClientContext().lookup("ou=users");
//System.out.println( obj );
assertNotNull( obj );
}
public void testSimpleUidUser() throws NamingException {
Attributes myAttrs = getClientContext().getAttributes("uid=one.user,ou=users");
assertEquals(8, myAttrs.size());
assertEquals("uid=one.user,ou=users,ou=system", myAttrs.get("dn").get() );
}
public void testSimpleCnUser() throws NamingException {
Attributes myAttrs = getClientContext().getAttributes("cn=user.two,ou=users");
assertEquals(8, myAttrs.size());
assertEquals("cn=user.two,ou=users,ou=system", myAttrs.get("dn").get() );
assertEquals("Two", myAttrs.get("givenName").get() );
}
public void testOthersUsers() throws NamingException {
Attributes myAttrs = getClientContext().getAttributes("uid=other.two,ou=others");
assertEquals("uid=other.two,ou=others,ou=system", myAttrs.get("dn").get() );
assertEquals("Other", myAttrs.get("givenName").get() );
}
}

View File

@ -1,132 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.providers.dao.ldap;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.providers.dao.ldap.support.BaseLdapTestCase;
import org.acegisecurity.userdetails.UserDetails;
import javax.naming.NamingException;
/**
* Set of JUnit tests for the LdapPasswordAuthenticationDao.
*
* @author $author$
* @version $Revision$
*/
public class LdapPasswordAuthenticationDaoTests extends BaseLdapTestCase {
private LdapPasswordAuthenticationDao dao;
private String DEFAULT_ROLE = "DEFAULT_ROLE";
public static void main(String[] args) {
LdapPasswordAuthenticationDaoTests ats = new LdapPasswordAuthenticationDaoTests();
ats.setUp();
try {
ats.testSimpleUidUser();
} catch (Throwable t) {
t.printStackTrace();
} finally {
System.exit(0);
}
}
/** Check to see that a user with no roles can not login
* (this is the correct behavior the last time I checked the Acegi Docs).
*
*/
public void testEmptyRoles() {
dao.setUsernameFormat("uid={0},ou=users,ou=system");
try {
UserDetails userDetails = dao.loadUserByUsernameAndPassword("user.two",
"plaintext2");
fail("No roles are accessible for user; this test _should_ fail.");
} catch (BadCredentialsException ex) {
assertTrue("No roles are accessible for user; this test _should_ fail.",
ex.getMessage().startsWith(LdapPasswordAuthenticationDao.BAD_CREDENTIALS_EXCEPTION_MESSAGE));
}
}
/** Test that the user who is identified by
* Common Name (cn=..) can be authenticated. */
public void testSimpleCnUser() throws NamingException {
dao.setUsernameFormat("cn={0},ou=users,ou=system");
dao.setUserLookupNameFormat("cn={0},ou=users");
dao.setDefaultRole(DEFAULT_ROLE);
try {
UserDetails userDetails = dao.loadUserByUsernameAndPassword("User Two",
"plaintext2");
assertEquals(1, userDetails.getAuthorities().length);
assertEquals(DEFAULT_ROLE,
userDetails.getAuthorities()[0].getAuthority());
} catch (BadCredentialsException ex) {
fail();
}
}
/** Test that the user who is identified by
* UID (uid=..) can be authenticated. */
public void testSimpleUidUser() throws NamingException {
dao.setUsernameFormat("uid={0},ou=users,ou=system");
dao.setUserLookupNameFormat("uid={0},ou=users");
dao.setDefaultRole(DEFAULT_ROLE);
try {
System.out.println("Attempting user auth.");
UserDetails userDetails = dao.loadUserByUsernameAndPassword("one.user",
"plaintext");
//System.out.println( "UserDetails = " + userDetails );
assertEquals(1, userDetails.getAuthorities().length);
assertEquals(DEFAULT_ROLE,
userDetails.getAuthorities()[0].getAuthority());
} catch (BadCredentialsException ex) {
System.out.println("Unable to authenticate user.");
ex.printStackTrace();
fail();
}
}
/** Test that a login w/ a bad password fails. */
public void testSimpleUidUserBadPassword() throws NamingException {
dao.setUsernameFormat("uid={0},ou=users,ou=system");
dao.setUserLookupNameFormat("uid={0},ou=users");
dao.setDefaultRole(DEFAULT_ROLE);
try {
UserDetails userDetails = dao.loadUserByUsernameAndPassword("one.user",
"plainlywrong");
fail();
} catch (BadCredentialsException ex) {
assertTrue(true);
}
}
/**
* Setup the basic properties of our LdapPasswordAuthenticationDao
*/
protected void setUp() {
dao = new LdapPasswordAuthenticationDao();
dao.setUrl("ldap://localhost:389/ou=system");
}
}

View File

@ -1,431 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.providers.dao.ldap;
import java.util.HashMap;
import java.util.Map;
import junit.framework.TestCase;
import org.acegisecurity.AccountExpiredException;
import org.acegisecurity.Authentication;
import org.acegisecurity.AuthenticationServiceException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.CredentialsExpiredException;
import org.acegisecurity.DisabledException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.LockedException;
import org.acegisecurity.providers.TestingAuthenticationToken;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.dao.UserCache;
import org.acegisecurity.providers.dao.cache.EhCacheBasedUserCache;
import org.acegisecurity.providers.dao.cache.NullUserCache;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataRetrievalFailureException;
/**
* Tests {@link PasswordDaoAuthenticationProvider}.
*
* @author Karel Miarka
*/
public class PasswordDaoAuthenticationProviderTests extends TestCase {
//~ Methods ================================================================
public final void setUp() throws Exception {
super.setUp();
}
public static void main(String[] args) {
junit.textui.TestRunner.run(PasswordDaoAuthenticationProviderTests.class);
}
public void testAuthenticateFailsForIncorrectPasswordCase() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa",
"KOala");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsIfAccountExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter",
"opal");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserPeterAccountExpired());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown AccountExpiredException");
} catch (AccountExpiredException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsIfAccountLocked() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter",
"opal");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserPeterAccountLocked());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown AccountExpiredException");
} catch (LockedException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsIfCredentialsExpired() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter",
"opal");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserPeterCredentialsExpired());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown CredentialsExpiredException");
} catch (CredentialsExpiredException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsIfUserDisabled() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("peter",
"opal");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserPeter());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown DisabledException");
} catch (DisabledException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsWhenAuthenticationDaoHasBackendFailure() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa",
"koala");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoSimulateBackendError());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown AuthenticationServiceException");
} catch (AuthenticationServiceException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsWithInvalidPassword() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa",
"INVALID_PASSWORD");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsWithInvalidUsername() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("INVALID_USER",
"koala");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException expected) {
assertTrue(true);
}
}
public void testAuthenticateFailsWithMixedCaseUsernameIfDefaultChanged() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("MaRiSSA",
"koala");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
try {
provider.authenticate(token);
fail("Should have thrown BadCredentialsException");
} catch (BadCredentialsException expected) {
assertTrue(true);
}
}
public void testAuthenticates() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa",
"koala");
token.setDetails("192.168.0.1");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
Authentication result = provider.authenticate(token);
if (!(result instanceof UsernamePasswordAuthenticationToken)) {
fail(
"Should have returned instance of UsernamePasswordAuthenticationToken");
}
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertEquals(User.class, castResult.getPrincipal().getClass());
assertEquals("koala", castResult.getCredentials());
assertEquals("ROLE_ONE", castResult.getAuthorities()[0].getAuthority());
assertEquals("ROLE_TWO", castResult.getAuthorities()[1].getAuthority());
assertEquals("192.168.0.1", castResult.getDetails());
}
public void testAuthenticatesASecondTime() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa",
"koala");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
Authentication result = provider.authenticate(token);
if (!(result instanceof UsernamePasswordAuthenticationToken)) {
fail(
"Should have returned instance of UsernamePasswordAuthenticationToken");
}
// Now try to authenticate with the previous result (with its UserDetails)
Authentication result2 = provider.authenticate(result);
if (!(result2 instanceof UsernamePasswordAuthenticationToken)) {
fail(
"Should have returned instance of UsernamePasswordAuthenticationToken");
}
assertEquals(result.getCredentials(), result2.getCredentials());
}
public void testAuthenticatesWithForcePrincipalAsString() {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken("marissa",
"koala");
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserMarissa());
provider.setUserCache(new MockUserCache());
provider.setForcePrincipalAsString(true);
Authentication result = provider.authenticate(token);
if (!(result instanceof UsernamePasswordAuthenticationToken)) {
fail(
"Should have returned instance of UsernamePasswordAuthenticationToken");
}
UsernamePasswordAuthenticationToken castResult = (UsernamePasswordAuthenticationToken) result;
assertEquals(String.class, castResult.getPrincipal().getClass());
assertEquals("marissa", castResult.getPrincipal());
}
public void testGettersSetters() {
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setUserCache(new EhCacheBasedUserCache());
assertEquals(EhCacheBasedUserCache.class,
provider.getUserCache().getClass());
assertFalse(provider.isForcePrincipalAsString());
provider.setForcePrincipalAsString(true);
assertTrue(provider.isForcePrincipalAsString());
}
public void testStartupFailsIfNoAuthenticationDao()
throws Exception {
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
try {
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testStartupFailsIfNoUserCacheSet() throws Exception {
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
provider.setPasswordAuthenticationDao(new MockAuthenticationDaoUserMarissa());
assertEquals(NullUserCache.class, provider.getUserCache().getClass());
provider.setUserCache(null);
try {
provider.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
} catch (IllegalArgumentException expected) {
assertTrue(true);
}
}
public void testStartupSuccess() throws Exception {
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
PasswordAuthenticationDao dao = new MockAuthenticationDaoUserMarissa();
provider.setPasswordAuthenticationDao(dao);
provider.setUserCache(new MockUserCache());
assertEquals(dao, provider.getPasswordAuthenticationDao());
provider.afterPropertiesSet();
assertTrue(true);
}
public void testSupports() {
PasswordDaoAuthenticationProvider provider = new PasswordDaoAuthenticationProvider();
assertTrue(provider.supports(UsernamePasswordAuthenticationToken.class));
assertTrue(!provider.supports(TestingAuthenticationToken.class));
}
//~ Inner Classes ==========================================================
private class MockAuthenticationDaoSimulateBackendError
implements PasswordAuthenticationDao {
public UserDetails loadUserByUsernameAndPassword(String username,
String password)
throws BadCredentialsException, DataAccessException {
throw new DataRetrievalFailureException(
"This mock simulator is designed to fail");
}
}
private class MockAuthenticationDaoUserMarissa
implements PasswordAuthenticationDao {
public UserDetails loadUserByUsernameAndPassword(String username,
String password)
throws BadCredentialsException, DataAccessException {
if ("marissa".equals(username) && "koala".equals(password)) {
return new User("marissa", "koala", true, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
} else {
throw new BadCredentialsException("Invalid credentials");
}
}
}
private class MockAuthenticationDaoUserPeter
implements PasswordAuthenticationDao {
public UserDetails loadUserByUsernameAndPassword(String username,
String password)
throws BadCredentialsException, DataAccessException {
if ("peter".equals(username) && "opal".equals(password)) {
return new User("peter", "opal", false, true, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
} else {
throw new BadCredentialsException("Invalid credentials");
}
}
}
private class MockAuthenticationDaoUserPeterAccountExpired
implements PasswordAuthenticationDao {
public UserDetails loadUserByUsernameAndPassword(String username,
String password)
throws UsernameNotFoundException, DataAccessException {
if ("peter".equals(username)) {
return new User("peter", "opal", true, false, true, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
} else {
throw new UsernameNotFoundException("Could not find: "
+ username);
}
}
}
private class MockAuthenticationDaoUserPeterAccountLocked
implements PasswordAuthenticationDao {
public UserDetails loadUserByUsernameAndPassword(String username,
String password)
throws UsernameNotFoundException, DataAccessException {
if ("peter".equals(username)) {
return new User("peter", "opal", true, true, true, false,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
} else {
throw new UsernameNotFoundException("Could not find: "
+ username);
}
}
}
private class MockAuthenticationDaoUserPeterCredentialsExpired
implements PasswordAuthenticationDao {
public UserDetails loadUserByUsernameAndPassword(String username,
String password)
throws UsernameNotFoundException, DataAccessException {
if ("peter".equals(username)) {
return new User("peter", "opal", true, true, false, true,
new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
"ROLE_TWO")});
} else {
throw new UsernameNotFoundException("Could not find: "
+ username);
}
}
}
private class MockUserCache implements UserCache {
private Map cache = new HashMap();
public UserDetails getUserFromCache(String username) {
return (User) cache.get(username);
}
public void putUserInCache(UserDetails user) {
cache.put(user.getUsername(), user);
}
public void removeUserFromCache(String username) {}
}
}

View File

@ -1,43 +0,0 @@
<html>
<body bgcolor="#ffffff">
<h2>LDAP JUnit Tests and Helper Files.</h2>
<p>
Because the inter-class dependencies may not be obvious at first glance
they are documented for this package; most of this complexity is on account
of the JUnit design, hopefully future testing frameworks will be less intrusive.
</p>
<dl>
<dt>LdapTestHelper</dt>
<dd>Containing the majority of the code which references the
apache directory server classes, LdapTestHelper is designed
to be assigned as a static field in the BaseLdapTestCase, although
it can be used elsewhere. LdapTestHelper contains all the code
needed to start, initialize, and shutdown the directory server.
</dd>
<dt>DirContentsInitializer</dt>
<dd>DirContentsInitializer contains the JNDI code
used to load the directory server up with entries (users and groups).
When I figure out how to correctly import LDIF files, DirContentsInitializer
will probably be radically simplified.
</dd>
<dt>BaseLdapTestCase</dt>
<dd>Contains common methods and fields that will probably
be needed by any TestCase which interacts with the directory server,
including a static reference to a LdapTestHelper instance.
</dd>
<dt>DirSetupTestCase</dt>
<dd>Contains some simple code designed to test that DirContentsInitializer
has functioned properly. If these tests fail then the
other tests are expected to fail too.
</dd>
<dt>LdapPasswordAuthenticationTest</dt>
<dd>Contains tests which configure a LdapPasswordAuthenticationDao bean and
excersize it against the directory server.
</dd>
</dl>
</body>
</html>

View File

@ -1,84 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.providers.dao.ldap.support;
import junit.framework.TestCase;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
/**
* This class defines certain base properties needed by
* all LDAP unit tests. It also uses the EmbeddedLdapServerController to
* bootstrap an 'embedded' instance of the Apache Directory Server to
* run the Unit tests against.
*/
public class BaseLdapTestCase extends TestCase {
//~ Static fields/initializers =============================================
// static finalizers, they'd be nice, as the EmbeddedLdapServerController
// never seems to get the chance to cleanup after itself
// Maybe JUnit4 will include such a thing.
protected static EmbeddedLdapServerController embeddedLdapServerController = new EmbeddedLdapServerController();
static {
try {
LdapDirInitializer.intializeDir( embeddedLdapServerController.getServerContext() );
} catch (NamingException e) {
System.out.println("Error: unable to initialize LDAP Server for Unit tests.");
System.out.println(" Unable to continue testing LDAP Authentication Dao without LDAP Server.");
e.printStackTrace();
}
}
/** Returns a 'client' connection to the embedded LDAP Server, using
* JNDI to connect.
*/
protected DirContext getClientContext() throws NamingException {
Hashtable env = new Hashtable();
env.put(Context.PROVIDER_URL, "ldap://localhost:389/ou=system");
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
env.put(Context.SECURITY_CREDENTIALS, "secret");
return new InitialDirContext(env);
}
/**
* This is a LDAP DirContext which connects directly to the
* embedded Apache Directory Server against which the Unit tests
* are run, as such the normal Unit tests should never need to
* reference it (with the possible exception of comparing return values
* between the Server Context and the Client Context).
*
* @see org.acegisecurity.providers.dao.ldap.support.EmbeddedLdapServerController
* @see org.acegisecurity.providers.dao.ldap.support.LdapDirInitializer
*
* @return The server context for LDAP operations; used for things like
* addding/removing users to to test against.
*/
protected DirContext getServerContext() {
return embeddedLdapServerController.getServerContext();
}
}

View File

@ -1,228 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.providers.dao.ldap.support;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import org.acegisecurity.providers.ldap.LdapUtils;
import org.apache.ldap.common.ldif.LdifIterator;
import org.apache.ldap.common.ldif.LdifParser;
import org.apache.ldap.common.ldif.LdifParserImpl;
import org.apache.ldap.common.message.LockableAttributesImpl;
import org.apache.ldap.common.name.LdapName;
import org.apache.ldap.server.DirectoryService;
import org.apache.ldap.server.configuration.MutableServerStartupConfiguration;
import org.apache.ldap.server.configuration.ShutdownConfiguration;
import org.apache.ldap.server.jndi.ServerContextFactory;
/**
* Used as static field in BaseLdapTestCase;
* responsible for global state during JUnit tests - since
* JUnit reinstantiates the test class for every method.
*
* @version $Id$
*
*/
public class EmbeddedLdapServerController {
static final int LDAP_PORT = 10389;
private File tempDirectory;
private DirContext serverContext;
/**
*
*/
public EmbeddedLdapServerController() {
// create temporary directory for directory-server to store files in
tempDirectory = initTempFiles();
// start the apache directory server
startServer();
}
/**
* Creates if needed a temporary directory to store the apache directory
* server files. Since I can't get the class to shutdown cleanly,
* it also ensures a clean start by removing any files in the temp. directory.
*
* @return The directory that should be used to store temporary files in.
*/
protected File initTempFiles() {
String tmpDir = System.getProperty("java.io.tmpdir");
File dir = new File(tmpDir);
File tmp = new File(dir, "apacheds_tmp");
if (tmp.exists()) {
cleanupTempFiles(tmp);
} else {
tmp.mkdir();
}
System.out.println("Directory temp files at: " + tmp.getAbsolutePath());
return tmp;
}
/** Attempts to open the file and import the contents as LDIF entries
* into the test directory.
*
* @param file The LDIF file to import
* @throws IOException
* @throws NamingException
*/
// public void importLDIF(File file) throws IOException, NamingException {
// FileInputStream fis = new FileInputStream(file);
// importLDIF(fis);
// }
/** Attempts to read the provided InputStream for LDIF entries
* and adds those entries to the test directory server.
*
* @param in InputStream of LDIF data.
* @throws NamingException
* @throws IOException
*/
public void importLDIF(InputStream in) throws NamingException, IOException {
LdifParser parser = new LdifParserImpl();
LdifIterator iterator = new LdifIterator( in );
while ( iterator.hasNext() ) {
Attributes attributes = new LockableAttributesImpl();
String ldif = ( String ) iterator.next();
parser.parse( attributes, ldif );
Name dn = new LdapName( ( String ) attributes.remove( "dn" ).get() );
dn.remove( 0 );
serverContext.createSubcontext( dn, attributes );
}
}
/** starts the apache directory server. */
protected void startServer() {
System.out.println("Creating embedded LDAP server on port " + LDAP_PORT);
MutableServerStartupConfiguration startup = new MutableServerStartupConfiguration();
startup.setWorkingDirectory(tempDirectory);
startup.setLdapPort(LDAP_PORT);
Hashtable env = startup.toJndiEnvironment();
env.putAll(getEnvironment());
env.put(Context.INITIAL_CONTEXT_FACTORY, ServerContextFactory.class.getName());
try {
serverContext = new InitialDirContext( env );
} catch (NamingException nx) {
nx.printStackTrace();
}
}
/**
* Stops the apache directory server, and attempts to remove
* the data files that the server creates.
*/
protected void shutdownServer() {
// close our internal instance of the server-context
LdapUtils.closeContext(serverContext);
serverContext = null;
// signal the server that its time to say goodbye
Hashtable env = new ShutdownConfiguration().toJndiEnvironment();
env.putAll(getEnvironment());
try {
new InitialContext( env );
} catch (NamingException e) {
e.printStackTrace();
}
}
/**
* Utility method to remove any files in the temporary directory
* that we use to store the directory server's data files.
*
* @param tempDir The temporary directory.
*/
protected void cleanupTempFiles(File tempDir) {
if ((null != tempDir) && (tempDir.exists())) {
File[] files = tempDir.listFiles();
for (int i = 0; i < files.length; i++) {
if (!files[i].delete()) {
System.err.println("Error: unable to cleanup Apache Directory Server file: " + files[i]);
}
}
}
}
/**
* This isn't working, probably because I am referencing the class
* as a static field, but maybe someone can figure out a way to
* implement this correctly.
*/
public void finalize() throws Throwable {
System.out.println("Entering EmbeddedLdapServerController.finalize()");
shutdownServer();
cleanupTempFiles(tempDirectory);
tempDirectory.delete();
super.finalize();
System.out.println("Leaving EmbeddedLdapServerController.finalize()");
}
/**
* @return The directory that the directory server will use to store its data files.
*/
// public File getTempDirectory() {
// return tempDirectory;
// }
/**
* @return The directory that the directory server will use to store its data files.
*/
// public String getTempDirectoryPath() {
// return tempDirectory.getAbsolutePath();
// }
/** Create and return a Hashtable with standard JNDI settings for our tests. */
protected Properties getEnvironment() {
Properties env = new Properties();
env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
env.setProperty(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
env.setProperty(Context.SECURITY_CREDENTIALS,"secret");
// env.setProperty(Context.INITIAL_CONTEXT_FACTORY, CoreContextFactory.class.getName());
env.setProperty( Context.PROVIDER_URL, "ou=system" );
// env.put( EnvKeys.WKDIR, tempDirectory.getAbsolutePath() );
return env;
}
/** Get our reference to the server-mode context. */
public DirContext getServerContext() {
return serverContext;
}
public static void main(String[] args) throws IOException {
EmbeddedLdapServerController server = new EmbeddedLdapServerController();
System.out.println(DirectoryService.getInstance());
}
}

View File

@ -1,123 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.acegisecurity.providers.dao.ldap.support;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
/** Container for a bunch of methods begining with 'dirInit' and taking
* a JNDI DirContext, which are used to construct the initial state
* of the EmbeddedServer <b>before</b> Unit tests are run.
*
* @TODO Externalize this into a LDIF resource file(s); I would have done this, but
* I can't seem to get this to work in both Eclipse and Maven at the same time.
*
* @author robert.sanders
*
*/
public class LdapDirInitializer {
public static void intializeDir(DirContext ctx) throws NamingException {
LdapDirInitializer ldi = new LdapDirInitializer();
ldi.dirInit_SimpleUidUser(ctx);
ldi.dirInit_SimpleCnUser(ctx);
ldi.dirInit_OuOthers(ctx);
ldi.dirInit_UserNamedOtherOne(ctx);
ldi.dirInit_UserNamedOtherTwo(ctx);
}
private void dirInit_SimpleUidUser(DirContext ctx) throws NamingException {
String name = "uid=one.user,ou=users";
Attributes attrs = new BasicAttributes();
attrs.put("dn", name + ",ou=system");
attrs.put("cn", "User One");
attrs.put("sn", "One");
attrs.put("givenName", "User");
attrs.put("uid", "user.one");
attrs.put("mail", "one.user@hotmail.com");
attrs.put("userPassword", "plaintext");
attrs.put("objectClass", "inetOrgPerson");
attrs.put("objectClass", "top");
ctx.createSubcontext(name, attrs);
}
private void dirInit_SimpleCnUser(DirContext ctx) throws NamingException {
String name = "cn=User Two,ou=users";
Attributes attrs = new BasicAttributes();
attrs.put("dn", name + ",ou=system");
attrs.put("cn", "Two User");
attrs.put("givenName", "Two");
attrs.put("sn", "User");
attrs.put("uid", "user.two");
attrs.put("mail", "user.two@hotmail.com");
attrs.put("userPassword", "plaintext2");
attrs.put("objectClass", "inetOrgPerson");
attrs.put("objectClass", "top");
ctx.createSubcontext(name, attrs);
}
private void dirInit_UserNamedOtherOne(DirContext ctx) throws NamingException {
String name = "uid=other.one,ou=others";
Attributes attrs = new BasicAttributes();
attrs.put("dn", name + ",ou=system");
attrs.put("cn", "Other One");
attrs.put("givenName", "Other");
attrs.put("sn", "One");
attrs.put("uid", "other.one");
attrs.put("mail", "other.one@hotmail.com");
attrs.put("userPassword", "otherone");
attrs.put("objectClass", "inetOrgPerson");
attrs.put("objectClass", "top");
ctx.createSubcontext(name, attrs);
}
private void dirInit_UserNamedOtherTwo(DirContext ctx) throws NamingException {
String name = "uid=other.two,ou=others";
Attributes attrs = new BasicAttributes();
attrs.put("dn", name + ",ou=system");
attrs.put("cn", "Other Two");
attrs.put("givenName", "Other");
attrs.put("sn", "Two");
attrs.put("uid", "other.two");
attrs.put("mail", "other.two@hotmail.com");
attrs.put("userPassword", "othertwo");
attrs.put("objectClass", "inetOrgPerson");
attrs.put("objectClass", "top");
ctx.createSubcontext(name, attrs);
}
private void dirInit_OuOthers(DirContext ctx) throws NamingException {
String otherUserOU = "ou=Others";
Attributes attrs = new BasicAttributes();
attrs.put("dn", otherUserOU + ",ou=system");
attrs.put("ou", "others");
attrs.put("objectClass", "top");
attrs.put("objectClass", "organizationalUnit");
ctx.createSubcontext(otherUserOU, attrs);
}
}