You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@directory.apache.org by ka...@apache.org on 2010/08/20 21:32:02 UTC
svn commit: r987611 [12/13] - in /directory/apacheds/trunk: ./ all/
core-annotations/ core-api/
core-api/src/main/java/org/apache/directory/server/core/
core-api/src/main/java/org/apache/directory/server/core/event/
core-api/src/main/java/org/apache/di...
Modified: directory/apacheds/trunk/server-config/src/main/java/org/apache/directory/server/config/LdifConfigExtractor.java
URL: http://svn.apache.org/viewvc/directory/apacheds/trunk/server-config/src/main/java/org/apache/directory/server/config/LdifConfigExtractor.java?rev=987611&r1=987610&r2=987611&view=diff
==============================================================================
--- directory/apacheds/trunk/server-config/src/main/java/org/apache/directory/server/config/LdifConfigExtractor.java (original)
+++ directory/apacheds/trunk/server-config/src/main/java/org/apache/directory/server/config/LdifConfigExtractor.java Fri Aug 20 19:31:58 2010
@@ -51,12 +51,12 @@ import org.slf4j.LoggerFactory;
*/
public class LdifConfigExtractor
{
-
+
private static final String CONFIG_SUBDIR = "config";
-
+
private static final Logger LOG = LoggerFactory.getLogger( LdifConfigExtractor.class );
-
-
+
+
/**
* Extracts the LDIF files from a Jar file or copies exploded LDIF resources.
*
@@ -70,7 +70,7 @@ public class LdifConfigExtractor
LOG.debug( "creating non existing output directory {}", outputDirectory.getAbsolutePath() );
outputDirectory.mkdir();
}
-
+
File configDirectory = new File( outputDirectory, CONFIG_SUBDIR );
if ( !configDirectory.exists() )
@@ -85,7 +85,7 @@ public class LdifConfigExtractor
LOG.debug( "extracting the configuration to the directory at {}", configDirectory.getAbsolutePath() );
- Pattern pattern = Pattern.compile( ".*config/ou=config.*\\.ldif" );
+ Pattern pattern = Pattern.compile( ".*config" + File.separator + "ou=config.*\\.ldif" );
Map<String, Boolean> list = ResourceMap.getResources( pattern );
for ( Entry<String, Boolean> entry : list.entrySet() )
@@ -102,7 +102,7 @@ public class LdifConfigExtractor
}
}
-
+
/**
* Copies a file line by line from the source file argument to the
* destination file argument.
@@ -114,30 +114,31 @@ public class LdifConfigExtractor
private static void copyFile( File source, File destination ) throws IOException
{
LOG.debug( "copyFile(): source = {}, destination = {}", source, destination );
-
- if ( ! destination.getParentFile().exists() )
+
+ if ( !destination.getParentFile().exists() )
{
destination.getParentFile().mkdirs();
}
-
- if ( ! source.getParentFile().exists() )
+
+ if ( !source.getParentFile().exists() )
{
throw new FileNotFoundException( I18n.err( I18n.ERR_509, source.getAbsolutePath() ) );
}
-
+
FileWriter out = new FileWriter( destination );
BufferedReader in = new BufferedReader( new FileReader( source ) );
String line;
while ( null != ( line = in.readLine() ) )
{
- out.write( line + "\n" );
+ out.write( line + "\n" );
}
-
+
in.close();
out.flush();
out.close();
}
+
/**
* Extracts the LDIF schema resource from a Jar.
*
@@ -161,12 +162,12 @@ public class LdifConfigExtractor
{
return;
}
-
- if ( ! destination.getParentFile().exists() )
+
+ if ( !destination.getParentFile().exists() )
{
destination.getParentFile().mkdirs();
}
-
+
FileOutputStream out = new FileOutputStream( destination );
try
{
@@ -176,7 +177,7 @@ public class LdifConfigExtractor
out.write( buf, 0, readCount );
}
out.flush();
- }
+ }
finally
{
out.close();
@@ -188,7 +189,7 @@ public class LdifConfigExtractor
}
}
-
+
/**
* Calculates the destination file.
*
@@ -200,7 +201,7 @@ public class LdifConfigExtractor
File parent = resource.getParentFile();
Stack<String> fileComponentStack = new Stack<String>();
fileComponentStack.push( resource.getName() );
-
+
while ( parent != null )
{
if ( parent.getName().equals( "config" ) )
@@ -209,24 +210,24 @@ public class LdifConfigExtractor
// config/config base path. So we need to add one more
// schema component to all LDIF files minus this config.ldif
fileComponentStack.push( "config" );
-
+
return assembleDestinationFile( outputDirectory, fileComponentStack );
}
fileComponentStack.push( parent.getName() );
-
- if ( parent.equals( parent.getParentFile() )
- || parent.getParentFile() == null )
+
+ if ( parent.equals( parent.getParentFile() ) || parent.getParentFile() == null )
{
throw new IllegalStateException( I18n.err( I18n.ERR_510 ) );
}
-
+
parent = parent.getParentFile();
}
throw new IllegalStateException( I18n.err( I18n.ERR_511 ) );
}
+
/**
* Assembles the destination file by appending file components previously
* pushed on the fileComponentStack argument.
@@ -237,12 +238,12 @@ public class LdifConfigExtractor
private static File assembleDestinationFile( File outputDirectory, Stack<String> fileComponentStack )
{
File destinationFile = outputDirectory.getAbsoluteFile();
-
- while ( ! fileComponentStack.isEmpty() )
+
+ while ( !fileComponentStack.isEmpty() )
{
destinationFile = new File( destinationFile, fileComponentStack.pop() );
}
-
+
return destinationFile;
}
Propchange: directory/apacheds/trunk/server-config/src/main/resources/
------------------------------------------------------------------------------
--- svn:mergeinfo (original)
+++ svn:mergeinfo Fri Aug 20 19:31:58 2010
@@ -1,4 +1,5 @@
-/directory/apacheds/branches/apacheds-cidit/default-config/src/main/resources:897934-899975
+/directory/apacheds/branches/apacheds-cidit/default-config/src/main/resources:897934-898678
+/directory/apacheds/branches/apacheds-codec-merge/server-config/src/main/resources:982369-987590
/directory/apacheds/branches/apacheds-dnfactory-experiment/server-config/src/main/resources:980138-980938
/directory/apacheds/branches/apacheds-replication/core-annotations/src/main/resources:749790-764110
/directory/apacheds/branches/apacheds-replication/default-config/src/main/resources:749790-764110
@@ -6,4 +7,3 @@
/directory/apacheds/branches/apacheds-schema/default-config/src/main/resources:806623-896441
/directory/apacheds/branches/apacheds-subtree/server-config/src/main/resources:965203-965686
/directory/apacheds/branches/xdbm-refactoring/default-config/src/main/resources:945827-946347
-/directory/apacheds/trunk/server-config/src/main/resources:980025-980137
Propchange: directory/apacheds/trunk/server-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java
------------------------------------------------------------------------------
--- svn:mergeinfo (original)
+++ svn:mergeinfo Fri Aug 20 19:31:58 2010
@@ -1,7 +1,8 @@
+/directory/apacheds/branches/apacheds-cidit/default-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java:898675-899143
+/directory/apacheds/branches/apacheds-codec-merge/server-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java:982369-987590
/directory/apacheds/branches/apacheds-dnfactory-experiment/server-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java:980138-980938
/directory/apacheds/branches/apacheds-replication/core-annotations/src/main/java/org/apache/directory/server/core/factory/CiDITDirectoryServiceFactory.java:749790-764110
/directory/apacheds/branches/apacheds-schema/core-annotations/src/main/java/org/apache/directory/server/core/factory/CiDITDirectoryServiceFactory.java:806623-896441
/directory/apacheds/branches/apacheds-subtree/server-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java:965203-965686
/directory/apacheds/branches/cidit/default-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java:900288-900681
/directory/apacheds/branches/xdbm-refactoring/default-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java:945827-946347
-/directory/apacheds/trunk/server-config/src/test/java/org/apache/directory/server/config/ConfigPartitionReaderTest.java:980025-980137
Propchange: directory/apacheds/trunk/server-integ/
------------------------------------------------------------------------------
--- svn:mergeinfo (original)
+++ svn:mergeinfo Fri Aug 20 19:31:58 2010
@@ -1 +1,2 @@
+/directory/apacheds/branches/apacheds-codec-merge/server-integ:982369-987590
/directory/apacheds/branches/apacheds-dnfactory-experiment/server-integ:980138-980937
Modified: directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/add/AddIT.java
URL: http://svn.apache.org/viewvc/directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/add/AddIT.java?rev=987611&r1=987610&r2=987611&view=diff
==============================================================================
--- directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/add/AddIT.java (original)
+++ directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/add/AddIT.java Fri Aug 20 19:31:58 2010
@@ -63,7 +63,6 @@ import netscape.ldap.LDAPResponseListene
import netscape.ldap.LDAPSearchConstraints;
import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.message.SearchResultEntry;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.constants.ServerDNConstants;
@@ -87,6 +86,7 @@ import org.apache.directory.shared.ldap.
import org.apache.directory.shared.ldap.entry.EntryAttribute;
import org.apache.directory.shared.ldap.ldif.LdifUtils;
import org.apache.directory.shared.ldap.message.ResultCodeEnum;
+import org.apache.directory.shared.ldap.message.SearchResultEntry;
import org.apache.directory.shared.ldap.name.DN;
import org.apache.directory.shared.ldap.util.StringTools;
import org.junit.Test;
@@ -100,84 +100,46 @@ import org.slf4j.LoggerFactory;
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
-@RunWith ( FrameworkRunner.class )
-@CreateDS( allowAnonAccess=true, name="AddIT-class",
- partitions =
- {
- @CreatePartition(
- name = "example",
- suffix = "dc=example,dc=com",
- contextEntry = @ContextEntry(
- entryLdif =
- "dn: dc=example,dc=com\n" +
- "dc: example\n" +
- "objectClass: top\n" +
- "objectClass: domain\n\n" ),
- indexes =
- {
- @CreateIndex( attribute = "objectClass" ),
- @CreateIndex( attribute = "dc" ),
- @CreateIndex( attribute = "ou" )
- } ),
-
- @CreatePartition(
- name = "directory",
- suffix = "dc=directory,dc=apache,dc=org",
- contextEntry = @ContextEntry(
- entryLdif =
- "dn: dc=directory,dc=apache,dc=org\n"+
- "dc: directory\n"+
- "objectClass: top\n"+
- "objectClass: domain\n\n" ),
- indexes =
- {
- @CreateIndex( attribute = "objectClass" ),
- @CreateIndex( attribute = "dc" ),
- @CreateIndex( attribute = "ou" )
- } )
- })
-@CreateLdapServer (
- transports =
- {
- @CreateTransport( protocol = "LDAP" )
- })
-@ApplyLdifs( {
- // Entry # 0
- "dn: cn=The Person,ou=system",
- "objectClass: person",
- "objectClass: top",
- "cn: The Person",
- "description: this is a person",
- "sn: Person",
-
- // Entry # 1
- "dn: uid=akarasulu,ou=users,ou=system",
- "objectClass: uidObject",
- "objectClass: person",
- "objectClass: top",
- "uid: akarasulu",
- "cn: Alex Karasulu",
- "sn: karasulu",
-
- // Entry # 2
- "dn: ou=Computers,uid=akarasulu,ou=users,ou=system",
- "objectClass: organizationalUnit",
- "objectClass: top",
- "ou: computers",
- "description: Computers for Alex",
- "seeAlso: ou=Machines,uid=akarasulu,ou=users,ou=system",
-
- // Entry # 3
- "dn: uid=akarasuluref,ou=users,ou=system",
- "objectClass: uidObject",
- "objectClass: referral",
- "objectClass: top",
- "uid: akarasuluref",
- "ref: ldap://localhost:10389/uid=akarasulu,ou=users,ou=system",
- "ref: ldap://foo:10389/uid=akarasulu,ou=users,ou=system",
- "ref: ldap://bar:10389/uid=akarasulu,ou=users,ou=system"
- }
-)
+@RunWith(FrameworkRunner.class)
+@CreateDS(allowAnonAccess = true, name = "AddIT-class", partitions =
+ {
+ @CreatePartition(name = "example", suffix = "dc=example,dc=com", contextEntry = @ContextEntry(entryLdif = "dn: dc=example,dc=com\n"
+ + "dc: example\n" + "objectClass: top\n" + "objectClass: domain\n\n"), indexes =
+ { @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"), @CreateIndex(attribute = "ou") }),
+
+ @CreatePartition(name = "directory", suffix = "dc=directory,dc=apache,dc=org", contextEntry = @ContextEntry(entryLdif = "dn: dc=directory,dc=apache,dc=org\n"
+ + "dc: directory\n" + "objectClass: top\n" + "objectClass: domain\n\n"), indexes =
+ { @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"), @CreateIndex(attribute = "ou") }) })
+@CreateLdapServer(transports =
+ { @CreateTransport(protocol = "LDAP") })
+@ApplyLdifs(
+ {
+ // Entry # 0
+ "dn: cn=The Person,ou=system",
+ "objectClass: person",
+ "objectClass: top",
+ "cn: The Person",
+ "description: this is a person",
+ "sn: Person",
+
+ // Entry # 1
+ "dn: uid=akarasulu,ou=users,ou=system", "objectClass: uidObject", "objectClass: person",
+ "objectClass: top",
+ "uid: akarasulu",
+ "cn: Alex Karasulu",
+ "sn: karasulu",
+
+ // Entry # 2
+ "dn: ou=Computers,uid=akarasulu,ou=users,ou=system", "objectClass: organizationalUnit", "objectClass: top",
+ "ou: computers",
+ "description: Computers for Alex",
+ "seeAlso: ou=Machines,uid=akarasulu,ou=users,ou=system",
+
+ // Entry # 3
+ "dn: uid=akarasuluref,ou=users,ou=system", "objectClass: uidObject", "objectClass: referral",
+ "objectClass: top", "uid: akarasuluref", "ref: ldap://localhost:10389/uid=akarasulu,ou=users,ou=system",
+ "ref: ldap://foo:10389/uid=akarasulu,ou=users,ou=system",
+ "ref: ldap://bar:10389/uid=akarasulu,ou=users,ou=system" })
public class AddIT extends AbstractLdapTestUnit
{
private static final Logger LOG = LoggerFactory.getLogger( AddIT.class );
@@ -186,7 +148,8 @@ public class AddIT extends AbstractLdapT
private static final String BASE = "ou=system";
private static final String BASE_EXAMPLE_COM = "dc=example,dc=com";
private static final String BASE_DIRECTORY_APACHE_ORG = "dc=directory,dc=apache,dc=org";
-
+
+
/**
* This is the original defect as in JIRA DIREVE-216.
*
@@ -198,8 +161,7 @@ public class AddIT extends AbstractLdapT
DirContext ctx = ( DirContext ) getWiredContext( ldapServer ).lookup( BASE );
// modify object classes, add two more
- Attributes attributes = LdifUtils.createAttributes(
- "objectClass: organizationalPerson",
+ Attributes attributes = LdifUtils.createAttributes( "objectClass: organizationalPerson",
"objectClass: inetOrgPerson" );
DirContext person = ( DirContext ) ctx.lookup( RDN );
@@ -210,7 +172,8 @@ public class AddIT extends AbstractLdapT
attributes = person.getAttributes( "" );
Attribute newOcls = attributes.get( "objectClass" );
- String[] expectedOcls = { "top", "person", "organizationalPerson", "inetOrgPerson" };
+ String[] expectedOcls =
+ { "top", "person", "organizationalPerson", "inetOrgPerson" };
for ( String name : expectedOcls )
{
@@ -276,8 +239,8 @@ public class AddIT extends AbstractLdapT
// expected
}
}
-
-
+
+
/**
* Test case to demonstrate DIRSERVER-643 ("Netscape SDK: Adding an entry with
* two description attributes does not combine values."). Uses Sun ONE Directory
@@ -289,7 +252,7 @@ public class AddIT extends AbstractLdapT
public void testAddEntryWithTwoDescriptions() throws Exception
{
LdapConnection con = getClientApiConnection( ldapServer );
-
+
String dn = "cn=Kate Bush," + BASE;
Entry kate = new DefaultEntry( new DN( dn ) );
@@ -346,7 +309,7 @@ public class AddIT extends AbstractLdapT
con.add( kate );
// Analyze entry and description attribute
- Entry kateReloaded = ( (SearchResultEntry ) con.lookup( dn ) ).getEntry();
+ Entry kateReloaded = ( ( SearchResultEntry ) con.lookup( dn ) ).getEntry();
assertNotNull( kateReloaded );
EntryAttribute attr = kateReloaded.get( "description" );
assertNotNull( attr );
@@ -372,7 +335,7 @@ public class AddIT extends AbstractLdapT
String dn = "cn=Kate Bush," + BASE;
Entry kate = new DefaultEntry( new DN( dn ) );
-
+
kate.add( "objectclass", "top", "person" );
kate.add( "sn", "Bush" );
@@ -398,7 +361,7 @@ public class AddIT extends AbstractLdapT
con.unBind();
}
-
+
/**
* Try to add entry with invalid number of values for a single-valued attribute
*
@@ -409,7 +372,7 @@ public class AddIT extends AbstractLdapT
public void testAddWithInvalidNumberOfAttributeValues() throws Exception
{
DirContext ctx = ( DirContext ) getWiredContext( ldapServer ).lookup( BASE );
-
+
// add inetOrgPerson with two displayNames
Attributes attrs = new BasicAttributes( true );
Attribute ocls = new BasicAttribute( "objectClass" );
@@ -545,7 +508,7 @@ public class AddIT extends AbstractLdapT
sr = ne.next();
assertEquals( "ou=favorite", sr.getName() );
assertFalse( ne.hasMore() );
-
+
// search with base set to alias and dereferencing turned on
controls = new SearchControls();
controls.setDerefLinkFlag( false );
@@ -554,9 +517,9 @@ public class AddIT extends AbstractLdapT
ne = containerCtx.search( "ou=bestFruit", "(objectClass=*)", controls );
assertTrue( ne.hasMore() );
sr = ne.next();
- assertEquals( "ldap://localhost:"+ ldapServer.getPort() +"/ou=favorite,ou=Fruits,ou=system", sr.getName() );
+ assertEquals( "ldap://localhost:" + ldapServer.getPort() + "/ou=favorite,ou=Fruits,ou=system", sr.getName() );
assertFalse( ne.hasMore() );
-
+
// Remove alias and entry
containerCtx.destroySubcontext( rdnAlias );
containerCtx.destroySubcontext( entryRdn );
@@ -564,8 +527,8 @@ public class AddIT extends AbstractLdapT
// Remove container
ctx.destroySubcontext( containerRdn );
}
-
-
+
+
/**
* Try to add entry and an alias to it. Afterwards, remove it. Taken from
* DIRSERVER-1157 test contribution.
@@ -704,13 +667,13 @@ public class AddIT extends AbstractLdapT
constraints.setClientControls( new LDAPControl( LDAPControl.MANAGEDSAIT, true, new byte[0] ) );
constraints.setServerControls( new LDAPControl( LDAPControl.MANAGEDSAIT, true, new byte[0] ) );
conn.setConstraints( constraints );
-
+
// add success
LDAPAttributeSet attrSet = new LDAPAttributeSet();
attrSet.add( new LDAPAttribute( "objectClass", "organizationalUnit" ) );
attrSet.add( new LDAPAttribute( "ou", "UnderReferral" ) );
LDAPEntry entry = new LDAPEntry( "ou=UnderReferral,uid=akarasuluref,ou=users,ou=system", attrSet );
-
+
try
{
conn.add( entry, constraints );
@@ -718,57 +681,56 @@ public class AddIT extends AbstractLdapT
}
catch ( LDAPException le )
{
- assertEquals( 10, le.getLDAPResultCode() );
+ assertEquals( ResultCodeEnum.REFERRAL.getValue(), le.getLDAPResultCode() );
}
-
+
try
{
- conn.read( "ou=UnderReferral,uid=akarasuluref,ou=users,ou=system",
- ( LDAPSearchConstraints ) constraints );
+ conn.read( "ou=UnderReferral,uid=akarasuluref,ou=users,ou=system", ( LDAPSearchConstraints ) constraints );
fail();
}
catch ( LDAPException le )
{
-
+
}
-
+
conn.disconnect();
}
-
-
- public static LdapContext getContext( String principalDn, DirectoryService service, String dn )
- throws Exception
+
+
+ public static LdapContext getContext( String principalDn, DirectoryService service, String dn ) throws Exception
{
if ( principalDn == null )
{
principalDn = "";
}
-
+
DN userDn = new DN( principalDn, service.getSchemaManager() );
LdapPrincipal principal = new LdapPrincipal( userDn, AuthenticationLevel.SIMPLE );
-
+
if ( dn == null )
{
dn = "";
}
-
+
CoreSession session = service.getSession( principal );
LdapContext ctx = new ServerLdapContext( service, session, new LdapName( dn ) );
return ctx;
}
-
-
+
+
/**
* Tests add operation on referral entry with the ManageDsaIT control.
*/
@Test
public void testOnReferralWitJNDIIgnore() throws Exception
{
- LdapContext MNNCtx = getContext( ServerDNConstants.ADMIN_SYSTEM_DN, ldapServer.getDirectoryService(), "uid=akarasuluref,ou=users,ou=system" );
+ LdapContext MNNCtx = getContext( ServerDNConstants.ADMIN_SYSTEM_DN, ldapServer.getDirectoryService(),
+ "uid=akarasuluref,ou=users,ou=system" );
// Set to 'ignore'
MNNCtx.addToEnvironment( Context.REFERRAL, "ignore" );
-
+
try
{
// JNDI entry
@@ -785,12 +747,12 @@ public class AddIT extends AbstractLdapT
assertTrue( true );
}
}
-
-
+
+
/**
* Tests referral handling when an ancestor is a referral.
*/
- @Test
+ @Test
public void testAncestorReferral() throws Exception
{
LOG.debug( "" );
@@ -804,22 +766,22 @@ public class AddIT extends AbstractLdapT
attrSet.add( new LDAPAttribute( "objectClass", "organizationalUnit" ) );
attrSet.add( new LDAPAttribute( "ou", "UnderReferral" ) );
LDAPEntry entry = new LDAPEntry( "ou=UnderReferral,ou=Computers,uid=akarasuluref,ou=users,ou=system", attrSet );
-
+
LDAPResponseListener listener = conn.add( entry, null, constraints );
LDAPResponse response = listener.getResponse();
assertEquals( ResultCodeEnum.REFERRAL.getValue(), response.getResultCode() );
- assertEquals( "ldap://localhost:10389/ou=UnderReferral,ou=Computers,uid=akarasulu,ou=users,ou=system",
- response.getReferrals()[0] );
- assertEquals( "ldap://foo:10389/ou=UnderReferral,ou=Computers,uid=akarasulu,ou=users,ou=system",
- response.getReferrals()[1] );
- assertEquals( "ldap://bar:10389/ou=UnderReferral,ou=Computers,uid=akarasulu,ou=users,ou=system",
- response.getReferrals()[2] );
+ assertEquals( "ldap://localhost:10389/ou=UnderReferral,ou=Computers,uid=akarasulu,ou=users,ou=system", response
+ .getReferrals()[0] );
+ assertEquals( "ldap://foo:10389/ou=UnderReferral,ou=Computers,uid=akarasulu,ou=users,ou=system", response
+ .getReferrals()[1] );
+ assertEquals( "ldap://bar:10389/ou=UnderReferral,ou=Computers,uid=akarasulu,ou=users,ou=system", response
+ .getReferrals()[2] );
conn.disconnect();
}
-
+
/**
* Tests add operation on normal and referral entries without the
* ManageDsaIT control. Referrals are sent back to the client with a
@@ -832,14 +794,14 @@ public class AddIT extends AbstractLdapT
LDAPConstraints constraints = new LDAPConstraints();
constraints.setReferrals( false );
conn.setConstraints( constraints );
-
+
// referrals failure
LDAPAttributeSet attrSet = new LDAPAttributeSet();
attrSet.add( new LDAPAttribute( "objectClass", "organizationalUnit" ) );
attrSet.add( new LDAPAttribute( "ou", "UnderReferral" ) );
LDAPEntry entry = new LDAPEntry( "ou=UnderReferral,uid=akarasuluref,ou=users,ou=system", attrSet );
-
+
LDAPResponseListener listener = null;
LDAPResponse response = null;
listener = conn.add( entry, null, constraints );
@@ -847,14 +809,15 @@ public class AddIT extends AbstractLdapT
assertEquals( ResultCodeEnum.REFERRAL.getValue(), response.getResultCode() );
- assertEquals( "ldap://localhost:10389/ou=UnderReferral,uid=akarasulu,ou=users,ou=system", response.getReferrals()[0] );
+ assertEquals( "ldap://localhost:10389/ou=UnderReferral,uid=akarasulu,ou=users,ou=system", response
+ .getReferrals()[0] );
assertEquals( "ldap://foo:10389/ou=UnderReferral,uid=akarasulu,ou=users,ou=system", response.getReferrals()[1] );
assertEquals( "ldap://bar:10389/ou=UnderReferral,uid=akarasulu,ou=users,ou=system", response.getReferrals()[2] );
conn.disconnect();
}
-
-
+
+
/**
* Tests add operation on normal and referral entries without the
* ManageDsaIT control using JNDI instead of the Netscape API. Referrals
@@ -867,19 +830,20 @@ public class AddIT extends AbstractLdapT
SearchControls controls = new SearchControls();
controls.setReturningAttributes( new String[0] );
controls.setSearchScope( SearchControls.OBJECT_SCOPE );
-
+
// add failure
Attributes attrs = new BasicAttributes( "objectClass", "organizationalUnit", true );
attrs.put( "ou", "UnderReferral" );
-
+
try
{
ctx.createSubcontext( "ou=UnderReferral,uid=akarasuluref,ou=users,ou=system", attrs );
fail( "Should never get here: add should fail with ReferralExcpetion" );
}
- catch( ReferralException e )
+ catch ( ReferralException e )
{
- assertEquals( "ldap://localhost:10389/ou=UnderReferral,uid=akarasulu,ou=users,ou=system", e.getReferralInfo() );
+ assertEquals( "ldap://localhost:10389/ou=UnderReferral,uid=akarasulu,ou=users,ou=system", e
+ .getReferralInfo() );
}
ctx.close();
@@ -902,7 +866,7 @@ public class AddIT extends AbstractLdapT
attrs.put( "givenName", "Jim" );
attrs.put( "sn", "Bean" );
attrs.put( "cn", "\"Jim, Bean\"" );
-
+
ctx.createSubcontext( "cn=\"Jim, Bean\"", attrs );
}
@@ -914,7 +878,7 @@ public class AddIT extends AbstractLdapT
public void testAddEntryNoRDNInEntry() throws Exception
{
DirContext ctx = ( DirContext ) getWiredContext( ldapServer ).lookup( BASE );
-
+
// Create a person
Attributes person = new BasicAttributes( "objectClass", "inetOrgPerson", true );
person.get( "objectClass" ).add( "top" );
@@ -924,22 +888,23 @@ public class AddIT extends AbstractLdapT
person.put( "cn", "Jackson" );
DirContext michaelCtx = ctx.createSubcontext( "givenname=Michael", person );
-
+
assertNotNull( michaelCtx );
-
+
DirContext jackson = ( DirContext ) ctx.lookup( "givenname=Michael" );
person = jackson.getAttributes( "" );
Attribute newOcls = person.get( "objectClass" );
- String[] expectedOcls = { "top", "person", "organizationalPerson", "inetOrgPerson" };
+ String[] expectedOcls =
+ { "top", "person", "organizationalPerson", "inetOrgPerson" };
for ( String name : expectedOcls )
{
assertTrue( "object class " + name + " is present", newOcls.contains( name ) );
}
-
+
Attribute givenName = person.get( "givenname" );
-
+
assertEquals( "Michael", givenName.get() );
}
@@ -952,7 +917,7 @@ public class AddIT extends AbstractLdapT
public void testAddEntryDifferentRDNInEntry() throws Exception
{
DirContext ctx = ( DirContext ) getWiredContext( ldapServer ).lookup( BASE );
-
+
// Create a person
Attributes person = new BasicAttributes( "objectClass", "inetOrgPerson", true );
person.get( "objectClass" ).add( "top" );
@@ -963,24 +928,26 @@ public class AddIT extends AbstractLdapT
person.put( "cn", "Jackson" );
DirContext michaelCtx = ctx.createSubcontext( "cn=Michael", person );
-
+
assertNotNull( michaelCtx );
-
+
DirContext jackson = ( DirContext ) ctx.lookup( "cn=Michael" );
person = jackson.getAttributes( "" );
Attribute newOcls = person.get( "objectClass" );
- String[] expectedOcls = { "top", "person", "organizationalPerson", "inetOrgPerson" };
+ String[] expectedOcls =
+ { "top", "person", "organizationalPerson", "inetOrgPerson" };
for ( String name : expectedOcls )
{
assertTrue( "object class " + name + " is present", newOcls.contains( name ) );
}
-
+
Attribute cn = person.get( "cn" );
-
+
assertEquals( 2, cn.size() );
- String[] expectedCns = { "Jackson", "Michael" };
+ String[] expectedCns =
+ { "Jackson", "Michael" };
for ( String name : expectedCns )
{
@@ -997,7 +964,7 @@ public class AddIT extends AbstractLdapT
public void testAddEntryDifferentRDNSingleValuedInEntry() throws Exception
{
DirContext ctx = ( DirContext ) getWiredContext( ldapServer ).lookup( BASE );
-
+
// Create a person
Attributes person = new BasicAttributes( "objectClass", "inetOrgPerson", true );
person.get( "objectClass" ).add( "top" );
@@ -1008,23 +975,24 @@ public class AddIT extends AbstractLdapT
person.put( "cn", "Jackson" );
DirContext michaelCtx = ctx.createSubcontext( "displayName=test", person );
-
+
assertNotNull( michaelCtx );
-
+
DirContext jackson = ( DirContext ) ctx.lookup( "displayName=test" );
person = jackson.getAttributes( "" );
Attribute newOcls = person.get( "objectClass" );
- String[] expectedOcls = { "top", "person", "organizationalPerson", "inetOrgPerson" };
+ String[] expectedOcls =
+ { "top", "person", "organizationalPerson", "inetOrgPerson" };
for ( String name : expectedOcls )
{
assertTrue( "object class " + name + " is present", newOcls.contains( name ) );
}
-
+
// Check that the displayName attribute has been replaced
Attribute displayName = person.get( "displayName" );
-
+
assertEquals( 1, displayName.size() );
assertTrue( displayName.contains( "test" ) );
}
@@ -1038,7 +1006,7 @@ public class AddIT extends AbstractLdapT
public void testAddEntryComposedRDN() throws Exception
{
DirContext ctx = ( DirContext ) getWiredContext( ldapServer ).lookup( BASE );
-
+
// Create a person
Attributes person = new BasicAttributes( "objectClass", "inetOrgPerson", true );
person.get( "objectClass" ).add( "top" );
@@ -1048,29 +1016,30 @@ public class AddIT extends AbstractLdapT
person.put( "cn", "Jackson" );
DirContext michaelCtx = ctx.createSubcontext( "displayName=test+cn=Michael", person );
-
+
assertNotNull( michaelCtx );
-
+
DirContext jackson = ( DirContext ) ctx.lookup( "displayName=test+cn=Michael" );
person = jackson.getAttributes( "" );
Attribute newOcls = person.get( "objectClass" );
- String[] expectedOcls = { "top", "person", "organizationalPerson", "inetOrgPerson" };
+ String[] expectedOcls =
+ { "top", "person", "organizationalPerson", "inetOrgPerson" };
for ( String name : expectedOcls )
{
assertTrue( "object class " + name + " is present", newOcls.contains( name ) );
}
-
+
// Check that the DIsplayName attribute has been added
Attribute displayName = person.get( "displayName" );
-
+
assertEquals( 1, displayName.size() );
assertTrue( displayName.contains( "test" ) );
// Check that the cn attribute value has been added
Attribute cn = person.get( "cn" );
-
+
assertEquals( 2, cn.size() );
assertTrue( cn.contains( "Jackson" ) );
assertTrue( cn.contains( "Michael" ) );
@@ -1093,20 +1062,20 @@ public class AddIT extends AbstractLdapT
// modify object classes, add two more
Attributes attributes = new BasicAttributes( true );
Attribute ocls = new BasicAttribute( "description" );
-
+
// Inject a 1024 bytes long description
StringBuilder sb = new StringBuilder();
-
+
for ( int i = 0; i < 128; i++ )
{
sb.append( "0123456789ABCDEF" );
}
-
+
ocls.add( sb.toString() );
attributes.put( ocls );
DirContext person = ( DirContext ) ctx.lookup( RDN );
-
+
try
{
person.modifyAttributes( "", DirContext.ADD_ATTRIBUTE, attributes );
@@ -1116,14 +1085,14 @@ public class AddIT extends AbstractLdapT
{
// We are expecting the session to be close here.
}
-
+
// Test again with a bigger size
// Limit the PDU size to 1024
ldapServer.getDirectoryService().setMaxPDUSize( 4096 );
-
+
ctx = ( DirContext ) getWiredContext( ldapServer ).lookup( BASE );
person = ( DirContext ) ctx.lookup( RDN );
-
+
try
{
person.modifyAttributes( "", DirContext.ADD_ATTRIBUTE, attributes );
@@ -1137,7 +1106,7 @@ public class AddIT extends AbstractLdapT
// Read again from directory
ctx = ( DirContext ) getWiredContext( ldapServer ).lookup( BASE );
person = ( DirContext ) ctx.lookup( RDN );
-
+
assertNotNull( person );
attributes = person.getAttributes( "" );
Attribute newOcls = attributes.get( "objectClass" );
@@ -1210,13 +1179,13 @@ public class AddIT extends AbstractLdapT
assertTrue( userPasswordAttribute.contains( StringTools.getBytesUtf8( "ABC" ) ) );
assertFalse( res.hasMore() );
}
-
-
+
+
@Test
public void testAddEntryUUIDAndCSNAttributes() throws Exception
{
LdapConnection con = getClientApiConnection( ldapServer );
-
+
String dn = "cn=Kate Bush," + BASE;
Entry entry = new DefaultEntry( new DN( dn ) );
entry.add( "objectclass", "top", "person" );
@@ -1232,7 +1201,7 @@ public class AddIT extends AbstractLdapT
CsnFactory csnFac = new CsnFactory( 0 );
Csn csn = csnFac.newInstance();
entry.add( SchemaConstants.ENTRY_CSN_AT, csn.toString() );
-
+
con.add( entry );
// Analyze entry and description attribute
@@ -1242,19 +1211,19 @@ public class AddIT extends AbstractLdapT
EntryAttribute attr = addedEntry.get( SchemaConstants.ENTRY_UUID_AT );
assertNotNull( attr );
-
+
assertEquals( uuid.toString(), attr.getString() );
attr = addedEntry.get( SchemaConstants.ENTRY_CSN_AT );
assertNotNull( attr );
assertEquals( csn.toString(), attr.getString() );
-
+
// Remove entry
con.delete( dn );
con.unBind();
}
-
+
protected Attributes getPersonAttributes( String sn, String cn )
{
Attributes attrs = new BasicAttributes( true );
@@ -1281,7 +1250,6 @@ public class AddIT extends AbstractLdapT
return attrs;
}
-
/**
* <pre>
* ou=system
Modified: directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/add/AddingEntriesWithSpecialCharactersInRDNIT.java
URL: http://svn.apache.org/viewvc/directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/add/AddingEntriesWithSpecialCharactersInRDNIT.java?rev=987611&r1=987610&r2=987611&view=diff
==============================================================================
--- directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/add/AddingEntriesWithSpecialCharactersInRDNIT.java (original)
+++ directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/add/AddingEntriesWithSpecialCharactersInRDNIT.java Fri Aug 20 19:31:58 2010
@@ -24,8 +24,6 @@ import static org.junit.Assert.assertNot
import static org.junit.Assert.assertTrue;
import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.message.SearchResponse;
-import org.apache.directory.ldap.client.api.message.SearchResultEntry;
import org.apache.directory.server.annotations.CreateLdapServer;
import org.apache.directory.server.annotations.CreateTransport;
import org.apache.directory.server.core.integ.AbstractLdapTestUnit;
@@ -38,6 +36,8 @@ import org.apache.directory.shared.ldap.
import org.apache.directory.shared.ldap.entry.EntryAttribute;
import org.apache.directory.shared.ldap.exception.LdapException;
import org.apache.directory.shared.ldap.filter.SearchScope;
+import org.apache.directory.shared.ldap.message.Response;
+import org.apache.directory.shared.ldap.message.SearchResultEntry;
import org.apache.directory.shared.ldap.name.DN;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -49,12 +49,9 @@ import org.junit.runner.RunWith;
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
-@RunWith( FrameworkRunner.class )
-@CreateLdapServer (
- transports =
- {
- @CreateTransport( protocol = "LDAP" )
- })
+@RunWith(FrameworkRunner.class)
+@CreateLdapServer(transports =
+ { @CreateTransport(protocol = "LDAP") })
public class AddingEntriesWithSpecialCharactersInRDNIT extends AbstractLdapTestUnit
{
private Entry getPersonEntry( String sn, String cn ) throws LdapException
@@ -63,7 +60,7 @@ public class AddingEntriesWithSpecialCha
entry.add( SchemaConstants.OBJECT_CLASS_AT, "person" );
entry.add( SchemaConstants.CN_AT, cn );
entry.add( SchemaConstants.SN_AT, sn );
-
+
return entry;
}
@@ -73,7 +70,7 @@ public class AddingEntriesWithSpecialCha
Entry entry = new DefaultEntry();
entry.add( SchemaConstants.OBJECT_CLASS_AT, "organizationalUnit" );
entry.add( SchemaConstants.OU_AT, ou );
-
+
return entry;
}
@@ -93,20 +90,20 @@ public class AddingEntriesWithSpecialCha
personEntry.setDn( new DN( dn ) );
connection.add( personEntry );
- Cursor<SearchResponse> cursor = connection.search( "ou=system", "(cn=Kate#Bush)", SearchScope.SUBTREE, "*" );
+ Cursor<Response> cursor = connection.search( "ou=system", "(cn=Kate#Bush)", SearchScope.SUBTREE, "*" );
boolean entryFound = false;
while ( cursor.next() )
{
Entry sr = ( ( SearchResultEntry ) cursor.get() ).getEntry();
entryFound = true;
-
+
assertTrue( personEntry.getDn().equals( sr.getDn() ) );
EntryAttribute cn = sr.get( "cn" );
assertNotNull( cn );
assertTrue( cn.contains( "Kate#Bush" ) );
}
-
+
assertTrue( "entry found", entryFound );
connection.delete( dn );
@@ -128,18 +125,18 @@ public class AddingEntriesWithSpecialCha
entry.setDn( new DN( dn ) );
connection.add( entry );
- Cursor<SearchResponse> cursor = connection.search( "ou=system", "(cn=Bush, Kate)", SearchScope.SUBTREE, "*" );
+ Cursor<Response> cursor = connection.search( "ou=system", "(cn=Bush, Kate)", SearchScope.SUBTREE, "*" );
boolean entryFound = false;
while ( cursor.next() )
{
Entry sr = ( ( SearchResultEntry ) cursor.get() ).getEntry();
entryFound = true;
-
+
assertTrue( entry.getDn().equals( sr.getDn() ) );
EntryAttribute cn = sr.get( "cn" );
assertNotNull( cn );
-
+
assertTrue( cn.contains( "Bush, Kate" ) );
}
@@ -156,14 +153,14 @@ public class AddingEntriesWithSpecialCha
public void testAddingWithQuotesInRdn() throws Exception
{
LdapConnection connection = ServerIntegrationUtils.getClientApiConnection( ldapServer );
-
+
Entry entry = getPersonEntry( "Messer", "Mackie \"The Knife\" Messer" );
String dn = "cn=Mackie \\\"The Knife\\\" Messer,ou=system";
entry.setDn( new DN( dn ) );
connection.add( entry );
-
- Cursor<SearchResponse> cursor = connection.search( "ou=system", "(cn=Mackie \"The Knife\" Messer)", SearchScope.SUBTREE, "*" );
+ Cursor<Response> cursor = connection.search( "ou=system", "(cn=Mackie \"The Knife\" Messer)",
+ SearchScope.SUBTREE, "*" );
boolean entryFound = false;
while ( cursor.next() )
{
@@ -176,7 +173,7 @@ public class AddingEntriesWithSpecialCha
}
assertTrue( "entry found", entryFound );
-
+
connection.delete( dn );
}
@@ -188,21 +185,21 @@ public class AddingEntriesWithSpecialCha
public void testAddingWithBackslashInRdn() throws Exception
{
LdapConnection connection = ServerIntegrationUtils.getClientApiConnection( ldapServer );
-
+
Entry entry = getOrgUnitEntry( "AC\\DC" );
String dn = "ou=AC\\\\DC,ou=system";
entry.setDn( new DN( dn ) );
connection.add( entry );
- Cursor<SearchResponse> cursor = connection.search( "ou=system", "(ou=AC\\5CDC)", SearchScope.SUBTREE, "*" );
- boolean entryFound= false;
-
+ Cursor<Response> cursor = connection.search( "ou=system", "(ou=AC\\5CDC)", SearchScope.SUBTREE, "*" );
+ boolean entryFound = false;
+
while ( cursor.next() )
{
Entry sr = ( ( SearchResultEntry ) cursor.get() ).getEntry();
entryFound = true;
assertTrue( entry.getDn().equals( sr.getDn() ) );
-
+
EntryAttribute ou = sr.get( "ou" );
assertNotNull( ou );
assertTrue( ou.contains( "AC\\DC" ) );
@@ -222,13 +219,14 @@ public class AddingEntriesWithSpecialCha
public void testAddingWithGreaterSignInRdn() throws Exception
{
LdapConnection connection = ServerIntegrationUtils.getClientApiConnection( ldapServer );
-
+
Entry entry = getOrgUnitEntry( "East -> West" );
String dn = "ou=East -\\> West,ou=system";
entry.setDn( new DN( dn ) );
- connection.add( entry );
+ connection.add( entry );
- Cursor<SearchResponse> cursor = connection.search( "ou=system", "(ou=East -> West)", SearchScope.SUBTREE, "*" );
+ Cursor<Response> cursor = connection
+ .search( "ou=system", "(ou=East -> West)", SearchScope.SUBTREE, "*" );
boolean entryFound = false;
while ( cursor.next() )
@@ -261,23 +259,23 @@ public class AddingEntriesWithSpecialCha
Entry entry = getOrgUnitEntry( "Scissors 8<" );
String dn = "ou=Scissors 8\\<,ou=system";
entry.setDn( new DN( dn ) );
- connection.add( entry );
+ connection.add( entry );
- Cursor<SearchResponse> cursor = connection.search( "ou=system", "(ou=Scissors 8<)", SearchScope.SUBTREE, "*" );
+ Cursor<Response> cursor = connection.search( "ou=system", "(ou=Scissors 8<)", SearchScope.SUBTREE, "*" );
boolean entryFound = false;
while ( cursor.next() )
{
Entry sr = ( ( SearchResultEntry ) cursor.get() ).getEntry();
entryFound = true;
-
+
assertTrue( entry.getDn().equals( sr.getDn() ) );
EntryAttribute ou = sr.get( "ou" );
assertNotNull( ou );
assertTrue( ou.contains( "Scissors 8<" ) );
}
-
+
assertTrue( "entry found", entryFound );
connection.delete( dn );
@@ -293,13 +291,14 @@ public class AddingEntriesWithSpecialCha
public void testAddingWithSemicolonInRdn() throws Exception
{
LdapConnection connection = ServerIntegrationUtils.getClientApiConnection( ldapServer );
-
+
Entry entry = getOrgUnitEntry( "semicolon group;" );
String dn = "ou=semicolon group\\;,ou=system";
entry.setDn( new DN( dn ) );
connection.add( entry );
- Cursor<SearchResponse> cursor = connection.search( "ou=system", "(ou=semicolon group;)", SearchScope.SUBTREE, "*" );
+ Cursor<Response> cursor = connection.search( "ou=system", "(ou=semicolon group;)", SearchScope.SUBTREE,
+ "*" );
boolean entryFound = false;
while ( cursor.next() )
@@ -312,7 +311,7 @@ public class AddingEntriesWithSpecialCha
assertNotNull( ou );
assertTrue( ou.contains( "semicolon group;" ) );
}
-
+
assertTrue( "entry found", entryFound );
connection.delete( dn );
@@ -328,14 +327,14 @@ public class AddingEntriesWithSpecialCha
public void testAddingWithEqualsInRdn() throws Exception
{
LdapConnection connection = ServerIntegrationUtils.getClientApiConnection( ldapServer );
-
+
Entry entry = getOrgUnitEntry( "nomen=omen" );
String dn = "ou=nomen\\=omen,ou=system";
entry.setDn( new DN( dn ) );
connection.add( entry );
- Cursor<SearchResponse> cursor = connection.search( "ou=system", "(ou=nomen=omen)", SearchScope.SUBTREE, "*" );
-
+ Cursor<Response> cursor = connection.search( "ou=system", "(ou=nomen=omen)", SearchScope.SUBTREE, "*" );
+
boolean entryFound = false;
while ( cursor.next() )
@@ -348,9 +347,9 @@ public class AddingEntriesWithSpecialCha
assertNotNull( ou );
assertTrue( ou.contains( "nomen=omen" ) );
}
-
+
assertTrue( "entry found", entryFound );
-
+
connection.delete( dn );
}
}
\ No newline at end of file
Modified: directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/bind/SaslBindIT.java
URL: http://svn.apache.org/viewvc/directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/bind/SaslBindIT.java?rev=987611&r1=987610&r2=987611&view=diff
==============================================================================
--- directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/bind/SaslBindIT.java (original)
+++ directory/apacheds/trunk/server-integ/src/test/java/org/apache/directory/server/operations/bind/SaslBindIT.java Fri Aug 20 19:31:58 2010
@@ -25,6 +25,7 @@ import static org.junit.Assert.assertTru
import static org.junit.Assert.fail;
import java.lang.reflect.Field;
+import java.nio.ByteBuffer;
import java.util.Hashtable;
import javax.naming.AuthenticationNotSupportedException;
@@ -56,10 +57,10 @@ import org.apache.directory.server.ldap.
import org.apache.directory.server.ldap.handlers.extended.StoredProcedureExtendedOperationHandler;
import org.apache.directory.shared.ldap.constants.SupportedSaslMechanisms;
import org.apache.directory.shared.ldap.message.BindRequestImpl;
+import org.apache.directory.shared.ldap.message.BindResponse;
+import org.apache.directory.shared.ldap.message.LdapProtocolEncoder;
import org.apache.directory.shared.ldap.message.MessageDecoder;
-import org.apache.directory.shared.ldap.message.MessageEncoder;
import org.apache.directory.shared.ldap.message.ResultCodeEnum;
-import org.apache.directory.shared.ldap.message.internal.InternalBindResponse;
import org.apache.directory.shared.ldap.message.spi.BinaryAttributeDetector;
import org.apache.directory.shared.ldap.name.DN;
import org.junit.Test;
@@ -73,523 +74,494 @@ import org.slf4j.LoggerFactory;
*
* @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
*/
-@RunWith ( FrameworkRunner.class )
-@ApplyLdifs( {
- // Entry # 1
- "dn: ou=users,dc=example,dc=com",
- "objectClass: organizationalUnit",
- "objectClass: top",
- "ou: users\n",
- // Entry # 2
- "dn: uid=hnelson,ou=users,dc=example,dc=com",
- "objectClass: inetOrgPerson",
- "objectClass: organizationalPerson",
- "objectClass: person",
- "objectClass: top",
- "uid: hnelson",
- "userPassword: secret",
- "cn: Horatio Nelson",
- "sn: Nelson"
- }
-)
-@CreateDS( allowAnonAccess=true, name="SaslBindIT-class",
- partitions =
- {
- @CreatePartition(
- name = "example",
- suffix = "dc=example,dc=com",
- contextEntry = @ContextEntry(
- entryLdif =
- "dn: dc=example,dc=com\n" +
- "dc: example\n" +
- "objectClass: top\n" +
- "objectClass: domain\n\n" ),
- indexes =
- {
- @CreateIndex( attribute = "objectClass" ),
- @CreateIndex( attribute = "dc" ),
- @CreateIndex( attribute = "ou" )
- } )
- })
-@CreateLdapServer (
- transports =
- {
- @CreateTransport( protocol = "LDAP" )
- },
- saslHost="localhost",
- saslMechanisms =
- {
- @SaslMechanism( name=SupportedSaslMechanisms.PLAIN, implClass=PlainMechanismHandler.class ),
- @SaslMechanism( name=SupportedSaslMechanisms.CRAM_MD5, implClass=CramMd5MechanismHandler.class),
- @SaslMechanism( name=SupportedSaslMechanisms.DIGEST_MD5, implClass=DigestMd5MechanismHandler.class),
- @SaslMechanism( name=SupportedSaslMechanisms.GSSAPI, implClass=GssapiMechanismHandler.class),
- @SaslMechanism( name=SupportedSaslMechanisms.NTLM, implClass=NtlmMechanismHandler.class),
- @SaslMechanism( name=SupportedSaslMechanisms.GSS_SPNEGO, implClass=NtlmMechanismHandler.class)
- },
- extendedOpHandlers =
- {
- StoredProcedureExtendedOperationHandler.class
- },
- ntlmProvider=BogusNtlmProvider.class
- )
+@RunWith(FrameworkRunner.class)
+@ApplyLdifs(
+ {
+ // Entry # 1
+ "dn: ou=users,dc=example,dc=com", "objectClass: organizationalUnit", "objectClass: top",
+ "ou: users\n",
+ // Entry # 2
+ "dn: uid=hnelson,ou=users,dc=example,dc=com", "objectClass: inetOrgPerson",
+ "objectClass: organizationalPerson", "objectClass: person", "objectClass: top", "uid: hnelson",
+ "userPassword: secret", "cn: Horatio Nelson", "sn: Nelson" })
+@CreateDS(allowAnonAccess = true, name = "SaslBindIT-class", partitions =
+ { @CreatePartition(name = "example", suffix = "dc=example,dc=com", contextEntry = @ContextEntry(entryLdif = "dn: dc=example,dc=com\n"
+ + "dc: example\n" + "objectClass: top\n" + "objectClass: domain\n\n"), indexes =
+ { @CreateIndex(attribute = "objectClass"), @CreateIndex(attribute = "dc"), @CreateIndex(attribute = "ou") }) })
+@CreateLdapServer(transports =
+ { @CreateTransport(protocol = "LDAP") }, saslHost = "localhost", saslMechanisms =
+ { @SaslMechanism(name = SupportedSaslMechanisms.PLAIN, implClass = PlainMechanismHandler.class),
+ @SaslMechanism(name = SupportedSaslMechanisms.CRAM_MD5, implClass = CramMd5MechanismHandler.class),
+ @SaslMechanism(name = SupportedSaslMechanisms.DIGEST_MD5, implClass = DigestMd5MechanismHandler.class),
+ @SaslMechanism(name = SupportedSaslMechanisms.GSSAPI, implClass = GssapiMechanismHandler.class),
+ @SaslMechanism(name = SupportedSaslMechanisms.NTLM, implClass = NtlmMechanismHandler.class),
+ @SaslMechanism(name = SupportedSaslMechanisms.GSS_SPNEGO, implClass = NtlmMechanismHandler.class) }, extendedOpHandlers =
+ { StoredProcedureExtendedOperationHandler.class }, ntlmProvider = BogusNtlmProvider.class)
public class SaslBindIT extends AbstractLdapTestUnit
{
-
- /**
- * Tests to make sure the server properly returns the supportedSASLMechanisms.
- */
- @Test
- public void testSupportedSASLMechanisms()
- {
- try
- {
- // We have to tell the server that it should accept anonymous
- // auth, because we are reading the rootDSE
- ldapServer.setAllowAnonymousAccess( true );
- ldapServer.getDirectoryService().setAllowAnonymousAccess( true );
-
- // Point on rootDSE
- DirContext context = new InitialDirContext();
-
- Attributes attrs = context.getAttributes( "ldap://localhost:"
- + ldapServer.getPort(), new String[]
- { "supportedSASLMechanisms" } );
-
-// Thread.sleep( 10 * 60 * 1000 );
- NamingEnumeration<? extends Attribute> answer = attrs.getAll();
- Attribute result = answer.next();
- assertEquals( 6, result.size() );
- assertTrue( result.contains( SupportedSaslMechanisms.GSSAPI ) );
- assertTrue( result.contains( SupportedSaslMechanisms.DIGEST_MD5 ) );
- assertTrue( result.contains( SupportedSaslMechanisms.CRAM_MD5 ) );
- assertTrue( result.contains( SupportedSaslMechanisms.NTLM ) );
- assertTrue( result.contains( SupportedSaslMechanisms.PLAIN ) );
- assertTrue( result.contains( SupportedSaslMechanisms.GSS_SPNEGO ) );
- }
- catch ( Exception e )
- {
- fail( "Should not have caught exception." );
- }
- }
-
-
- /**
- * Tests to make sure PLAIN-binds works
- */
- @Test
- public void testSaslBindPLAIN()
- {
- try
- {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
- env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
-
- env.put( Context.SECURITY_AUTHENTICATION, "PLAIN" );
- env.put( Context.SECURITY_PRINCIPAL, "uid=hnelson,ou=users,dc=example,dc=com" );
- env.put( Context.SECURITY_CREDENTIALS, "secret" );
-
- DirContext context = new InitialDirContext( env );
-
- String[] attrIDs =
- { "uid" };
-
- Attributes attrs = context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
- String uid = null;
-
- if ( attrs.get( "uid" ) != null )
- {
- uid = ( String ) attrs.get( "uid" ).get();
- }
-
- assertEquals( uid, "hnelson" );
- }
- catch ( NamingException e )
- {
- fail( "Should not have caught exception." );
- }
- }
-
-
- /**
- * Test a SASL bind with an empty mechanism
- */
- @Test
- public void testSaslBindNoMech()
- {
- try
- {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
- env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
-
- env.put( Context.SECURITY_AUTHENTICATION, "" );
- env.put( Context.SECURITY_PRINCIPAL, "uid=hnelson,ou=users,dc=example,dc=com" );
- env.put( Context.SECURITY_CREDENTIALS, "secret" );
-
- new InitialDirContext( env );
- fail( "Should not be there" );
- }
- catch ( AuthenticationNotSupportedException anse )
- {
- assertTrue( true );
- }
- catch ( NamingException ne )
- {
- fail( "Should not have caught exception." );
- }
- }
-
-
- /**
- * Tests to make sure CRAM-MD5 binds below the RootDSE work.
- */
- @Test
- public void testSaslCramMd5Bind()
- {
- try
- {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
- env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
-
- env.put( Context.SECURITY_AUTHENTICATION, "CRAM-MD5" );
- env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
- env.put( Context.SECURITY_CREDENTIALS, "secret" );
-
- DirContext context = new InitialDirContext( env );
-
- String[] attrIDs =
- { "uid" };
-
- Attributes attrs = context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
-
- String uid = null;
-
- if ( attrs.get( "uid" ) != null )
- {
- uid = ( String ) attrs.get( "uid" ).get();
- }
-
- assertEquals( uid, "hnelson" );
- }
- catch ( NamingException e )
- {
- fail( "Should not have caught exception." );
- }
- }
-
-
- /**
- * Tests to make sure CRAM-MD5 binds below the RootDSE fail if the password is bad.
- */
- @Test
- public void testSaslCramMd5BindBadPassword()
- {
- try
- {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
- env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
-
- env.put( Context.SECURITY_AUTHENTICATION, "CRAM-MD5" );
- env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
- env.put( Context.SECURITY_CREDENTIALS, "badsecret" );
-
- DirContext context = new InitialDirContext( env );
-
- String[] attrIDs =
- { "uid" };
-
- context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
-
- fail( "Should have thrown exception." );
- }
- catch ( NamingException e )
- {
- assertTrue( e.getMessage().contains( "Invalid response" ) );
- }
- }
-
-
- /**
- * Tests to make sure DIGEST-MD5 binds below the RootDSE work.
- */
- @Test
- public void testSaslDigestMd5Bind() throws Exception
- {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
- env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
-
- env.put( Context.SECURITY_AUTHENTICATION, "DIGEST-MD5" );
- env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
- env.put( Context.SECURITY_CREDENTIALS, "secret" );
-
- // Specify realm
- env.put( "java.naming.security.sasl.realm", "example.com" );
-
- // Request privacy protection
- env.put( "javax.security.sasl.qop", "auth-conf" );
-
- DirContext context = new InitialDirContext( env );
-
- String[] attrIDs =
- { "uid" };
-
- Attributes attrs = context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
-
- String uid = null;
-
- if ( attrs.get( "uid" ) != null )
- {
- uid = ( String ) attrs.get( "uid" ).get();
- }
-
- assertEquals( uid, "hnelson" );
- }
-
-
- /**
- * Tests to make sure DIGEST-MD5 binds below the RootDSE fail if the realm is bad.
- */
- @Test
- public void testSaslDigestMd5BindBadRealm()
- {
- try
- {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
- env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
-
- env.put( Context.SECURITY_AUTHENTICATION, "DIGEST-MD5" );
- env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
- env.put( Context.SECURITY_CREDENTIALS, "secret" );
-
- // Bad realm
- env.put( "java.naming.security.sasl.realm", "badrealm.com" );
-
- // Request privacy protection
- env.put( "javax.security.sasl.qop", "auth-conf" );
-
- DirContext context = new InitialDirContext( env );
-
- String[] attrIDs =
- { "uid" };
-
- context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
-
- fail( "Should have thrown exception." );
- }
- catch ( NamingException e )
- {
- assertTrue( e.getMessage().contains( "Nonexistent realm" ) );
- }
- }
-
-
- /**
- * Tests to make sure DIGEST-MD5 binds below the RootDSE fail if the password is bad.
- */
- @Test
- public void testSaslDigestMd5BindBadPassword()
- {
- try
- {
- Hashtable<String, String> env = new Hashtable<String, String>();
- env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
- env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
-
- env.put( Context.SECURITY_AUTHENTICATION, "DIGEST-MD5" );
- env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
- env.put( Context.SECURITY_CREDENTIALS, "badsecret" );
-
- DirContext context = new InitialDirContext( env );
- String[] attrIDs = { "uid" };
-
- context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
- fail( "Should have thrown exception." );
- }
- catch ( NamingException e )
- {
- assertTrue( e.getMessage().contains( "digest response format violation" ) );
- }
- }
-
-
- /**
- * Tests that the plumbing for NTLM bind works.
- */
- @Test
- public void testNtlmBind() throws Exception
- {
- BogusNtlmProvider provider = getNtlmProviderUsingReflection();
-
- NtlmSaslBindClient client = new NtlmSaslBindClient( SupportedSaslMechanisms.NTLM );
- InternalBindResponse type2response = client.bindType1( "type1_test".getBytes() );
- assertEquals( 1, type2response.getMessageId() );
- assertEquals( ResultCodeEnum.SASL_BIND_IN_PROGRESS, type2response.getLdapResult().getResultCode() );
- assertTrue( ArrayUtils.isEquals( "type1_test".getBytes(), provider.getType1Response() ) );
- assertTrue( ArrayUtils.isEquals( "challenge".getBytes(), type2response.getServerSaslCreds() ) );
-
- InternalBindResponse finalResponse = client.bindType3( "type3_test".getBytes() );
- assertEquals( 2, finalResponse.getMessageId() );
- assertEquals( ResultCodeEnum.SUCCESS, finalResponse.getLdapResult().getResultCode() );
- assertTrue( ArrayUtils.isEquals( "type3_test".getBytes(), provider.getType3Response() ) );
- }
-
-
- /**
- * Tests that the plumbing for NTLM bind works.
- */
- @Test
- public void testGssSpnegoBind() throws Exception
- {
- BogusNtlmProvider provider = new BogusNtlmProvider();
-
- // the provider configured in @CreateLdapServer only sets for the NTLM mechanism
- // but we use the same NtlmMechanismHandler class for GSS_SPNEGO too but this is a separate
- // instance, so we need to set the provider in the NtlmMechanismHandler instance of GSS_SPNEGO mechanism
- NtlmMechanismHandler ntlmHandler = ( NtlmMechanismHandler ) ldapServer.getSaslMechanismHandlers().get( SupportedSaslMechanisms.GSS_SPNEGO );
- ntlmHandler.setNtlmProvider( provider );
-
- NtlmSaslBindClient client = new NtlmSaslBindClient( SupportedSaslMechanisms.GSS_SPNEGO );
- InternalBindResponse type2response = client.bindType1( "type1_test".getBytes() );
- assertEquals( 1, type2response.getMessageId() );
- assertEquals( ResultCodeEnum.SASL_BIND_IN_PROGRESS, type2response.getLdapResult().getResultCode() );
- assertTrue( ArrayUtils.isEquals( "type1_test".getBytes(), provider.getType1Response() ) );
- assertTrue( ArrayUtils.isEquals( "challenge".getBytes(), type2response.getServerSaslCreds() ) );
-
- InternalBindResponse finalResponse = client.bindType3( "type3_test".getBytes() );
- assertEquals( 2, finalResponse.getMessageId() );
- assertEquals( ResultCodeEnum.SUCCESS, finalResponse.getLdapResult().getResultCode() );
- assertTrue( ArrayUtils.isEquals( "type3_test".getBytes(), provider.getType3Response() ) );
- }
-
-
- /**
- * A NTLM client
- */
- class NtlmSaslBindClient extends SocketClient
- {
- private final Logger LOG = LoggerFactory.getLogger( NtlmSaslBindClient.class );
-
- private final String mechanism;
-
-
- NtlmSaslBindClient( String mechanism ) throws Exception
- {
- this.mechanism = mechanism;
- setDefaultPort( ldapServer.getPort() );
- connect( "localhost", ldapServer.getPort() );
- setTcpNoDelay( false );
-
- LOG.debug( "isConnected() = {}", isConnected() );
- LOG.debug( "LocalPort = {}", getLocalPort() );
- LOG.debug( "LocalAddress = {}", getLocalAddress() );
- LOG.debug( "RemotePort = {}", getRemotePort() );
- LOG.debug( "RemoteAddress = {}", getRemoteAddress() );
- }
-
-
- InternalBindResponse bindType1( byte[] type1response ) throws Exception
- {
- if ( ! isConnected() )
- {
- throw new IllegalStateException( "Client is not connected." );
- }
-
- // Setup the bind request
- BindRequestImpl request = new BindRequestImpl( 1 ) ;
- request.setName( new DN( "uid=admin,ou=system" ) ) ;
- request.setSimple( false ) ;
- request.setCredentials( type1response ) ;
- request.setSaslMechanism( mechanism );
- request.setVersion3( true ) ;
-
- // Setup the ASN1 Encoder and Decoder
- MessageEncoder encoder = new MessageEncoder();
- MessageDecoder decoder = new MessageDecoder( new BinaryAttributeDetector() {
- public boolean isBinary( String attributeId )
- {
- return false;
- }
- } );
-
- // Send encoded request to server
- encoder.encodeBlocking( null, _output_, request );
- _output_.flush();
-
- while ( _input_.available() <= 0 )
- {
- Thread.sleep( 100 );
- }
-
- // Retrieve the response back from server to my last request.
- return ( InternalBindResponse ) decoder.decode( null, _input_ );
- }
-
-
- InternalBindResponse bindType3( byte[] type3response ) throws Exception
- {
- if ( ! isConnected() )
- {
- throw new IllegalStateException( "Client is not connected." );
- }
-
- // Setup the bind request
- BindRequestImpl request = new BindRequestImpl( 2 ) ;
- request.setName( new DN( "uid=admin,ou=system" ) ) ;
- request.setSimple( false ) ;
- request.setCredentials( type3response ) ;
- request.setSaslMechanism( mechanism );
- request.setVersion3( true ) ;
-
- // Setup the ASN1 Enoder and Decoder
- MessageEncoder encoder = new MessageEncoder();
- MessageDecoder decoder = new MessageDecoder( new BinaryAttributeDetector() {
- public boolean isBinary( String attributeId )
- {
- return false;
- }
- } );
-
- // Send encoded request to server
- encoder.encodeBlocking( null, _output_, request );
-
- _output_.flush();
-
- while ( _input_.available() <= 0 )
- {
- Thread.sleep( 100 );
- }
-
- // Retrieve the response back from server to my last request.
- return ( InternalBindResponse ) decoder.decode( null, _input_ );
- }
- }
-
-
- private BogusNtlmProvider getNtlmProviderUsingReflection()
- {
- BogusNtlmProvider provider = null;
- try
- {
- NtlmMechanismHandler ntlmHandler = ( NtlmMechanismHandler ) ldapServer.getSaslMechanismHandlers().get( SupportedSaslMechanisms.NTLM );
-
- // there is no getter for 'provider' field hence this hack
- Field field = ntlmHandler.getClass().getDeclaredField( "provider" );
- field.setAccessible( true );
- provider = ( BogusNtlmProvider ) field.get( ntlmHandler );
- }
- catch( Exception e )
- {
- e.printStackTrace();
- }
-
- return provider;
- }
+ /**
+ * Tests to make sure the server properly returns the supportedSASLMechanisms.
+ */
+ @Test
+ public void testSupportedSASLMechanisms()
+ {
+ try
+ {
+ // We have to tell the server that it should accept anonymous
+ // auth, because we are reading the rootDSE
+ ldapServer.setAllowAnonymousAccess( true );
+ ldapServer.getDirectoryService().setAllowAnonymousAccess( true );
+
+ // Point on rootDSE
+ DirContext context = new InitialDirContext();
+
+ Attributes attrs = context.getAttributes( "ldap://localhost:" + ldapServer.getPort(), new String[]
+ { "supportedSASLMechanisms" } );
+
+ // Thread.sleep( 10 * 60 * 1000 );
+ NamingEnumeration<? extends Attribute> answer = attrs.getAll();
+ Attribute result = answer.next();
+ assertEquals( 6, result.size() );
+ assertTrue( result.contains( SupportedSaslMechanisms.GSSAPI ) );
+ assertTrue( result.contains( SupportedSaslMechanisms.DIGEST_MD5 ) );
+ assertTrue( result.contains( SupportedSaslMechanisms.CRAM_MD5 ) );
+ assertTrue( result.contains( SupportedSaslMechanisms.NTLM ) );
+ assertTrue( result.contains( SupportedSaslMechanisms.PLAIN ) );
+ assertTrue( result.contains( SupportedSaslMechanisms.GSS_SPNEGO ) );
+ }
+ catch ( Exception e )
+ {
+ fail( "Should not have caught exception." );
+ }
+ }
+
+
+ /**
+ * Tests to make sure PLAIN-binds works
+ */
+ @Test
+ public void testSaslBindPLAIN()
+ {
+ try
+ {
+ Hashtable<String, String> env = new Hashtable<String, String>();
+ env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
+ env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
+
+ env.put( Context.SECURITY_AUTHENTICATION, "PLAIN" );
+ env.put( Context.SECURITY_PRINCIPAL, "uid=hnelson,ou=users,dc=example,dc=com" );
+ env.put( Context.SECURITY_CREDENTIALS, "secret" );
+
+ DirContext context = new InitialDirContext( env );
+
+ String[] attrIDs =
+ { "uid" };
+
+ Attributes attrs = context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
+ String uid = null;
+
+ if ( attrs.get( "uid" ) != null )
+ {
+ uid = ( String ) attrs.get( "uid" ).get();
+ }
+
+ assertEquals( uid, "hnelson" );
+ }
+ catch ( NamingException e )
+ {
+ fail( "Should not have caught exception." );
+ }
+ }
+
+
+ /**
+ * Test a SASL bind with an empty mechanism
+ */
+ @Test
+ public void testSaslBindNoMech()
+ {
+ try
+ {
+ Hashtable<String, String> env = new Hashtable<String, String>();
+ env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
+ env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
+
+ env.put( Context.SECURITY_AUTHENTICATION, "" );
+ env.put( Context.SECURITY_PRINCIPAL, "uid=hnelson,ou=users,dc=example,dc=com" );
+ env.put( Context.SECURITY_CREDENTIALS, "secret" );
+
+ new InitialDirContext( env );
+ fail( "Should not be there" );
+ }
+ catch ( AuthenticationNotSupportedException anse )
+ {
+ assertTrue( true );
+ }
+ catch ( NamingException ne )
+ {
+ fail( "Should not have caught exception." );
+ }
+ }
+
+
+ /**
+ * Tests to make sure CRAM-MD5 binds below the RootDSE work.
+ */
+ @Test
+ public void testSaslCramMd5Bind()
+ {
+ try
+ {
+ Hashtable<String, String> env = new Hashtable<String, String>();
+ env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
+ env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
+
+ env.put( Context.SECURITY_AUTHENTICATION, "CRAM-MD5" );
+ env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
+ env.put( Context.SECURITY_CREDENTIALS, "secret" );
+
+ DirContext context = new InitialDirContext( env );
+
+ String[] attrIDs =
+ { "uid" };
+
+ Attributes attrs = context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
+
+ String uid = null;
+
+ if ( attrs.get( "uid" ) != null )
+ {
+ uid = ( String ) attrs.get( "uid" ).get();
+ }
+
+ assertEquals( uid, "hnelson" );
+ }
+ catch ( NamingException e )
+ {
+ fail( "Should not have caught exception." );
+ }
+ }
+
+
+ /**
+ * Tests to make sure CRAM-MD5 binds below the RootDSE fail if the password is bad.
+ */
+ @Test
+ public void testSaslCramMd5BindBadPassword()
+ {
+ try
+ {
+ Hashtable<String, String> env = new Hashtable<String, String>();
+ env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
+ env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
+
+ env.put( Context.SECURITY_AUTHENTICATION, "CRAM-MD5" );
+ env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
+ env.put( Context.SECURITY_CREDENTIALS, "badsecret" );
+
+ DirContext context = new InitialDirContext( env );
+
+ String[] attrIDs =
+ { "uid" };
+
+ context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
+
+ fail( "Should have thrown exception." );
+ }
+ catch ( NamingException e )
+ {
+ assertTrue( e.getMessage().contains( "Invalid response" ) );
+ }
+ }
+
+
+ /**
+ * Tests to make sure DIGEST-MD5 binds below the RootDSE work.
+ */
+ @Test
+ public void testSaslDigestMd5Bind() throws Exception
+ {
+ Hashtable<String, String> env = new Hashtable<String, String>();
+ env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
+ env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
+
+ env.put( Context.SECURITY_AUTHENTICATION, "DIGEST-MD5" );
+ env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
+ env.put( Context.SECURITY_CREDENTIALS, "secret" );
+
+ // Specify realm
+ env.put( "java.naming.security.sasl.realm", "example.com" );
+
+ // Request privacy protection
+ env.put( "javax.security.sasl.qop", "auth-conf" );
+
+ DirContext context = new InitialDirContext( env );
+
+ String[] attrIDs =
+ { "uid" };
+
+ Attributes attrs = context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
+
+ String uid = null;
+
+ if ( attrs.get( "uid" ) != null )
+ {
+ uid = ( String ) attrs.get( "uid" ).get();
+ }
+
+ assertEquals( uid, "hnelson" );
+ }
-}
+ /**
+ * Tests to make sure DIGEST-MD5 binds below the RootDSE fail if the realm is bad.
+ */
+ @Test
+ public void testSaslDigestMd5BindBadRealm()
+ {
+ try
+ {
+ Hashtable<String, String> env = new Hashtable<String, String>();
+ env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
+ env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
+
+ env.put( Context.SECURITY_AUTHENTICATION, "DIGEST-MD5" );
+ env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
+ env.put( Context.SECURITY_CREDENTIALS, "secret" );
+
+ // Bad realm
+ env.put( "java.naming.security.sasl.realm", "badrealm.com" );
+
+ // Request privacy protection
+ env.put( "javax.security.sasl.qop", "auth-conf" );
+
+ DirContext context = new InitialDirContext( env );
+
+ String[] attrIDs =
+ { "uid" };
+
+ context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
+
+ fail( "Should have thrown exception." );
+ }
+ catch ( NamingException e )
+ {
+ assertTrue( e.getMessage().contains( "Nonexistent realm" ) );
+ }
+ }
+
+
+ /**
+ * Tests to make sure DIGEST-MD5 binds below the RootDSE fail if the password is bad.
+ */
+ @Test
+ public void testSaslDigestMd5BindBadPassword()
+ {
+ try
+ {
+ Hashtable<String, String> env = new Hashtable<String, String>();
+ env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
+ env.put( Context.PROVIDER_URL, "ldap://localhost:" + ldapServer.getPort() );
+
+ env.put( Context.SECURITY_AUTHENTICATION, "DIGEST-MD5" );
+ env.put( Context.SECURITY_PRINCIPAL, "hnelson" );
+ env.put( Context.SECURITY_CREDENTIALS, "badsecret" );
+
+ DirContext context = new InitialDirContext( env );
+ String[] attrIDs =
+ { "uid" };
+
+ context.getAttributes( "uid=hnelson,ou=users,dc=example,dc=com", attrIDs );
+ fail( "Should have thrown exception." );
+ }
+ catch ( NamingException e )
+ {
+ assertTrue( e.getMessage().contains( "digest response format violation" ) );
+ }
+ }
+
+
+ /**
+ * Tests that the plumbing for NTLM bind works.
+ */
+ @Test
+ public void testNtlmBind() throws Exception
+ {
+ BogusNtlmProvider provider = getNtlmProviderUsingReflection();
+
+ NtlmSaslBindClient client = new NtlmSaslBindClient( SupportedSaslMechanisms.NTLM );
+ BindResponse type2response = client.bindType1( "type1_test".getBytes() );
+ assertEquals( 1, type2response.getMessageId() );
+ assertEquals( ResultCodeEnum.SASL_BIND_IN_PROGRESS, type2response.getLdapResult().getResultCode() );
+ assertTrue( ArrayUtils.isEquals( "type1_test".getBytes(), provider.getType1Response() ) );
+ assertTrue( ArrayUtils.isEquals( "challenge".getBytes(), type2response.getServerSaslCreds() ) );
+
+ BindResponse finalResponse = client.bindType3( "type3_test".getBytes() );
+ assertEquals( 2, finalResponse.getMessageId() );
+ assertEquals( ResultCodeEnum.SUCCESS, finalResponse.getLdapResult().getResultCode() );
+ assertTrue( ArrayUtils.isEquals( "type3_test".getBytes(), provider.getType3Response() ) );
+ }
+
+
+ /**
+ * Tests that the plumbing for NTLM bind works.
+ */
+ @Test
+ public void testGssSpnegoBind() throws Exception
+ {
+ BogusNtlmProvider provider = new BogusNtlmProvider();
+
+ // the provider configured in @CreateLdapServer only sets for the NTLM mechanism
+ // but we use the same NtlmMechanismHandler class for GSS_SPNEGO too but this is a separate
+ // instance, so we need to set the provider in the NtlmMechanismHandler instance of GSS_SPNEGO mechanism
+ NtlmMechanismHandler ntlmHandler = ( NtlmMechanismHandler ) ldapServer.getSaslMechanismHandlers().get(
+ SupportedSaslMechanisms.GSS_SPNEGO );
+ ntlmHandler.setNtlmProvider( provider );
+
+ NtlmSaslBindClient client = new NtlmSaslBindClient( SupportedSaslMechanisms.GSS_SPNEGO );
+ BindResponse type2response = client.bindType1( "type1_test".getBytes() );
+ assertEquals( 1, type2response.getMessageId() );
+ assertEquals( ResultCodeEnum.SASL_BIND_IN_PROGRESS, type2response.getLdapResult().getResultCode() );
+ assertTrue( ArrayUtils.isEquals( "type1_test".getBytes(), provider.getType1Response() ) );
+ assertTrue( ArrayUtils.isEquals( "challenge".getBytes(), type2response.getServerSaslCreds() ) );
+
+ BindResponse finalResponse = client.bindType3( "type3_test".getBytes() );
+ assertEquals( 2, finalResponse.getMessageId() );
+ assertEquals( ResultCodeEnum.SUCCESS, finalResponse.getLdapResult().getResultCode() );
+ assertTrue( ArrayUtils.isEquals( "type3_test".getBytes(), provider.getType3Response() ) );
+ }
+
+ /**
+ * A NTLM client
+ */
+ class NtlmSaslBindClient extends SocketClient
+ {
+ private final Logger LOG = LoggerFactory.getLogger( NtlmSaslBindClient.class );
+
+ private final String mechanism;
+
+
+ NtlmSaslBindClient( String mechanism ) throws Exception
+ {
+ this.mechanism = mechanism;
+ setDefaultPort( ldapServer.getPort() );
+ connect( "localhost", ldapServer.getPort() );
+ setTcpNoDelay( false );
+
+ LOG.debug( "isConnected() = {}", isConnected() );
+ LOG.debug( "LocalPort = {}", getLocalPort() );
+ LOG.debug( "LocalAddress = {}", getLocalAddress() );
+ LOG.debug( "RemotePort = {}", getRemotePort() );
+ LOG.debug( "RemoteAddress = {}", getRemoteAddress() );
+ }
+
+
+ BindResponse bindType1( byte[] type1response ) throws Exception
+ {
+ if ( !isConnected() )
+ {
+ throw new IllegalStateException( "Client is not connected." );
+ }
+
+ // Setup the bind request
+ BindRequestImpl request = new BindRequestImpl( 1 );
+ request.setName( new DN( "uid=admin,ou=system" ) );
+ request.setSimple( false );
+ request.setCredentials( type1response );
+ request.setSaslMechanism( mechanism );
+ request.setVersion3( true );
+
+ // Setup the ASN1 Encoder and Decoder
+ MessageDecoder decoder = new MessageDecoder( new BinaryAttributeDetector()
+ {
+ public boolean isBinary( String attributeId )
+ {
+ return false;
+ }
+ } );
+
+ // Send encoded request to server
+ LdapProtocolEncoder encoder = new LdapProtocolEncoder();
+ ByteBuffer bb = encoder.encodeMessage( request );
+
+ bb.flip();
+
+ _output_.write( bb.array() );
+ _output_.flush();
+
+ while ( _input_.available() <= 0 )
+ {
+ Thread.sleep( 100 );
+ }
+
+ // Retrieve the response back from server to my last request.
+ return ( BindResponse ) decoder.decode( null, _input_ );
+ }
+
+
+ BindResponse bindType3( byte[] type3response ) throws Exception
+ {
+ if ( !isConnected() )
+ {
+ throw new IllegalStateException( "Client is not connected." );
+ }
+
+ // Setup the bind request
+ BindRequestImpl request = new BindRequestImpl( 2 );
+ request.setName( new DN( "uid=admin,ou=system" ) );
+ request.setSimple( false );
+ request.setCredentials( type3response );
+ request.setSaslMechanism( mechanism );
+ request.setVersion3( true );
+
+ // Setup the ASN1 Enoder and Decoder
+ MessageDecoder decoder = new MessageDecoder( new BinaryAttributeDetector()
+ {
+ public boolean isBinary( String attributeId )
+ {
+ return false;
+ }
+ } );
+
+ // Send encoded request to server
+ LdapProtocolEncoder encoder = new LdapProtocolEncoder();
+ ByteBuffer bb = encoder.encodeMessage( request );
+ bb.flip();
+
+ _output_.write( bb.array() );
+ _output_.flush();
+
+ while ( _input_.available() <= 0 )
+ {
+ Thread.sleep( 100 );
+ }
+
+ // Retrieve the response back from server to my last request.
+ return ( BindResponse ) decoder.decode( null, _input_ );
+ }
+ }
+
+
+ private BogusNtlmProvider getNtlmProviderUsingReflection()
+ {
+ BogusNtlmProvider provider = null;
+ try
+ {
+ NtlmMechanismHandler ntlmHandler = ( NtlmMechanismHandler ) ldapServer.getSaslMechanismHandlers().get(
+ SupportedSaslMechanisms.NTLM );
+
+ // there is no getter for 'provider' field hence this hack
+ Field field = ntlmHandler.getClass().getDeclaredField( "provider" );
+ field.setAccessible( true );
+ provider = ( BogusNtlmProvider ) field.get( ntlmHandler );
+ }
+ catch ( Exception e )
+ {
+ e.printStackTrace();
+ }
+
+ return provider;
+ }
+
+}