diff --git a/build.gradle b/build.gradle index 98ae149c..ad64d384 100644 --- a/build.gradle +++ b/build.gradle @@ -17,11 +17,13 @@ buildscript { classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.28.2" classpath 'org.hidetake:gradle-ssh-plugin:2.10.1' classpath 'io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.30.0' + classpath 'io.spring.javaformat:spring-javaformat-gradle-plugin:0.0.38' } } apply plugin: 'io.spring.convention.root' apply plugin: 'io.spring.convention.docs' +apply plugin: 'io.spring.javaformat' apply plugin: 's101' group = "org.springframework.ldap" @@ -60,4 +62,18 @@ asciidoctor { s101 { configurationDirectory = project.file("etc/s101") -} \ No newline at end of file +} + +allprojects { + if (!['spring-ldap-bom', 'spring-security-docs'].contains(project.name)) { + apply plugin: 'io.spring.javaformat' + + if (project.name.contains('sample')) { + tasks.whenTaskAdded { task -> + if (task.name.contains('format') || task.name.contains('checkFormat')) { + task.enabled = false + } + } + } + } +} diff --git a/core/src/main/java/org/springframework/LdapDataEntry.java b/core/src/main/java/org/springframework/LdapDataEntry.java index e26689b0..ee2d600c 100644 --- a/core/src/main/java/org/springframework/LdapDataEntry.java +++ b/core/src/main/java/org/springframework/LdapDataEntry.java @@ -11,49 +11,43 @@ import java.util.SortedSet; * @since 2.0 */ public interface LdapDataEntry { + /** - * Get the value of a String attribute. If more than one attribute value - * exists for the specified attribute, only the first one will be returned. - * If an attribute has no value, null will be returned. - * + * Get the value of a String attribute. If more than one attribute value exists for + * the specified attribute, only the first one will be returned. If an attribute has + * no value, null will be returned. * @param name name of the attribute. - * @return the value of the attribute if it exists, or null if - * the attribute doesn't exist or if it exists but with no value. + * @return the value of the attribute if it exists, or null if the + * attribute doesn't exist or if it exists but with no value. * @throws ClassCastException if the value of the entry is not a String. */ String getStringAttribute(String name); /** - * Get the value of an Object attribute. If more than one attribute value - * exists for the specified attribute, only the first one will be returned. - * If an attribute has no value, null will be returned. - * + * Get the value of an Object attribute. If more than one attribute value exists for + * the specified attribute, only the first one will be returned. If an attribute has + * no value, null will be returned. * @param name name of the attribute. - * @return the attribute value as an object if it exists, or - * null if the attribute doesn't exist or if it exists but with - * no value. + * @return the attribute value as an object if it exists, or null if the + * attribute doesn't exist or if it exists but with no value. */ Object getObjectAttribute(String name); /** - * Check if an Object attribute exists, regardless of whether it has a value - * or not. - * + * Check if an Object attribute exists, regardless of whether it has a value or not. * @param name name of the attribute - * @return true if the attribute exists, false - * otherwise + * @return true if the attribute exists, false otherwise */ boolean attributeExists(String name); /** - * Set the with the name name to the value. - * If the value is a {@link Name} instance, equality for Distinguished - * Names will be used for calculating attribute modifications. - * + * Set the with the name name to the value. If the value is + * a {@link Name} instance, equality for Distinguished Names will be used for + * calculating attribute modifications. * @param name name of the attribute. * @param value value to set the attribute to. - * @throws IllegalArgumentException if the value is a {@link Name} instance - * and one or several of the currently present attribute values is not + * @throws IllegalArgumentException if the value is a {@link Name} instance and one or + * several of the currently present attribute values is not * {@link Name} instances or Strings representing valid Distinguished Names. */ void setAttributeValue(String name, Object value); @@ -63,17 +57,15 @@ public interface LdapDataEntry { * * If value is null or value.length == 0 then the attribute will be removed. * - * If update mode, changes will be made only if the array has more or less - * objects or if one or more object has changed. Reordering the objects will - * not cause an update. - * - * If the values are {@link Name} instances, equality for Distinguished - * Names will be used for calculating attribute modifications. + * If update mode, changes will be made only if the array has more or less objects or + * if one or more object has changed. Reordering the objects will not cause an update. * + * If the values are {@link Name} instances, equality for Distinguished Names will be + * used for calculating attribute modifications. * @param name The id of the attribute. * @param values Attribute values. - * @throws IllegalArgumentException if value is a {@link Name} instance - * and one or several of the currently present attribute values is not + * @throws IllegalArgumentException if value is a {@link Name} instance and one or + * several of the currently present attribute values is not * {@link Name} instances or Strings representing valid Distinguished Names. */ void setAttributeValues(String name, Object[] values); @@ -83,130 +75,115 @@ public interface LdapDataEntry { * * If value is null or value.length == 0 then the attribute will be removed. * - * If update mode, changes will be made if the array has more or less - * objects or if one or more string has changed. + * If update mode, changes will be made if the array has more or less objects or if + * one or more string has changed. * - * Reordering the objects will only cause an update if orderMatters is set - * to true. + * Reordering the objects will only cause an update if orderMatters is set to true. * - * If the values are {@link Name} instances, equality for Distinguished - * Names will be used for calculating attribute modifications. + * If the values are {@link Name} instances, equality for Distinguished Names will be + * used for calculating attribute modifications. * @param name The id of the attribute. * @param values Attribute values. - * @param orderMatters If true, it will be changed even if data - * was just reordered. - * @throws IllegalArgumentException if value is a {@link Name} instance - * and one or several of the currently present attribute values is not + * @param orderMatters If true, it will be changed even if data was just + * reordered. + * @throws IllegalArgumentException if value is a {@link Name} instance and one or + * several of the currently present attribute values is not * {@link Name} instances or Strings representing valid Distinguished Names. */ void setAttributeValues(String name, Object[] values, boolean orderMatters); /** - * Add a value to the Attribute with the specified name. If the Attribute - * doesn't exist it will be created. This method makes sure that the there - * will be no duplicates of an added value - it the value exists it will not - * be added again. + * Add a value to the Attribute with the specified name. If the Attribute doesn't + * exist it will be created. This method makes sure that the there will be no + * duplicates of an added value - it the value exists it will not be added again. * - * If the value is a {@link Name} instance, equality for Distinguished - * Names will be used for calculating attribute modifications. - * - * @param name the name of the Attribute to which the specified value should - * be added. + * If the value is a {@link Name} instance, equality for Distinguished Names will be + * used for calculating attribute modifications. + * @param name the name of the Attribute to which the specified value should be added. * @param value the Attribute value to add. - * @throws IllegalArgumentException if value is a {@link Name} instance - * and one or several of the currently present attribute values is not + * @throws IllegalArgumentException if value is a {@link Name} instance and one or + * several of the currently present attribute values is not * {@link Name} instances or Strings representing valid Distinguished Names. */ void addAttributeValue(String name, Object value); /** - * Add a value to the Attribute with the specified name. If the Attribute - * doesn't exist it will be created. The addIfDuplicateExists - * parameter controls the handling of duplicates. It false, - * this method makes sure that the there will be no duplicates of an added - * value - it the value exists it will not be added again. + * Add a value to the Attribute with the specified name. If the Attribute doesn't + * exist it will be created. The addIfDuplicateExists parameter controls + * the handling of duplicates. It false, this method makes sure that the + * there will be no duplicates of an added value - it the value exists it will not be + * added again. * - * If the value is a {@link Name} instance, equality for Distinguished - * Names will be used for calculating attribute modifications. - * - * @param name the name of the Attribute to which the specified value should - * be added. + * If the value is a {@link Name} instance, equality for Distinguished Names will be + * used for calculating attribute modifications. + * @param name the name of the Attribute to which the specified value should be added. * @param value the Attribute value to add. - * @param addIfDuplicateExists true will add the value - * regardless of whether there is an identical value already, allowing for - * duplicate attribute values; false will not add the value if - * it already exists. - * @throws IllegalArgumentException if value is a {@link Name} instance - * and one or several of the currently present attribute values is not + * @param addIfDuplicateExists true will add the value regardless of + * whether there is an identical value already, allowing for duplicate attribute + * values; false will not add the value if it already exists. + * @throws IllegalArgumentException if value is a {@link Name} instance and one or + * several of the currently present attribute values is not * {@link Name} instances or Strings representing valid Distinguished Names. */ - void addAttributeValue(String name, Object value, - boolean addIfDuplicateExists); + void addAttributeValue(String name, Object value, boolean addIfDuplicateExists); /** - * Remove a value from the Attribute with the specified name. If the - * Attribute doesn't exist, do nothing. + * Remove a value from the Attribute with the specified name. If the Attribute doesn't + * exist, do nothing. * - * If the value is a {@link Name} instance, equality for Distinguished - * Names will be used for calculating attribute modifications. - * - * @param name the name of the Attribute from which the specified value - * should be removed. + * If the value is a {@link Name} instance, equality for Distinguished Names will be + * used for calculating attribute modifications. + * @param name the name of the Attribute from which the specified value should be + * removed. * @param value the value to remove. - * @throws IllegalArgumentException if value is a {@link Name} instance - * and one or several of the currently present attribute values is not + * @throws IllegalArgumentException if value is a {@link Name} instance and one or + * several of the currently present attribute values is not * {@link Name} instances or Strings representing valid Distinguished Names. */ void removeAttributeValue(String name, Object value); /** * Get all values of a String attribute. - * * @param name name of the attribute. - * @return a (possibly empty) array containing all registered values of the - * attribute as Strings if the attribute is defined or null - * otherwise. - * @throws IllegalArgumentException if any of the attribute values is not a - * String. + * @return a (possibly empty) array containing all registered values of the attribute + * as Strings if the attribute is defined or null otherwise. + * @throws IllegalArgumentException if any of the attribute values is not a String. */ String[] getStringAttributes(String name); /** * Get all values of an Object attribute. - * * @param name name of the attribute. - * @return a (possibly empty) array containing all registered values of the - * attribute if the attribute is defined or null otherwise. + * @return a (possibly empty) array containing all registered values of the attribute + * if the attribute is defined or null otherwise. * @since 1.3 */ Object[] getObjectAttributes(String name); /** * Get all String values of the attribute as a SortedSet. - * * @param name name of the attribute. - * @return a SortedSet containing all values of the attribute, - * or null if the attribute does not exist. - * @throws IllegalArgumentException if one of the found attribute values cannot be cast to a String. + * @return a SortedSet containing all values of the attribute, or + * null if the attribute does not exist. + * @throws IllegalArgumentException if one of the found attribute values cannot be + * cast to a String. */ SortedSet getAttributeSortedStringSet(String name); /** - * Returns the DN relative to the base path. - * NB: as of version 2.0 the returned name will be an LdapName instance. - * + * Returns the DN relative to the base path. NB: as of version 2.0 the returned + * name will be an LdapName instance. * @return The distinguished name of the current context. * * @see org.springframework.ldap.core.DirContextAdapter#getNameInNamespace() */ Name getDn(); - /** * Get all the Attributes. - * * @return all the Attributes. * @since 1.3 */ Attributes getAttributes(); + } diff --git a/core/src/main/java/org/springframework/ldap/AttributeInUseException.java b/core/src/main/java/org/springframework/ldap/AttributeInUseException.java index 695c8d3f..5e135364 100644 --- a/core/src/main/java/org/springframework/ldap/AttributeInUseException.java +++ b/core/src/main/java/org/springframework/ldap/AttributeInUseException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI AttributeInUseException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.AttributeInUseException */ public class AttributeInUseException extends NamingException { - public AttributeInUseException( - javax.naming.directory.AttributeInUseException cause) { + public AttributeInUseException(javax.naming.directory.AttributeInUseException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/AttributeModificationException.java b/core/src/main/java/org/springframework/ldap/AttributeModificationException.java index 0fb2d210..b5660cde 100644 --- a/core/src/main/java/org/springframework/ldap/AttributeModificationException.java +++ b/core/src/main/java/org/springframework/ldap/AttributeModificationException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI AttributeModificationException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.AttributeModificationException */ public class AttributeModificationException extends NamingException { - public AttributeModificationException( - javax.naming.directory.AttributeModificationException cause) { + public AttributeModificationException(javax.naming.directory.AttributeModificationException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/AuthenticationException.java b/core/src/main/java/org/springframework/ldap/AuthenticationException.java index 358f10a4..91a375aa 100644 --- a/core/src/main/java/org/springframework/ldap/AuthenticationException.java +++ b/core/src/main/java/org/springframework/ldap/AuthenticationException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI AuthenticationException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.AuthenticationException @@ -32,4 +32,5 @@ public class AuthenticationException extends NamingSecurityException { public AuthenticationException() { this(null); } + } diff --git a/core/src/main/java/org/springframework/ldap/AuthenticationNotSupportedException.java b/core/src/main/java/org/springframework/ldap/AuthenticationNotSupportedException.java index 05b5457f..f6881176 100644 --- a/core/src/main/java/org/springframework/ldap/AuthenticationNotSupportedException.java +++ b/core/src/main/java/org/springframework/ldap/AuthenticationNotSupportedException.java @@ -18,16 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI AuthenticationNotSupportedException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.AuthenticationNotSupportedException */ -public class AuthenticationNotSupportedException extends - NamingSecurityException { +public class AuthenticationNotSupportedException extends NamingSecurityException { - public AuthenticationNotSupportedException( - javax.naming.AuthenticationNotSupportedException cause) { + public AuthenticationNotSupportedException(javax.naming.AuthenticationNotSupportedException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/BadLdapGrammarException.java b/core/src/main/java/org/springframework/ldap/BadLdapGrammarException.java index c76eeb10..f95b2daa 100644 --- a/core/src/main/java/org/springframework/ldap/BadLdapGrammarException.java +++ b/core/src/main/java/org/springframework/ldap/BadLdapGrammarException.java @@ -17,9 +17,9 @@ package org.springframework.ldap; /** - * Thrown to indicate that an invalid value has been supplied to an LDAP - * operation. This could be an invalid filter or dn. - * + * Thrown to indicate that an invalid value has been supplied to an LDAP operation. This + * could be an invalid filter or dn. + * * @author Mattias Hellborg Arthursson */ public class BadLdapGrammarException extends NamingException { @@ -33,4 +33,5 @@ public class BadLdapGrammarException extends NamingException { public BadLdapGrammarException(String message, Throwable cause) { super(message, cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/CannotProceedException.java b/core/src/main/java/org/springframework/ldap/CannotProceedException.java index e0fab50c..df7febdc 100644 --- a/core/src/main/java/org/springframework/ldap/CannotProceedException.java +++ b/core/src/main/java/org/springframework/ldap/CannotProceedException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI CannotProceedException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.CannotProceedException @@ -28,4 +28,5 @@ public class CannotProceedException extends NamingException { public CannotProceedException(javax.naming.CannotProceedException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/CommunicationException.java b/core/src/main/java/org/springframework/ldap/CommunicationException.java index 308632bd..60913c01 100644 --- a/core/src/main/java/org/springframework/ldap/CommunicationException.java +++ b/core/src/main/java/org/springframework/ldap/CommunicationException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI CommunicationException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.CommunicationException @@ -28,4 +28,5 @@ public class CommunicationException extends NamingException { public CommunicationException(javax.naming.CommunicationException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/ConfigurationException.java b/core/src/main/java/org/springframework/ldap/ConfigurationException.java index 65a55eb6..48cf393c 100644 --- a/core/src/main/java/org/springframework/ldap/ConfigurationException.java +++ b/core/src/main/java/org/springframework/ldap/ConfigurationException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI ConfigurationException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.ConfigurationException @@ -28,4 +28,5 @@ public class ConfigurationException extends NamingException { public ConfigurationException(javax.naming.ConfigurationException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/ContextNotEmptyException.java b/core/src/main/java/org/springframework/ldap/ContextNotEmptyException.java index 58b3cc18..8418a444 100644 --- a/core/src/main/java/org/springframework/ldap/ContextNotEmptyException.java +++ b/core/src/main/java/org/springframework/ldap/ContextNotEmptyException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI ContextNotEmptyException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.ContextNotEmptyException @@ -28,4 +28,5 @@ public class ContextNotEmptyException extends NamingException { public ContextNotEmptyException(javax.naming.ContextNotEmptyException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/InsufficientResourcesException.java b/core/src/main/java/org/springframework/ldap/InsufficientResourcesException.java index 15773801..a853c5dc 100644 --- a/core/src/main/java/org/springframework/ldap/InsufficientResourcesException.java +++ b/core/src/main/java/org/springframework/ldap/InsufficientResourcesException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI InsufficientResourcesException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.InsufficientResourcesException */ public class InsufficientResourcesException extends NamingException { - public InsufficientResourcesException( - javax.naming.InsufficientResourcesException cause) { + public InsufficientResourcesException(javax.naming.InsufficientResourcesException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/InterruptedNamingException.java b/core/src/main/java/org/springframework/ldap/InterruptedNamingException.java index 14954897..6208805f 100644 --- a/core/src/main/java/org/springframework/ldap/InterruptedNamingException.java +++ b/core/src/main/java/org/springframework/ldap/InterruptedNamingException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI InterruptedNamingException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.InterruptedNamingException */ public class InterruptedNamingException extends NamingException { - public InterruptedNamingException( - javax.naming.InterruptedNamingException cause) { + public InterruptedNamingException(javax.naming.InterruptedNamingException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/InvalidAttributeIdentifierException.java b/core/src/main/java/org/springframework/ldap/InvalidAttributeIdentifierException.java index 2f51a32b..cdbcc392 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidAttributeIdentifierException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidAttributeIdentifierException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI InvalidAttributeIdentifierException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.InvalidAttributeIdentifierException */ public class InvalidAttributeIdentifierException extends NamingException { - public InvalidAttributeIdentifierException( - javax.naming.directory.InvalidAttributeIdentifierException cause) { + public InvalidAttributeIdentifierException(javax.naming.directory.InvalidAttributeIdentifierException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/InvalidAttributeValueException.java b/core/src/main/java/org/springframework/ldap/InvalidAttributeValueException.java index cd003735..77570b87 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidAttributeValueException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidAttributeValueException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI InvalidAttributeValueException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.InvalidAttributeValueException */ public class InvalidAttributeValueException extends NamingException { - public InvalidAttributeValueException( - javax.naming.directory.InvalidAttributeValueException cause) { + public InvalidAttributeValueException(javax.naming.directory.InvalidAttributeValueException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/InvalidAttributesException.java b/core/src/main/java/org/springframework/ldap/InvalidAttributesException.java index 7085ed34..27dbe24e 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidAttributesException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidAttributesException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI InvalidAttributesException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.InvalidAttributesException */ public class InvalidAttributesException extends NamingException { - public InvalidAttributesException( - javax.naming.directory.InvalidAttributesException cause) { + public InvalidAttributesException(javax.naming.directory.InvalidAttributesException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/InvalidNameException.java b/core/src/main/java/org/springframework/ldap/InvalidNameException.java index d88f9e2e..7197b860 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidNameException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidNameException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI InvalidNameException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.InvalidNameException @@ -28,4 +28,5 @@ public class InvalidNameException extends NamingException { public InvalidNameException(javax.naming.InvalidNameException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/InvalidSearchControlsException.java b/core/src/main/java/org/springframework/ldap/InvalidSearchControlsException.java index 0dbaad11..49423b43 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidSearchControlsException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidSearchControlsException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI InvalidSearchControlsException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.InvalidSearchControlsException */ public class InvalidSearchControlsException extends NamingException { - public InvalidSearchControlsException( - javax.naming.directory.InvalidSearchControlsException cause) { + public InvalidSearchControlsException(javax.naming.directory.InvalidSearchControlsException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/InvalidSearchFilterException.java b/core/src/main/java/org/springframework/ldap/InvalidSearchFilterException.java index 4dbb425f..4d1e311e 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidSearchFilterException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidSearchFilterException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI InvalidSearchFilterException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.InvalidSearchFilterException */ public class InvalidSearchFilterException extends NamingException { - public InvalidSearchFilterException( - javax.naming.directory.InvalidSearchFilterException cause) { + public InvalidSearchFilterException(javax.naming.directory.InvalidSearchFilterException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/LdapReferralException.java b/core/src/main/java/org/springframework/ldap/LdapReferralException.java index 2bd876d1..04b48e24 100644 --- a/core/src/main/java/org/springframework/ldap/LdapReferralException.java +++ b/core/src/main/java/org/springframework/ldap/LdapReferralException.java @@ -18,11 +18,11 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI LdapReferralException. - * - * This class is not abstract. We need to be able to instantiate it, should the - * caught exception be a provider-specific subclass of + * + * This class is not abstract. We need to be able to instantiate it, should the caught + * exception be a provider-specific subclass of * {@link javax.naming.ldap.LdapReferralException}. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.ldap.LdapReferralException @@ -32,4 +32,5 @@ public class LdapReferralException extends ReferralException { public LdapReferralException(javax.naming.ldap.LdapReferralException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/LimitExceededException.java b/core/src/main/java/org/springframework/ldap/LimitExceededException.java index 83013401..8c37157f 100644 --- a/core/src/main/java/org/springframework/ldap/LimitExceededException.java +++ b/core/src/main/java/org/springframework/ldap/LimitExceededException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI LimitExceededException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.LimitExceededException @@ -28,4 +28,5 @@ public class LimitExceededException extends NamingException { public LimitExceededException(javax.naming.LimitExceededException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/LinkException.java b/core/src/main/java/org/springframework/ldap/LinkException.java index 77bc196c..a9385458 100644 --- a/core/src/main/java/org/springframework/ldap/LinkException.java +++ b/core/src/main/java/org/springframework/ldap/LinkException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI LinkException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.LinkException @@ -28,4 +28,5 @@ public class LinkException extends NamingException { public LinkException(javax.naming.LinkException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/LinkLoopException.java b/core/src/main/java/org/springframework/ldap/LinkLoopException.java index 20786509..6fcfac52 100644 --- a/core/src/main/java/org/springframework/ldap/LinkLoopException.java +++ b/core/src/main/java/org/springframework/ldap/LinkLoopException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI LinkLoopException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.LinkLoopException @@ -28,4 +28,5 @@ public class LinkLoopException extends LinkException { public LinkLoopException(javax.naming.LinkLoopException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/MalformedLinkException.java b/core/src/main/java/org/springframework/ldap/MalformedLinkException.java index 4190b49d..b63e0590 100644 --- a/core/src/main/java/org/springframework/ldap/MalformedLinkException.java +++ b/core/src/main/java/org/springframework/ldap/MalformedLinkException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI MalformedLinkException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.MalformedLinkException @@ -28,4 +28,5 @@ public class MalformedLinkException extends LinkException { public MalformedLinkException(javax.naming.MalformedLinkException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/NameAlreadyBoundException.java b/core/src/main/java/org/springframework/ldap/NameAlreadyBoundException.java index 13f73087..33592059 100644 --- a/core/src/main/java/org/springframework/ldap/NameAlreadyBoundException.java +++ b/core/src/main/java/org/springframework/ldap/NameAlreadyBoundException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI NameAlreadyBoundException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.NameAlreadyBoundException */ public class NameAlreadyBoundException extends NamingException { - public NameAlreadyBoundException( - javax.naming.NameAlreadyBoundException cause) { + public NameAlreadyBoundException(javax.naming.NameAlreadyBoundException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/NameNotFoundException.java b/core/src/main/java/org/springframework/ldap/NameNotFoundException.java index ef1956a2..283f1e68 100644 --- a/core/src/main/java/org/springframework/ldap/NameNotFoundException.java +++ b/core/src/main/java/org/springframework/ldap/NameNotFoundException.java @@ -18,13 +18,13 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI NameNotFoundException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.NameNotFoundException */ public class NameNotFoundException extends NamingException { - + public NameNotFoundException(String msg) { super(msg); } @@ -32,4 +32,5 @@ public class NameNotFoundException extends NamingException { public NameNotFoundException(javax.naming.NameNotFoundException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/NamingException.java b/core/src/main/java/org/springframework/ldap/NamingException.java index 43a93ef3..40e387a8 100644 --- a/core/src/main/java/org/springframework/ldap/NamingException.java +++ b/core/src/main/java/org/springframework/ldap/NamingException.java @@ -25,9 +25,9 @@ import javax.naming.Name; import org.springframework.core.NestedRuntimeException; /** - * Base class for exception thrown by the framework whenever it encounters a - * problem related to LDAP. - * + * Base class for exception thrown by the framework whenever it encounters a problem + * related to LDAP. + * * @author Ulrik Sandberg * @since 1.2 */ @@ -36,12 +36,11 @@ public abstract class NamingException extends NestedRuntimeException { private Throwable cause; /** - * Overrides {@link NestedRuntimeException#getCause()} since serialization - * always tries to serialize the base class before the subclass. Our - * cause may have a resolvedObj that is not - * serializable. By storing the cause in this class, we get a chance at - * temporarily nulling the cause before serialization, thus in effect making - * the current instance serializable. + * Overrides {@link NestedRuntimeException#getCause()} since serialization always + * tries to serialize the base class before the subclass. Our cause may have + * a resolvedObj that is not serializable. By storing the cause in this + * class, we get a chance at temporarily nulling the cause before serialization, thus + * in effect making the current instance serializable. */ public Throwable getCause() { // Even if you cannot set the cause of this exception other than through @@ -53,9 +52,7 @@ public abstract class NamingException extends NestedRuntimeException { /** * Constructor that takes a message. - * - * @param msg - * the detail message + * @param msg the detail message */ public NamingException(String msg) { super(msg); @@ -63,13 +60,9 @@ public abstract class NamingException extends NestedRuntimeException { /** * Constructor that allows a message and a root cause. - * - * @param msg - * the detail message - * @param cause - * the cause of the exception. This argument is generally - * expected to be a proper subclass of - * {@link javax.naming.NamingException}. + * @param msg the detail message + * @param cause the cause of the exception. This argument is generally expected to be + * a proper subclass of {@link javax.naming.NamingException}. */ public NamingException(String msg, Throwable cause) { super(msg); @@ -77,26 +70,21 @@ public abstract class NamingException extends NestedRuntimeException { } /** - * Constructor that allows a plain root cause, intended for subclasses - * mirroring corresponding javax.naming exceptions. - * - * @param cause - * the cause of the exception. This argument is generally - * expected to be a proper subclass of - * {@link javax.naming.NamingException}. + * Constructor that allows a plain root cause, intended for subclasses mirroring + * corresponding javax.naming exceptions. + * @param cause the cause of the exception. This argument is generally expected to be + * a proper subclass of {@link javax.naming.NamingException}. */ public NamingException(Throwable cause) { this(cause != null ? cause.getMessage() : null, cause); } /** - * Convenience method to get the explanation associated with this exception, - * if the root cause was an instance of {@link javax.naming.NamingException}. - * - * @return a detail string explaining more about this exception if the root - * cause is an instance of javax.naming.NamingException, or - * null if there is no detail message for this - * exception + * Convenience method to get the explanation associated with this exception, if the + * root cause was an instance of {@link javax.naming.NamingException}. + * @return a detail string explaining more about this exception if the root cause is + * an instance of javax.naming.NamingException, or null if there is no + * detail message for this exception */ public String getExplanation() { if (getCause() instanceof javax.naming.NamingException) { @@ -106,49 +94,42 @@ public abstract class NamingException extends NestedRuntimeException { } /** - * Convenience method to get the unresolved part of the name associated with - * this exception, if the root cause was an instance of + * Convenience method to get the unresolved part of the name associated with this + * exception, if the root cause was an instance of * {@link javax.naming.NamingException}. - * - * @return a composite name describing the part of the name that has not - * been resolved if the root cause is an instance of - * javax.naming.NamingException, or null if the - * remaining name field has not been set + * @return a composite name describing the part of the name that has not been resolved + * if the root cause is an instance of javax.naming.NamingException, or + * null if the remaining name field has not been set */ public Name getRemainingName() { if (getCause() instanceof javax.naming.NamingException) { - return ((javax.naming.NamingException) getCause()) - .getRemainingName(); + return ((javax.naming.NamingException) getCause()).getRemainingName(); } return null; } /** - * Convenience method to get the leading portion of the resolved name - * associated with this exception, if the root cause was an instance of + * Convenience method to get the leading portion of the resolved name associated with + * this exception, if the root cause was an instance of * {@link javax.naming.NamingException}. - * - * @return a composite name describing the leading portion of the name - * that was resolved successfully if the root cause is an instance - * of javax.naming.NamingException, or null if the - * resolved name field has not been set + * @return a composite name describing the leading portion of the name that was + * resolved successfully if the root cause is an instance of + * javax.naming.NamingException, or null if the resolved name field has + * not been set */ public Name getResolvedName() { if (getCause() instanceof javax.naming.NamingException) { - return ((javax.naming.NamingException) getCause()) - .getResolvedName(); + return ((javax.naming.NamingException) getCause()).getResolvedName(); } return null; } /** - * Convenience method to get the resolved object associated with this - * exception, if the root cause was an instance of - * {@link javax.naming.NamingException}. - * - * @return the object that was resolved so far if the root cause is an - * instance of javax.naming.NamingException, or null - * if the resolved object field has not been set + * Convenience method to get the resolved object associated with this exception, if + * the root cause was an instance of {@link javax.naming.NamingException}. + * @return the object that was resolved so far if the root cause is an instance of + * javax.naming.NamingException, or null if the resolved object field has + * not been set */ public Object getResolvedObj() { if (getCause() instanceof javax.naming.NamingException) { @@ -158,14 +139,11 @@ public abstract class NamingException extends NestedRuntimeException { } /** - * Checks if the resolvedObj of the causing exception is - * suspected to be non-serializable, and if so temporarily nulls it before - * calling the default serialization mechanism. - * - * @param stream - * the stream onto which this object is serialized - * @throws IOException - * if there is an error writing this object to the stream + * Checks if the resolvedObj of the causing exception is suspected to be + * non-serializable, and if so temporarily nulls it before calling the default + * serialization mechanism. + * @param stream the stream onto which this object is serialized + * @throws IOException if there is an error writing this object to the stream */ private void writeObject(ObjectOutputStream stream) throws IOException { Object resolvedObj = getResolvedObj(); @@ -176,11 +154,14 @@ public abstract class NamingException extends NestedRuntimeException { namingException.setResolvedObj(null); try { stream.defaultWriteObject(); - } finally { + } + finally { namingException.setResolvedObj(resolvedObj); } - } else { + } + else { stream.defaultWriteObject(); } } + } diff --git a/core/src/main/java/org/springframework/ldap/NamingSecurityException.java b/core/src/main/java/org/springframework/ldap/NamingSecurityException.java index 790c2669..c96666e3 100644 --- a/core/src/main/java/org/springframework/ldap/NamingSecurityException.java +++ b/core/src/main/java/org/springframework/ldap/NamingSecurityException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI NamingSecurityException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.NamingSecurityException @@ -28,4 +28,5 @@ public class NamingSecurityException extends NamingException { public NamingSecurityException(javax.naming.NamingSecurityException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/NoInitialContextException.java b/core/src/main/java/org/springframework/ldap/NoInitialContextException.java index 3613039a..d7368f7e 100644 --- a/core/src/main/java/org/springframework/ldap/NoInitialContextException.java +++ b/core/src/main/java/org/springframework/ldap/NoInitialContextException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI NoInitialContextException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.NoInitialContextException */ public class NoInitialContextException extends NamingException { - public NoInitialContextException( - javax.naming.NoInitialContextException cause) { + public NoInitialContextException(javax.naming.NoInitialContextException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/NoPermissionException.java b/core/src/main/java/org/springframework/ldap/NoPermissionException.java index e8d78b0a..6cf8aafb 100644 --- a/core/src/main/java/org/springframework/ldap/NoPermissionException.java +++ b/core/src/main/java/org/springframework/ldap/NoPermissionException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI NoPermissionException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.NoPermissionException @@ -28,4 +28,5 @@ public class NoPermissionException extends NamingSecurityException { public NoPermissionException(javax.naming.NoPermissionException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/NoSuchAttributeException.java b/core/src/main/java/org/springframework/ldap/NoSuchAttributeException.java index befa8546..df62bf6a 100644 --- a/core/src/main/java/org/springframework/ldap/NoSuchAttributeException.java +++ b/core/src/main/java/org/springframework/ldap/NoSuchAttributeException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI NoSuchAttributeException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.NoSuchAttributeException @@ -32,4 +32,5 @@ public class NoSuchAttributeException extends NamingException { public NoSuchAttributeException(javax.naming.directory.NoSuchAttributeException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/NotContextException.java b/core/src/main/java/org/springframework/ldap/NotContextException.java index 544d66f5..a0a1196a 100644 --- a/core/src/main/java/org/springframework/ldap/NotContextException.java +++ b/core/src/main/java/org/springframework/ldap/NotContextException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI NotContextException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.NotContextException @@ -28,4 +28,5 @@ public class NotContextException extends NamingException { public NotContextException(javax.naming.NotContextException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/OperationNotSupportedException.java b/core/src/main/java/org/springframework/ldap/OperationNotSupportedException.java index 19a07091..274895c6 100644 --- a/core/src/main/java/org/springframework/ldap/OperationNotSupportedException.java +++ b/core/src/main/java/org/springframework/ldap/OperationNotSupportedException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI OperationNotSupportedException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.OperationNotSupportedException */ public class OperationNotSupportedException extends NamingException { - public OperationNotSupportedException( - javax.naming.OperationNotSupportedException cause) { + public OperationNotSupportedException(javax.naming.OperationNotSupportedException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/PartialResultException.java b/core/src/main/java/org/springframework/ldap/PartialResultException.java index 6af1b724..f7ece082 100644 --- a/core/src/main/java/org/springframework/ldap/PartialResultException.java +++ b/core/src/main/java/org/springframework/ldap/PartialResultException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI PartialResultException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.PartialResultException @@ -28,4 +28,5 @@ public class PartialResultException extends NamingException { public PartialResultException(javax.naming.PartialResultException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/ReferralException.java b/core/src/main/java/org/springframework/ldap/ReferralException.java index 9a48144f..e6bf27f4 100644 --- a/core/src/main/java/org/springframework/ldap/ReferralException.java +++ b/core/src/main/java/org/springframework/ldap/ReferralException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI ReferralException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.ReferralException @@ -28,4 +28,5 @@ public class ReferralException extends NamingException { public ReferralException(javax.naming.ReferralException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/SchemaViolationException.java b/core/src/main/java/org/springframework/ldap/SchemaViolationException.java index dd6022f9..b2021a1a 100644 --- a/core/src/main/java/org/springframework/ldap/SchemaViolationException.java +++ b/core/src/main/java/org/springframework/ldap/SchemaViolationException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI SchemaViolationException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.directory.SchemaViolationException */ public class SchemaViolationException extends NamingException { - public SchemaViolationException( - javax.naming.directory.SchemaViolationException cause) { + public SchemaViolationException(javax.naming.directory.SchemaViolationException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/ServiceUnavailableException.java b/core/src/main/java/org/springframework/ldap/ServiceUnavailableException.java index a89ea48b..900880a8 100644 --- a/core/src/main/java/org/springframework/ldap/ServiceUnavailableException.java +++ b/core/src/main/java/org/springframework/ldap/ServiceUnavailableException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI ServiceUnavailableException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.ServiceUnavailableException */ public class ServiceUnavailableException extends NamingException { - public ServiceUnavailableException( - javax.naming.ServiceUnavailableException cause) { + public ServiceUnavailableException(javax.naming.ServiceUnavailableException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/SizeLimitExceededException.java b/core/src/main/java/org/springframework/ldap/SizeLimitExceededException.java index 17e66bdc..9d0df109 100644 --- a/core/src/main/java/org/springframework/ldap/SizeLimitExceededException.java +++ b/core/src/main/java/org/springframework/ldap/SizeLimitExceededException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI SizeLimitExceededException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.SizeLimitExceededException */ public class SizeLimitExceededException extends LimitExceededException { - public SizeLimitExceededException( - javax.naming.SizeLimitExceededException cause) { + public SizeLimitExceededException(javax.naming.SizeLimitExceededException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/TimeLimitExceededException.java b/core/src/main/java/org/springframework/ldap/TimeLimitExceededException.java index 6f2c8f59..1b4dfdc4 100644 --- a/core/src/main/java/org/springframework/ldap/TimeLimitExceededException.java +++ b/core/src/main/java/org/springframework/ldap/TimeLimitExceededException.java @@ -18,15 +18,15 @@ package org.springframework.ldap; /** * Runtime exception mirroring the JNDI TimeLimitExceededException. - * + * * @author Ulrik Sandberg * @since 1.2 * @see javax.naming.TimeLimitExceededException */ public class TimeLimitExceededException extends LimitExceededException { - public TimeLimitExceededException( - javax.naming.TimeLimitExceededException cause) { + public TimeLimitExceededException(javax.naming.TimeLimitExceededException cause) { super(cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/UncategorizedLdapException.java b/core/src/main/java/org/springframework/ldap/UncategorizedLdapException.java index 92b53bcd..039cad5b 100644 --- a/core/src/main/java/org/springframework/ldap/UncategorizedLdapException.java +++ b/core/src/main/java/org/springframework/ldap/UncategorizedLdapException.java @@ -18,7 +18,7 @@ package org.springframework.ldap; /** * NamingException to be thrown when no other matching subclass is found. - * + * * @author Ulrik Sandberg * @since 1.2 */ @@ -35,4 +35,5 @@ public class UncategorizedLdapException extends NamingException { public UncategorizedLdapException(Throwable cause) { super("Uncategorized exception occured during LDAP processing", cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/aot/hint/LdapCoreRuntimeHints.java b/core/src/main/java/org/springframework/ldap/aot/hint/LdapCoreRuntimeHints.java index e9a05d69..6844176d 100644 --- a/core/src/main/java/org/springframework/ldap/aot/hint/LdapCoreRuntimeHints.java +++ b/core/src/main/java/org/springframework/ldap/aot/hint/LdapCoreRuntimeHints.java @@ -68,9 +68,9 @@ class LdapCoreRuntimeHints implements RuntimeHintsRegistrar { hints.reflection().registerTypeIfPresent(classLoader, "com.sun.jndi.ldap.ctl.SortResponseControl", (builder) -> builder.onReachableType(SortControlDirContextProcessor.class) .withMembers(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)); - hints.reflection().registerType(TypeReference.of("javax.net.ssl.SSLSocketFactory"), (builder) -> builder - .withMethod("getDefault", Collections.emptyList(), ExecutableMode.INVOKE) - .onReachableType(TypeReference.of("com.sun.jndi.ldap.Connection"))); + hints.reflection().registerType(TypeReference.of("javax.net.ssl.SSLSocketFactory"), + (builder) -> builder.withMethod("getDefault", Collections.emptyList(), ExecutableMode.INVOKE) + .onReachableType(TypeReference.of("com.sun.jndi.ldap.Connection"))); } } diff --git a/core/src/main/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecorator.java b/core/src/main/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecorator.java index f25e8bad..7c03db83 100644 --- a/core/src/main/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecorator.java +++ b/core/src/main/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecorator.java @@ -20,21 +20,19 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.ldap.core.AuthenticationSource; /** - * Decorator on AuthenticationSource to have default authentication information - * be returned should the target return empty principal and credentials. Useful - * in combination with AcegiAuthenticationSource if users are to be - * allowed to read some information even though they are not logged in. + * Decorator on AuthenticationSource to have default authentication information be + * returned should the target return empty principal and credentials. Useful in + * combination with AcegiAuthenticationSource if users are to be allowed to + * read some information even though they are not logged in. *

- * Note: The defaultUser should be an non-privileged - * user. This is important as this is the one that will be used when no user is - * logged in (i.e. empty principal is returned from the target - * AuthenticationSource). - * + * Note: The defaultUser should be an non-privileged user. This is + * important as this is the one that will be used when no user is logged in (i.e. empty + * principal is returned from the target AuthenticationSource). + * * @author Mattias Hellborg Arthursson - * + * */ -public class DefaultValuesAuthenticationSourceDecorator implements - AuthenticationSource, InitializingBean { +public class DefaultValuesAuthenticationSourceDecorator implements AuthenticationSource, InitializingBean { private AuthenticationSource target; @@ -50,18 +48,13 @@ public class DefaultValuesAuthenticationSourceDecorator implements /** * Constructor to setup instance directly. - * - * @param target - * the target AuthenticationSource. - * @param defaultUser - * dn of the user to use when the target returns an empty - * principal. - * @param defaultPassword - * password of the user to use when the target returns an empty - * principal. + * @param target the target AuthenticationSource. + * @param defaultUser dn of the user to use when the target returns an empty + * principal. + * @param defaultPassword password of the user to use when the target returns an empty + * principal. */ - public DefaultValuesAuthenticationSourceDecorator( - AuthenticationSource target, String defaultUser, + public DefaultValuesAuthenticationSourceDecorator(AuthenticationSource target, String defaultUser, String defaultPassword) { this.target = target; this.defaultUser = defaultUser; @@ -69,54 +62,48 @@ public class DefaultValuesAuthenticationSourceDecorator implements } /** - * Checks if the target's principal is not empty; if not, the credentials - * from the target is returned - otherwise return the - * defaultPassword. - * + * Checks if the target's principal is not empty; if not, the credentials from the + * target is returned - otherwise return the defaultPassword. * @return the target's password if the target's principal is not empty, the - * defaultPassword otherwise. + * defaultPassword otherwise. */ public String getCredentials() { if (StringUtils.hasText(target.getPrincipal())) { return target.getCredentials(); - } else { + } + else { return defaultPassword; } } /** - * Checks if the target's principal is not empty; if not, this is returned - - * otherwise return the defaultPassword. - * - * @return the target's principal if it is not empty, the - * defaultPassword otherwise. + * Checks if the target's principal is not empty; if not, this is returned - otherwise + * return the defaultPassword. + * @return the target's principal if it is not empty, the defaultPassword + * otherwise. */ public String getPrincipal() { String principal = target.getPrincipal(); if (StringUtils.hasText(principal)) { return principal; - } else { + } + else { return defaultUser; } } /** * Set the password of the default user. - * - * @param defaultPassword - * the password of the default user. + * @param defaultPassword the password of the default user. */ public void setDefaultPassword(String defaultPassword) { this.defaultPassword = defaultPassword; } /** - * Set the default user DN. This should be a non-privileged user, since it - * will be used when no authentication information is returned from the - * target. - * - * @param defaultUser - * DN of the default user. + * Set the default user DN. This should be a non-privileged user, since it will be + * used when no authentication information is returned from the target. + * @param defaultUser DN of the default user. */ public void setDefaultUser(String defaultUser) { this.defaultUser = defaultUser; @@ -124,9 +111,7 @@ public class DefaultValuesAuthenticationSourceDecorator implements /** * Set the target AuthenticationSource. - * - * @param target - * the target AuthenticationSource. + * @param target the target AuthenticationSource. */ public void setTarget(AuthenticationSource target) { this.target = target; @@ -134,23 +119,21 @@ public class DefaultValuesAuthenticationSourceDecorator implements /* * (non-Javadoc) - * + * * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet() */ public void afterPropertiesSet() throws Exception { if (target == null) { - throw new IllegalArgumentException( - "Property 'target' must be set.'"); + throw new IllegalArgumentException("Property 'target' must be set.'"); } if (defaultUser == null) { - throw new IllegalArgumentException( - "Property 'defaultUser' must be set.'"); + throw new IllegalArgumentException("Property 'defaultUser' must be set.'"); } if (defaultPassword == null) { - throw new IllegalArgumentException( - "Property 'defaultPassword' must be set.'"); + throw new IllegalArgumentException("Property 'defaultPassword' must be set.'"); } } + } diff --git a/core/src/main/java/org/springframework/ldap/config/ContextSourceParser.java b/core/src/main/java/org/springframework/ldap/config/ContextSourceParser.java index 15a90699..032f2f04 100644 --- a/core/src/main/java/org/springframework/ldap/config/ContextSourceParser.java +++ b/core/src/main/java/org/springframework/ldap/config/ContextSourceParser.java @@ -48,69 +48,123 @@ import static org.springframework.ldap.config.ParserUtils.getString; * @author Eddu Melendez */ public class ContextSourceParser implements BeanDefinitionParser { + private static final String ATT_ANONYMOUS_READ_ONLY = "anonymous-read-only"; + private static final String ATT_AUTHENTICATION_SOURCE_REF = "authentication-source-ref"; + private static final String ATT_AUTHENTICATION_STRATEGY_REF = "authentication-strategy-ref"; + private static final String ATT_BASE = "base"; + private static final String ATT_PASSWORD = "password"; + private static final String ATT_NATIVE_POOLING = "native-pooling"; + private static final String ATT_REFERRAL = "referral"; + private static final String ATT_URL = "url"; + private static final String ATT_BASE_ENV_PROPS_REF = "base-env-props-ref"; // pooling attributes private static final String ATT_MAX_ACTIVE = "max-active"; - private static final String ATT_MAX_TOTAL = "max-total"; - private static final String ATT_MAX_IDLE = "max-idle"; - private static final String ATT_MIN_IDLE = "min-idle"; - private static final String ATT_MAX_WAIT = "max-wait"; - private static final String ATT_WHEN_EXHAUSTED = "when-exhausted"; - private static final String ATT_TEST_ON_BORROW = "test-on-borrow"; - private static final String ATT_TEST_ON_RETURN = "test-on-return"; - private static final String ATT_TEST_WHILE_IDLE = "test-while-idle"; - private static final String ATT_EVICTION_RUN_MILLIS = "eviction-run-interval-millis"; - private static final String ATT_TESTS_PER_EVICTION_RUN = "tests-per-eviction-run"; - private static final String ATT_EVICTABLE_TIME_MILLIS = "min-evictable-time-millis"; - private static final String ATT_VALIDATION_QUERY_BASE = "validation-query-base"; - private static final String ATT_VALIDATION_QUERY_FILTER = "validation-query-filter"; - private static final String ATT_VALIDATION_QUERY_SEARCH_CONTROLS_REF = "validation-query-search-controls-ref"; - private static final String ATT_NON_TRANSIENT_EXCEPTIONS = "non-transient-exceptions"; - private static final String ATT_MAX_IDLE_PER_KEY = "max-idle-per-key"; - private static final String ATT_MIN_IDLE_PER_KEY = "min-idle-per-key"; - private static final String ATT_MAX_TOTAL_PER_KEY = "max-total-per-key"; - private static final String ATT_EVICTION_POLICY_CLASS = "eviction-policy-class"; - private static final String ATT_FAIRNESS = "fairness"; - private static final String ATT_JMX_ENABLE = "jmx-enable"; - private static final String ATT_JMX_NAME_BASE = "jmx-name-base"; - private static final String ATT_JMX_NAME_PREFIX = "jmx-name-prefix"; - private static final String ATT_LIFO = "lifo"; - private static final String ATT_BLOCK_WHEN_EXHAUSTED = "block-when-exhausted"; - private static final String ATT_TEST_ON_CREATE = "test-on-create"; - private static final String ATT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = "soft-min-evictable-idle-time-millis"; + private static final String ATT_MAX_TOTAL = "max-total"; + + private static final String ATT_MAX_IDLE = "max-idle"; + + private static final String ATT_MIN_IDLE = "min-idle"; + + private static final String ATT_MAX_WAIT = "max-wait"; + + private static final String ATT_WHEN_EXHAUSTED = "when-exhausted"; + + private static final String ATT_TEST_ON_BORROW = "test-on-borrow"; + + private static final String ATT_TEST_ON_RETURN = "test-on-return"; + + private static final String ATT_TEST_WHILE_IDLE = "test-while-idle"; + + private static final String ATT_EVICTION_RUN_MILLIS = "eviction-run-interval-millis"; + + private static final String ATT_TESTS_PER_EVICTION_RUN = "tests-per-eviction-run"; + + private static final String ATT_EVICTABLE_TIME_MILLIS = "min-evictable-time-millis"; + + private static final String ATT_VALIDATION_QUERY_BASE = "validation-query-base"; + + private static final String ATT_VALIDATION_QUERY_FILTER = "validation-query-filter"; + + private static final String ATT_VALIDATION_QUERY_SEARCH_CONTROLS_REF = "validation-query-search-controls-ref"; + + private static final String ATT_NON_TRANSIENT_EXCEPTIONS = "non-transient-exceptions"; + + private static final String ATT_MAX_IDLE_PER_KEY = "max-idle-per-key"; + + private static final String ATT_MIN_IDLE_PER_KEY = "min-idle-per-key"; + + private static final String ATT_MAX_TOTAL_PER_KEY = "max-total-per-key"; + + private static final String ATT_EVICTION_POLICY_CLASS = "eviction-policy-class"; + + private static final String ATT_FAIRNESS = "fairness"; + + private static final String ATT_JMX_ENABLE = "jmx-enable"; + + private static final String ATT_JMX_NAME_BASE = "jmx-name-base"; + + private static final String ATT_JMX_NAME_PREFIX = "jmx-name-prefix"; + + private static final String ATT_LIFO = "lifo"; + + private static final String ATT_BLOCK_WHEN_EXHAUSTED = "block-when-exhausted"; + + private static final String ATT_TEST_ON_CREATE = "test-on-create"; + + private static final String ATT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = "soft-min-evictable-idle-time-millis"; private static final String ATT_USERNAME = "username"; static final String DEFAULT_ID = "contextSource"; + private static final int DEFAULT_MAX_ACTIVE = 8; + private static final int DEFAULT_MAX_TOTAL = -1; + private static final int DEFAULT_MAX_IDLE = 8; + private static final int DEFAULT_MIN_IDLE = 0; + private static final int DEFAULT_MAX_WAIT = -1; + private static final int DEFAULT_EVICTION_RUN_MILLIS = -1; + private static final int DEFAULT_TESTS_PER_EVICTION_RUN = 3; + private static final int DEFAULT_EVICTABLE_MILLIS = 1000 * 60 * 30; + private static final int DEFAULT_MAX_TOTAL_PER_KEY = 8; + private static final int DEFAULT_MAX_IDLE_PER_KEY = 8; + private static final int DEFAULT_MIN_IDLE_PER_KEY = 0; - private static final String DEFAULT_EVICTION_POLICY_CLASS_NAME = - "org.apache.commons.pool2.impl.DefaultEvictionPolicy"; + + private static final String DEFAULT_EVICTION_POLICY_CLASS_NAME = "org.apache.commons.pool2.impl.DefaultEvictionPolicy"; + private static final boolean DEFAULT_FAIRNESS = false; + private static final boolean DEFAULT_JMX_ENABLE = true; + private static final String DEFAULT_JMX_NAME_BASE = null; + private static final String DEFAULT_JMX_NAME_PREFIX = "ldap-pool"; + private static final boolean DEFAULT_LIFO = true; + private static final int DEFAULT_MAX_WAIT_MILLIS = -1; + private static final boolean DEFAULT_BLOCK_WHEN_EXHAUSTED = true; + private static final int DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS = -1; @Override @@ -125,10 +179,8 @@ public class ContextSourceParser implements BeanDefinitionParser { builder.addPropertyValue("userDn", username); builder.addPropertyValue("password", password); - BeanDefinitionBuilder urlsBuilder = BeanDefinitionBuilder - .rootBeanDefinition(UrlsFactory.class) - .setFactoryMethod("urls") - .addConstructorArgValue(url); + BeanDefinitionBuilder urlsBuilder = BeanDefinitionBuilder.rootBeanDefinition(UrlsFactory.class) + .setFactoryMethod("urls").addConstructorArgValue(url); builder.addPropertyValue("urls", urlsBuilder.getBeanDefinition()); builder.addPropertyValue("base", getString(element, ATT_BASE, "")); @@ -140,20 +192,23 @@ public class ContextSourceParser implements BeanDefinitionParser { builder.addPropertyValue("pooled", nativePooling); String authStrategyRef = element.getAttribute(ATT_AUTHENTICATION_STRATEGY_REF); - if(StringUtils.hasText(authStrategyRef)) { + if (StringUtils.hasText(authStrategyRef)) { builder.addPropertyReference("authenticationStrategy", authStrategyRef); } String authSourceRef = element.getAttribute(ATT_AUTHENTICATION_SOURCE_REF); - if(StringUtils.hasText(authSourceRef)) { + if (StringUtils.hasText(authSourceRef)) { builder.addPropertyReference("authenticationSource", authSourceRef); - } else { - Assert.hasText(username, "username attribute must be specified unless an authentication-source-ref explicitly configured"); - Assert.hasText(password, "password attribute must be specified unless an authentication-source-ref explicitly configured"); + } + else { + Assert.hasText(username, + "username attribute must be specified unless an authentication-source-ref explicitly configured"); + Assert.hasText(password, + "password attribute must be specified unless an authentication-source-ref explicitly configured"); } String baseEnvPropsRef = element.getAttribute(ATT_BASE_ENV_PROPS_REF); - if(StringUtils.hasText(baseEnvPropsRef)) { + if (StringUtils.hasText(baseEnvPropsRef)) { builder.addPropertyReference("baseEnvironmentProperties", baseEnvPropsRef); } @@ -162,7 +217,8 @@ public class ContextSourceParser implements BeanDefinitionParser { BeanDefinition actualContextSourceDefinition = targetContextSourceDefinition; if (!anonymousReadOnly) { - BeanDefinitionBuilder proxyBuilder = BeanDefinitionBuilder.rootBeanDefinition(TransactionAwareContextSourceProxy.class); + BeanDefinitionBuilder proxyBuilder = BeanDefinitionBuilder + .rootBeanDefinition(TransactionAwareContextSourceProxy.class); proxyBuilder.addConstructorArgValue(targetContextSourceDefinition); actualContextSourceDefinition = proxyBuilder.getBeanDefinition(); } @@ -173,9 +229,7 @@ public class ContextSourceParser implements BeanDefinitionParser { return actualContextSourceDefinition; } - private BeanDefinition applyPoolingIfApplicable( - BeanDefinition targetContextSourceDefinition, - Element element, + private BeanDefinition applyPoolingIfApplicable(BeanDefinition targetContextSourceDefinition, Element element, boolean nativePooling) { Element poolingElement = DomUtils.getChildElementByTagName(element, Elements.POOLING); @@ -184,11 +238,12 @@ public class ContextSourceParser implements BeanDefinitionParser { if (pooling2Element != null && poolingElement != null) { throw new IllegalArgumentException( String.format("%s cannot be enabled together with %s.", Elements.POOLING2, Elements.POOLING)); - } else if (poolingElement == null && pooling2Element == null) { + } + else if (poolingElement == null && pooling2Element == null) { return targetContextSourceDefinition; } - if(nativePooling) { + if (nativePooling) { throw new IllegalArgumentException( String.format("%s cannot be enabled together with %s", ATT_NATIVE_POOLING, Elements.POOLING)); } @@ -209,20 +264,29 @@ public class ContextSourceParser implements BeanDefinitionParser { } return builder.getBeanDefinition(); - } else { + } + else { BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(PoolingContextSource.class); builder.addPropertyValue("contextSource", targetContextSourceDefinition); - builder.addPropertyValue("maxActive", getString(poolingElement, ATT_MAX_ACTIVE, String.valueOf(DEFAULT_MAX_ACTIVE))); - builder.addPropertyValue("maxTotal", getString(poolingElement, ATT_MAX_TOTAL, String.valueOf(DEFAULT_MAX_TOTAL))); - builder.addPropertyValue("maxIdle", getString(poolingElement, ATT_MAX_IDLE, String.valueOf(DEFAULT_MAX_IDLE))); - builder.addPropertyValue("minIdle", getString(poolingElement, ATT_MIN_IDLE, String.valueOf(DEFAULT_MIN_IDLE))); - builder.addPropertyValue("maxWait", getString(poolingElement, ATT_MAX_WAIT, String.valueOf(DEFAULT_MAX_WAIT))); + builder.addPropertyValue("maxActive", + getString(poolingElement, ATT_MAX_ACTIVE, String.valueOf(DEFAULT_MAX_ACTIVE))); + builder.addPropertyValue("maxTotal", + getString(poolingElement, ATT_MAX_TOTAL, String.valueOf(DEFAULT_MAX_TOTAL))); + builder.addPropertyValue("maxIdle", + getString(poolingElement, ATT_MAX_IDLE, String.valueOf(DEFAULT_MAX_IDLE))); + builder.addPropertyValue("minIdle", + getString(poolingElement, ATT_MIN_IDLE, String.valueOf(DEFAULT_MIN_IDLE))); + builder.addPropertyValue("maxWait", + getString(poolingElement, ATT_MAX_WAIT, String.valueOf(DEFAULT_MAX_WAIT))); String whenExhausted = getString(poolingElement, ATT_WHEN_EXHAUSTED, PoolExhaustedAction.BLOCK.name()); builder.addPropertyValue("whenExhaustedAction", PoolExhaustedAction.valueOf(whenExhausted).getValue()); - builder.addPropertyValue("timeBetweenEvictionRunsMillis", getString(poolingElement, ATT_EVICTION_RUN_MILLIS, String.valueOf(DEFAULT_EVICTION_RUN_MILLIS))); - builder.addPropertyValue("minEvictableIdleTimeMillis", getString(poolingElement, ATT_EVICTABLE_TIME_MILLIS, String.valueOf(DEFAULT_EVICTABLE_MILLIS))); - builder.addPropertyValue("numTestsPerEvictionRun", getString(poolingElement, ATT_TESTS_PER_EVICTION_RUN, String.valueOf(DEFAULT_TESTS_PER_EVICTION_RUN))); + builder.addPropertyValue("timeBetweenEvictionRunsMillis", + getString(poolingElement, ATT_EVICTION_RUN_MILLIS, String.valueOf(DEFAULT_EVICTION_RUN_MILLIS))); + builder.addPropertyValue("minEvictableIdleTimeMillis", + getString(poolingElement, ATT_EVICTABLE_TIME_MILLIS, String.valueOf(DEFAULT_EVICTABLE_MILLIS))); + builder.addPropertyValue("numTestsPerEvictionRun", getString(poolingElement, ATT_TESTS_PER_EVICTION_RUN, + String.valueOf(DEFAULT_TESTS_PER_EVICTION_RUN))); boolean testOnBorrow = getBoolean(poolingElement, ATT_TEST_ON_BORROW, false); boolean testOnReturn = getBoolean(poolingElement, ATT_TEST_ON_RETURN, false); @@ -236,34 +300,40 @@ public class ContextSourceParser implements BeanDefinitionParser { } } - private void populatePoolValidationProperties(BeanDefinitionBuilder builder, Element element, - boolean testOnBorrow, boolean testOnReturn, boolean testWhileIdle) { + private void populatePoolValidationProperties(BeanDefinitionBuilder builder, Element element, boolean testOnBorrow, + boolean testOnReturn, boolean testWhileIdle) { builder.addPropertyValue("testOnBorrow", testOnBorrow); builder.addPropertyValue("testOnReturn", testOnReturn); builder.addPropertyValue("testWhileIdle", testWhileIdle); - BeanDefinitionBuilder validatorBuilder = BeanDefinitionBuilder.rootBeanDefinition(DefaultDirContextValidator.class); + BeanDefinitionBuilder validatorBuilder = BeanDefinitionBuilder + .rootBeanDefinition(DefaultDirContextValidator.class); validatorBuilder.addPropertyValue("base", getString(element, ATT_VALIDATION_QUERY_BASE, "")); validatorBuilder.addPropertyValue("filter", getString(element, ATT_VALIDATION_QUERY_FILTER, DefaultDirContextValidator.DEFAULT_FILTER)); String searchControlsRef = element.getAttribute(ATT_VALIDATION_QUERY_SEARCH_CONTROLS_REF); - if(StringUtils.hasText(searchControlsRef)) { + if (StringUtils.hasText(searchControlsRef)) { validatorBuilder.addPropertyReference("searchControls", searchControlsRef); } builder.addPropertyValue("dirContextValidator", validatorBuilder.getBeanDefinition()); - builder.addPropertyValue("timeBetweenEvictionRunsMillis", getString(element, ATT_EVICTION_RUN_MILLIS, String.valueOf(DEFAULT_EVICTION_RUN_MILLIS))); - builder.addPropertyValue("numTestsPerEvictionRun", getInt(element, ATT_TESTS_PER_EVICTION_RUN, DEFAULT_TESTS_PER_EVICTION_RUN)); - builder.addPropertyValue("minEvictableIdleTimeMillis", getString(element, ATT_EVICTABLE_TIME_MILLIS, String.valueOf(DEFAULT_EVICTABLE_MILLIS))); + builder.addPropertyValue("timeBetweenEvictionRunsMillis", + getString(element, ATT_EVICTION_RUN_MILLIS, String.valueOf(DEFAULT_EVICTION_RUN_MILLIS))); + builder.addPropertyValue("numTestsPerEvictionRun", + getInt(element, ATT_TESTS_PER_EVICTION_RUN, DEFAULT_TESTS_PER_EVICTION_RUN)); + builder.addPropertyValue("minEvictableIdleTimeMillis", + getString(element, ATT_EVICTABLE_TIME_MILLIS, String.valueOf(DEFAULT_EVICTABLE_MILLIS))); - String nonTransientExceptions = getString(element, ATT_NON_TRANSIENT_EXCEPTIONS, CommunicationException.class.getName()); + String nonTransientExceptions = getString(element, ATT_NON_TRANSIENT_EXCEPTIONS, + CommunicationException.class.getName()); String[] strings = StringUtils.commaDelimitedListToStringArray(nonTransientExceptions); Set> nonTransientExceptionClasses = new HashSet>(); for (String className : strings) { try { nonTransientExceptionClasses.add(ClassUtils.getDefaultClassLoader().loadClass(className)); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { throw new IllegalArgumentException(String.format("%s is not a valid class name", className), e); } } @@ -271,28 +341,28 @@ public class ContextSourceParser implements BeanDefinitionParser { builder.addPropertyValue("nonTransientExceptions", nonTransientExceptionClasses); } - private void populatePoolValidationProperties(BeanDefinitionBuilder builder, Element element) { - BeanDefinitionBuilder validatorBuilder = BeanDefinitionBuilder.rootBeanDefinition( - org.springframework.ldap.pool2.validation.DefaultDirContextValidator.class); + BeanDefinitionBuilder validatorBuilder = BeanDefinitionBuilder + .rootBeanDefinition(org.springframework.ldap.pool2.validation.DefaultDirContextValidator.class); validatorBuilder.addPropertyValue("base", getString(element, ATT_VALIDATION_QUERY_BASE, "")); - validatorBuilder.addPropertyValue("filter", - getString(element, ATT_VALIDATION_QUERY_FILTER, - org.springframework.ldap.pool2.validation.DefaultDirContextValidator.DEFAULT_FILTER)); + validatorBuilder.addPropertyValue("filter", getString(element, ATT_VALIDATION_QUERY_FILTER, + org.springframework.ldap.pool2.validation.DefaultDirContextValidator.DEFAULT_FILTER)); String searchControlsRef = element.getAttribute(ATT_VALIDATION_QUERY_SEARCH_CONTROLS_REF); - if(StringUtils.hasText(searchControlsRef)) { + if (StringUtils.hasText(searchControlsRef)) { validatorBuilder.addPropertyReference("searchControls", searchControlsRef); } builder.addPropertyValue("dirContextValidator", validatorBuilder.getBeanDefinition()); - String nonTransientExceptions = getString(element, ATT_NON_TRANSIENT_EXCEPTIONS, CommunicationException.class.getName()); + String nonTransientExceptions = getString(element, ATT_NON_TRANSIENT_EXCEPTIONS, + CommunicationException.class.getName()); String[] strings = StringUtils.commaDelimitedListToStringArray(nonTransientExceptions); Set> nonTransientExceptionClasses = new HashSet>(); for (String className : strings) { try { nonTransientExceptionClasses.add(ClassUtils.getDefaultClassLoader().loadClass(className)); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { throw new IllegalArgumentException(String.format("%s is not a valid class name", className), e); } } @@ -301,36 +371,50 @@ public class ContextSourceParser implements BeanDefinitionParser { } private void populatePoolConfigProperties(BeanDefinitionBuilder builder, Element element) { - BeanDefinitionBuilder configBuilder = BeanDefinitionBuilder - .rootBeanDefinition(PoolConfig.class); + BeanDefinitionBuilder configBuilder = BeanDefinitionBuilder.rootBeanDefinition(PoolConfig.class); - configBuilder.addPropertyValue("maxTotal", getString(element, ATT_MAX_TOTAL, String.valueOf(DEFAULT_MAX_TOTAL))); - configBuilder.addPropertyValue("maxTotalPerKey", getString(element, ATT_MAX_TOTAL_PER_KEY, String.valueOf(DEFAULT_MAX_TOTAL_PER_KEY))); - configBuilder.addPropertyValue("maxIdlePerKey", getString(element, ATT_MAX_IDLE_PER_KEY, String.valueOf(DEFAULT_MAX_IDLE_PER_KEY))); - configBuilder.addPropertyValue("minIdlePerKey", getString(element, ATT_MIN_IDLE_PER_KEY, String.valueOf(DEFAULT_MIN_IDLE_PER_KEY))); - configBuilder.addPropertyValue("evictionPolicyClassName", getString(element, ATT_EVICTION_POLICY_CLASS, DEFAULT_EVICTION_POLICY_CLASS_NAME)); + configBuilder.addPropertyValue("maxTotal", + getString(element, ATT_MAX_TOTAL, String.valueOf(DEFAULT_MAX_TOTAL))); + configBuilder.addPropertyValue("maxTotalPerKey", + getString(element, ATT_MAX_TOTAL_PER_KEY, String.valueOf(DEFAULT_MAX_TOTAL_PER_KEY))); + configBuilder.addPropertyValue("maxIdlePerKey", + getString(element, ATT_MAX_IDLE_PER_KEY, String.valueOf(DEFAULT_MAX_IDLE_PER_KEY))); + configBuilder.addPropertyValue("minIdlePerKey", + getString(element, ATT_MIN_IDLE_PER_KEY, String.valueOf(DEFAULT_MIN_IDLE_PER_KEY))); + configBuilder.addPropertyValue("evictionPolicyClassName", + getString(element, ATT_EVICTION_POLICY_CLASS, DEFAULT_EVICTION_POLICY_CLASS_NAME)); configBuilder.addPropertyValue("fairness", getBoolean(element, ATT_FAIRNESS, DEFAULT_FAIRNESS)); configBuilder.addPropertyValue("jmxEnabled", getBoolean(element, ATT_JMX_ENABLE, DEFAULT_JMX_ENABLE)); configBuilder.addPropertyValue("jmxNameBase", getString(element, ATT_JMX_NAME_BASE, DEFAULT_JMX_NAME_BASE)); - configBuilder.addPropertyValue("jmxNamePrefix", getString(element, ATT_JMX_NAME_PREFIX, DEFAULT_JMX_NAME_PREFIX)); + configBuilder.addPropertyValue("jmxNamePrefix", + getString(element, ATT_JMX_NAME_PREFIX, DEFAULT_JMX_NAME_PREFIX)); configBuilder.addPropertyValue("lifo", getBoolean(element, ATT_LIFO, DEFAULT_LIFO)); - configBuilder.addPropertyValue("maxWaitMillis", getString(element, ATT_MAX_WAIT, String.valueOf(DEFAULT_MAX_WAIT_MILLIS))); - configBuilder.addPropertyValue("blockWhenExhausted", Boolean.valueOf(getString(element, ATT_BLOCK_WHEN_EXHAUSTED, String.valueOf(DEFAULT_BLOCK_WHEN_EXHAUSTED)))); + configBuilder.addPropertyValue("maxWaitMillis", + getString(element, ATT_MAX_WAIT, String.valueOf(DEFAULT_MAX_WAIT_MILLIS))); + configBuilder.addPropertyValue("blockWhenExhausted", Boolean + .valueOf(getString(element, ATT_BLOCK_WHEN_EXHAUSTED, String.valueOf(DEFAULT_BLOCK_WHEN_EXHAUSTED)))); configBuilder.addPropertyValue("testOnBorrow", getBoolean(element, ATT_TEST_ON_BORROW, false)); configBuilder.addPropertyValue("testOnCreate", getBoolean(element, ATT_TEST_ON_CREATE, false)); configBuilder.addPropertyValue("testOnReturn", getBoolean(element, ATT_TEST_ON_RETURN, false)); configBuilder.addPropertyValue("testWhileIdle", getBoolean(element, ATT_TEST_WHILE_IDLE, false)); - configBuilder.addPropertyValue("timeBetweenEvictionRunsMillis", getString(element, ATT_EVICTION_RUN_MILLIS, String.valueOf(DEFAULT_EVICTION_RUN_MILLIS))); - configBuilder.addPropertyValue("numTestsPerEvictionRun", getString(element, ATT_TESTS_PER_EVICTION_RUN, String.valueOf(DEFAULT_TESTS_PER_EVICTION_RUN))); - configBuilder.addPropertyValue("minEvictableIdleTimeMillis", getString(element, ATT_EVICTABLE_TIME_MILLIS, String.valueOf(DEFAULT_EVICTABLE_MILLIS))); - configBuilder.addPropertyValue("softMinEvictableIdleTimeMillis", getString(element, ATT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS, String.valueOf(DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS))); + configBuilder.addPropertyValue("timeBetweenEvictionRunsMillis", + getString(element, ATT_EVICTION_RUN_MILLIS, String.valueOf(DEFAULT_EVICTION_RUN_MILLIS))); + configBuilder.addPropertyValue("numTestsPerEvictionRun", + getString(element, ATT_TESTS_PER_EVICTION_RUN, String.valueOf(DEFAULT_TESTS_PER_EVICTION_RUN))); + configBuilder.addPropertyValue("minEvictableIdleTimeMillis", + getString(element, ATT_EVICTABLE_TIME_MILLIS, String.valueOf(DEFAULT_EVICTABLE_MILLIS))); + configBuilder.addPropertyValue("softMinEvictableIdleTimeMillis", getString(element, + ATT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS, String.valueOf(DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS))); builder.addConstructorArgValue(configBuilder.getBeanDefinition()); } static class UrlsFactory { + public static String[] urls(String value) { return StringUtils.commaDelimitedListToStringArray(value); } + } + } diff --git a/core/src/main/java/org/springframework/ldap/config/DefaultRenamingStrategyParser.java b/core/src/main/java/org/springframework/ldap/config/DefaultRenamingStrategyParser.java index a0e643ab..714ac943 100644 --- a/core/src/main/java/org/springframework/ldap/config/DefaultRenamingStrategyParser.java +++ b/core/src/main/java/org/springframework/ldap/config/DefaultRenamingStrategyParser.java @@ -30,20 +30,22 @@ import static org.springframework.ldap.config.ParserUtils.getString; * @author Mattias Hellborg Arthursson */ public class DefaultRenamingStrategyParser implements BeanDefinitionParser { + private static final String ATT_TEMP_SUFFIX = "temp-suffix"; @Override public BeanDefinition parse(Element element, ParserContext parserContext) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DefaultTempEntryRenamingStrategy.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder + .rootBeanDefinition(DefaultTempEntryRenamingStrategy.class); builder.addPropertyValue("tempSuffix", - getString(element, ATT_TEMP_SUFFIX, - DefaultTempEntryRenamingStrategy.DEFAULT_TEMP_SUFFIX)); + getString(element, ATT_TEMP_SUFFIX, DefaultTempEntryRenamingStrategy.DEFAULT_TEMP_SUFFIX)); AbstractBeanDefinition beanDefinition = builder.getBeanDefinition(); - parserContext.getContainingBeanDefinition().getPropertyValues() - .addPropertyValue("renamingStrategy", beanDefinition); + parserContext.getContainingBeanDefinition().getPropertyValues().addPropertyValue("renamingStrategy", + beanDefinition); return beanDefinition; } + } diff --git a/core/src/main/java/org/springframework/ldap/config/Elements.java b/core/src/main/java/org/springframework/ldap/config/Elements.java index c74de58b..652169f3 100644 --- a/core/src/main/java/org/springframework/ldap/config/Elements.java +++ b/core/src/main/java/org/springframework/ldap/config/Elements.java @@ -21,12 +21,21 @@ package org.springframework.ldap.config; * @author Anindya Chatterjee */ public abstract class Elements { + public static final String CONTEXT_SOURCE = "context-source"; + public static final String POOLING = "pooling"; + public static final String POOLING2 = "pooling2"; + public static final String LDAP_TEMPLATE = "ldap-template"; + public static final String TRANSACTION_MANAGER = "transaction-manager"; + public static final String REPOSITORIES = "repositories"; + public static final String DEFAULT_RENAMING_STRATEGY = "default-renaming-strategy"; + public static final String DIFFERENT_SUBTREE_RENAMING_STRATEGY = "different-subtree-renaming-strategy"; + } diff --git a/core/src/main/java/org/springframework/ldap/config/LdapNamespaceHandler.java b/core/src/main/java/org/springframework/ldap/config/LdapNamespaceHandler.java index 34bffa40..d95792cb 100644 --- a/core/src/main/java/org/springframework/ldap/config/LdapNamespaceHandler.java +++ b/core/src/main/java/org/springframework/ldap/config/LdapNamespaceHandler.java @@ -23,10 +23,12 @@ import org.springframework.beans.factory.xml.NamespaceHandlerSupport; * @author Rob Winch */ public class LdapNamespaceHandler extends NamespaceHandlerSupport { + @Override public void init() { registerBeanDefinitionParser(Elements.CONTEXT_SOURCE, new ContextSourceParser()); registerBeanDefinitionParser(Elements.LDAP_TEMPLATE, new LdapTemplateParser()); registerBeanDefinitionParser(Elements.TRANSACTION_MANAGER, new TransactionManagerParser()); } + } diff --git a/core/src/main/java/org/springframework/ldap/config/LdapTemplateParser.java b/core/src/main/java/org/springframework/ldap/config/LdapTemplateParser.java index 6e50fd1f..e411c4e7 100644 --- a/core/src/main/java/org/springframework/ldap/config/LdapTemplateParser.java +++ b/core/src/main/java/org/springframework/ldap/config/LdapTemplateParser.java @@ -35,16 +35,25 @@ import static org.springframework.ldap.config.ParserUtils.getString; * @author Mattias Hellborg Arthursson */ public class LdapTemplateParser implements BeanDefinitionParser { + private static final String ATT_COUNT_LIMIT = "count-limit"; + private static final String ATT_TIME_LIMIT = "time-limit"; + private static final String ATT_SEARCH_SCOPE = "search-scope"; + private static final String ATT_IGNORE_PARTIAL_RESULT = "ignore-partial-result"; + private static final String ATT_IGNORE_NAME_NOT_FOUND = "ignore-name-not-found"; + private static final String ATT_ODM_REF = "odm-ref"; + private static final String ATT_CONTEXT_SOURCE_REF = "context-source-ref"; private static final String DEFAULT_ID = "ldapTemplate"; + private static final int DEFAULT_COUNT_LIMIT = 0; + private static final int DEFAULT_TIME_LIMIT = 0; @Override @@ -62,7 +71,7 @@ public class LdapTemplateParser implements BeanDefinitionParser { builder.addPropertyValue("ignoreNameNotFoundException", getBoolean(element, ATT_IGNORE_NAME_NOT_FOUND, false)); String odmRef = element.getAttribute(ATT_ODM_REF); - if(StringUtils.hasText(odmRef)) { + if (StringUtils.hasText(odmRef)) { builder.addPropertyReference("objectDirectoryMapper", odmRef); } @@ -73,4 +82,5 @@ public class LdapTemplateParser implements BeanDefinitionParser { return beanDefinition; } + } diff --git a/core/src/main/java/org/springframework/ldap/config/ParserUtils.java b/core/src/main/java/org/springframework/ldap/config/ParserUtils.java index 82322bec..e7441bbd 100644 --- a/core/src/main/java/org/springframework/ldap/config/ParserUtils.java +++ b/core/src/main/java/org/springframework/ldap/config/ParserUtils.java @@ -23,6 +23,7 @@ import org.w3c.dom.Element; * @author Mattias Hellborg Arthursson */ final class ParserUtils { + static final String NAMESPACE = "http://www.springframework.org/schema/ldap"; /** @@ -58,4 +59,5 @@ final class ParserUtils { return defaultValue; } + } diff --git a/core/src/main/java/org/springframework/ldap/config/TransactionManagerParser.java b/core/src/main/java/org/springframework/ldap/config/TransactionManagerParser.java index c46437da..193e6199 100644 --- a/core/src/main/java/org/springframework/ldap/config/TransactionManagerParser.java +++ b/core/src/main/java/org/springframework/ldap/config/TransactionManagerParser.java @@ -38,11 +38,15 @@ import static org.springframework.ldap.config.ParserUtils.getString; * @author Mattias Hellborg Arthursson */ public class TransactionManagerParser implements BeanDefinitionParser { + private static final String ATT_CONTEXT_SOURCE_REF = "context-source-ref"; + private static final String ATT_DATA_SOURCE_REF = "data-source-ref"; + private static final String ATT_SESSION_FACTORY_REF = "session-factory-ref"; private static final String ATT_TEMP_SUFFIX = "temp-suffix"; + private static final String ATT_SUBTREE_NODE = "subtree-node"; private static final String DEFAULT_ID = "transactionManager"; @@ -54,20 +58,21 @@ public class TransactionManagerParser implements BeanDefinitionParser { String dataSourceRef = element.getAttribute(ATT_DATA_SOURCE_REF); String sessionFactoryRef = element.getAttribute(ATT_SESSION_FACTORY_REF); - if(StringUtils.hasText(dataSourceRef) && StringUtils.hasText(sessionFactoryRef)) { - throw new IllegalArgumentException( - String.format("Only one of %s and %s can be specified", - ATT_DATA_SOURCE_REF, ATT_SESSION_FACTORY_REF)); + if (StringUtils.hasText(dataSourceRef) && StringUtils.hasText(sessionFactoryRef)) { + throw new IllegalArgumentException(String.format("Only one of %s and %s can be specified", + ATT_DATA_SOURCE_REF, ATT_SESSION_FACTORY_REF)); } BeanDefinitionBuilder builder; - if(StringUtils.hasText(dataSourceRef)) { + if (StringUtils.hasText(dataSourceRef)) { builder = BeanDefinitionBuilder.rootBeanDefinition(ContextSourceAndDataSourceTransactionManager.class); builder.addPropertyReference("dataSource", dataSourceRef); - } else if(StringUtils.hasText(sessionFactoryRef)) { + } + else if (StringUtils.hasText(sessionFactoryRef)) { builder = BeanDefinitionBuilder.rootBeanDefinition(ContextSourceAndHibernateTransactionManager.class); builder.addPropertyReference("sessionFactory", sessionFactoryRef); - } else { + } + else { // Standard transaction manager builder = BeanDefinitionBuilder.rootBeanDefinition(ContextSourceTransactionManager.class); } @@ -75,13 +80,14 @@ public class TransactionManagerParser implements BeanDefinitionParser { builder.addPropertyReference("contextSource", contextSourceRef); Element defaultStrategyChild = DomUtils.getChildElementByTagName(element, Elements.DEFAULT_RENAMING_STRATEGY); - Element differentSubtreeChild = DomUtils.getChildElementByTagName(element, Elements.DIFFERENT_SUBTREE_RENAMING_STRATEGY); + Element differentSubtreeChild = DomUtils.getChildElementByTagName(element, + Elements.DIFFERENT_SUBTREE_RENAMING_STRATEGY); - if(defaultStrategyChild != null) { + if (defaultStrategyChild != null) { builder.addPropertyValue("renamingStrategy", parseDefaultRenamingStrategy(defaultStrategyChild)); } - if(differentSubtreeChild != null) { + if (differentSubtreeChild != null) { builder.addPropertyValue("renamingStrategy", parseDifferentSubtreeRenamingStrategy(differentSubtreeChild)); } @@ -94,7 +100,8 @@ public class TransactionManagerParser implements BeanDefinitionParser { } private BeanDefinition parseDifferentSubtreeRenamingStrategy(Element element) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DifferentSubtreeTempEntryRenamingStrategy.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder + .rootBeanDefinition(DifferentSubtreeTempEntryRenamingStrategy.class); String subtreeNode = element.getAttribute(ATT_SUBTREE_NODE); Assert.hasText(subtreeNode, ATT_SUBTREE_NODE + " must be specified"); @@ -105,11 +112,11 @@ public class TransactionManagerParser implements BeanDefinitionParser { } public BeanDefinition parseDefaultRenamingStrategy(Element element) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(DefaultTempEntryRenamingStrategy.class); + BeanDefinitionBuilder builder = BeanDefinitionBuilder + .rootBeanDefinition(DefaultTempEntryRenamingStrategy.class); builder.addPropertyValue("tempSuffix", - getString(element, ATT_TEMP_SUFFIX, - DefaultTempEntryRenamingStrategy.DEFAULT_TEMP_SUFFIX)); + getString(element, ATT_TEMP_SUFFIX, DefaultTempEntryRenamingStrategy.DEFAULT_TEMP_SUFFIX)); return builder.getBeanDefinition(); } diff --git a/core/src/main/java/org/springframework/ldap/control/AbstractFallbackRequestAndResponseControlDirContextProcessor.java b/core/src/main/java/org/springframework/ldap/control/AbstractFallbackRequestAndResponseControlDirContextProcessor.java index a4236e37..6d2bc1ac 100644 --- a/core/src/main/java/org/springframework/ldap/control/AbstractFallbackRequestAndResponseControlDirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/control/AbstractFallbackRequestAndResponseControlDirContextProcessor.java @@ -29,47 +29,47 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** - * Convenient base class useful when implementing a standard DirContextProcessor - * which has a request control and a response control. It handles the loading of - * the control classes, using fallback implementations specified by the subclass - * if necessary. It handles the request control constructor invocation; it only - * needs the constructor arguments to be provided. It also handles most of the - * work in the post processing of the response control, only delegating to a - * template method for the actual value retrieval. In short, it makes it easy to - * implement a custom DirContextProcessor.

- * + * Convenient base class useful when implementing a standard DirContextProcessor which has + * a request control and a response control. It handles the loading of the control + * classes, using fallback implementations specified by the subclass if necessary. It + * handles the request control constructor invocation; it only needs the constructor + * arguments to be provided. It also handles most of the work in the post processing of + * the response control, only delegating to a template method for the actual value + * retrieval. In short, it makes it easy to implement a custom DirContextProcessor. + *

+ * *

  * public class SortControlDirContextProcessor extends AbstractFallbackRequestAndResponseControlDirContextProcessor {
  * 	String sortKey;
- * 
+ *
  * 	private boolean sorted = false;
- * 
+ *
  * 	private int resultCode = -1;
- * 
+ *
  * 	public SortControlDirContextProcessor(String sortKey) {
  * 		this.sortKey = sortKey;
- * 
+ *
  * 		defaultRequestControl = "javax.naming.ldap.SortControl";
  * 		defaultResponseControl = "com.sun.jndi.ldap.ctl.SortControl";
  * 		fallbackRequestControl = "javax.naming.ldap.SortResponseControl";
  * 		fallbackResponseControl = "com.sun.jndi.ldap.ctl.SortResponseControl";
- * 
+ *
  * 		loadControlClasses();
  * 	}
- * 
+ *
  * 	public boolean isSorted() {
  * 		return sorted;
  * 	}
- * 
+ *
  * 	public int getResultCode() {
  * 		return resultCode;
  * 	}
- * 
+ *
  * 	public Control createRequestControl() {
  * 		return super.createRequestControl(new Class[] { String[].class, boolean.class }, new Object[] {
  *				new String[] { sortKey }, Boolean.valueOf(critical) });
  * 	}
- * 
+ *
  * 	protected void handleResponse(Object control) {
  * 		Boolean result = (Boolean) invokeMethod("isSorted", responseControlClass, control);
  * 		this.sorted = result.booleanValue();
@@ -78,11 +78,11 @@ import java.lang.reflect.Method;
  * 	}
  * }
  * 
- * + * * @author Ulrik Sandberg */ -public abstract class AbstractFallbackRequestAndResponseControlDirContextProcessor extends - AbstractRequestControlDirContextProcessor { +public abstract class AbstractFallbackRequestAndResponseControlDirContextProcessor + extends AbstractRequestControlDirContextProcessor { private static final boolean CRITICAL_CONTROL = true; @@ -124,9 +124,7 @@ public abstract class AbstractFallbackRequestAndResponseControlDirContextProcess } /** - * Set the class of the expected ResponseControl for the sorted result - * response. - * + * Set the class of the expected ResponseControl for the sorted result response. * @param responseControlClass Class of the expected response control. */ public void setResponseControlClass(Class responseControlClass) { @@ -174,8 +172,7 @@ public abstract class AbstractFallbackRequestAndResponseControlDirContextProcess } /* - * @see - * org.springframework.ldap.core.DirContextProcessor#postProcess(javax.naming + * @see org.springframework.ldap.core.DirContextProcessor#postProcess(javax.naming * .directory.DirContext) */ public void postProcess(DirContext ctx) throws NamingException { @@ -200,7 +197,6 @@ public abstract class AbstractFallbackRequestAndResponseControlDirContextProcess /** * Set whether this control should be indicated as critical. - * * @param critical whether the control is critical. * @since 2.0 */ @@ -209,4 +205,5 @@ public abstract class AbstractFallbackRequestAndResponseControlDirContextProcess } protected abstract void handleResponse(Object control); + } diff --git a/core/src/main/java/org/springframework/ldap/control/AbstractRequestControlDirContextProcessor.java b/core/src/main/java/org/springframework/ldap/control/AbstractRequestControlDirContextProcessor.java index d5bf7d5f..29abe7f8 100644 --- a/core/src/main/java/org/springframework/ldap/control/AbstractRequestControlDirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/control/AbstractRequestControlDirContextProcessor.java @@ -26,25 +26,24 @@ import javax.naming.ldap.Control; import javax.naming.ldap.LdapContext; /** - * Abstract superclass with responsibility to apply a single RequestControl on - * an LdapContext, preserving any existing controls. Subclasses should implement + * Abstract superclass with responsibility to apply a single RequestControl on an + * LdapContext, preserving any existing controls. Subclasses should implement * {@link DirContextProcessor#postProcess(DirContext)} and template method * {@link #createRequestControl()}. - * + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ public abstract class AbstractRequestControlDirContextProcessor implements DirContextProcessor { + protected Logger log = LoggerFactory.getLogger(AbstractRequestControlDirContextProcessor.class); private boolean replaceSameControlEnabled = true; /** - * If there already exists a request control of the same class as the one - * created by {@link #createRequestControl()} in the context, the new - * control can either replace the existing one (default behavior) or be - * added. - * + * If there already exists a request control of the same class as the one created by + * {@link #createRequestControl()} in the context, the new control can either replace + * the existing one (default behavior) or be added. * @return true if an already existing control will be replaced */ public boolean isReplaceSameControlEnabled() { @@ -52,13 +51,11 @@ public abstract class AbstractRequestControlDirContextProcessor implements DirCo } /** - * If there already exists a request control of the same class as the one - * created by {@link #createRequestControl()} in the context, the new - * control can either replace the existing one (default behavior) or be - * added. - * - * @param replaceSameControlEnabled true if an already - * existing control should be replaced + * If there already exists a request control of the same class as the one created by + * {@link #createRequestControl()} in the context, the new control can either replace + * the existing one (default behavior) or be added. + * @param replaceSameControlEnabled true if an already existing control + * should be replaced */ public void setReplaceSameControlEnabled(boolean replaceSameControlEnabled) { this.replaceSameControlEnabled = replaceSameControlEnabled; @@ -66,19 +63,17 @@ public abstract class AbstractRequestControlDirContextProcessor implements DirCo /** * Get the existing RequestControls from the LdapContext, call - * {@link #createRequestControl()} to get a new instance, build a new array - * of Controls and set it on the LdapContext. + * {@link #createRequestControl()} to get a new instance, build a new array of + * Controls and set it on the LdapContext. *

- * The {@link Control} feature is specific for LDAP v3 and thus applies only - * to {@link LdapContext}. However, the generic DirContextProcessor - * mechanism used for calling preProcess and - * postProcess uses DirContext, since it also works for LDAP - * v2. This is the reason that DirContext has to be cast to a LdapContext. - * + * The {@link Control} feature is specific for LDAP v3 and thus applies only to + * {@link LdapContext}. However, the generic DirContextProcessor mechanism used for + * calling preProcess and postProcess uses DirContext, since + * it also works for LDAP v2. This is the reason that DirContext has to be cast to a + * LdapContext. * @param ctx an LdapContext instance. * @throws NamingException - * @throws IllegalArgumentException if the supplied DirContext is not an - * LdapContext. + * @throws IllegalArgumentException if the supplied DirContext is not an LdapContext. */ public void preProcess(DirContext ctx) throws NamingException { LdapContext ldapContext; @@ -86,8 +81,8 @@ public abstract class AbstractRequestControlDirContextProcessor implements DirCo ldapContext = (LdapContext) ctx; } else { - throw new IllegalArgumentException("Request Control operations require LDAPv3 - " - + "Context must be of type LdapContext"); + throw new IllegalArgumentException( + "Request Control operations require LDAPv3 - " + "Context must be of type LdapContext"); } Control[] requestControls = ldapContext.getRequestControls(); @@ -115,8 +110,8 @@ public abstract class AbstractRequestControlDirContextProcessor implements DirCo /** * Create an instance of the appropriate RequestControl. - * * @return the new instance. */ public abstract Control createRequestControl(); + } diff --git a/core/src/main/java/org/springframework/ldap/control/CreateControlFailedException.java b/core/src/main/java/org/springframework/ldap/control/CreateControlFailedException.java index 8f85492a..26f921eb 100644 --- a/core/src/main/java/org/springframework/ldap/control/CreateControlFailedException.java +++ b/core/src/main/java/org/springframework/ldap/control/CreateControlFailedException.java @@ -19,9 +19,9 @@ package org.springframework.ldap.control; import org.springframework.ldap.NamingException; /** - * Thrown by an AbstractRequestControlDirContextProcessor when it cannot create - * a request control. - * + * Thrown by an AbstractRequestControlDirContextProcessor when it cannot create a request + * control. + * * @author Ulrik Sandberg * @since 1.2 */ @@ -29,9 +29,7 @@ public class CreateControlFailedException extends NamingException { /** * Create a new CreateControlFailedException. - * - * @param msg - * the detail message + * @param msg the detail message */ public CreateControlFailedException(String msg) { super(msg); @@ -39,13 +37,11 @@ public class CreateControlFailedException extends NamingException { /** * Create a new CreateControlFailedException. - * - * @param msg - * the detail message - * @param cause - * the root cause (if any) + * @param msg the detail message + * @param cause the root cause (if any) */ public CreateControlFailedException(String msg, Throwable cause) { super(msg, cause); } + } diff --git a/core/src/main/java/org/springframework/ldap/control/PagedResult.java b/core/src/main/java/org/springframework/ldap/control/PagedResult.java index 6b407c41..695d53de 100644 --- a/core/src/main/java/org/springframework/ldap/control/PagedResult.java +++ b/core/src/main/java/org/springframework/ldap/control/PagedResult.java @@ -18,9 +18,9 @@ package org.springframework.ldap.control; import java.util.List; /** - * Bean to encapsulate a result List and a {@link PagedResultsCookie} to use for - * returning the results when using {@link PagedResultsRequestControl}. - * + * Bean to encapsulate a result List and a {@link PagedResultsCookie} to use for returning + * the results when using {@link PagedResultsRequestControl}. + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg * @deprecated @@ -32,13 +32,9 @@ public class PagedResult { private PagedResultsCookie cookie; /** - * Constructs a PagedResults using the supplied List and - * {@link PagedResultsCookie}. - * - * @param resultList - * the result list. - * @param cookie - * the cookie. + * Constructs a PagedResults using the supplied List and {@link PagedResultsCookie}. + * @param resultList the result list. + * @param cookie the cookie. */ public PagedResult(List resultList, PagedResultsCookie cookie) { this.resultList = resultList; @@ -47,7 +43,6 @@ public class PagedResult { /** * Get the cookie. - * * @return the cookie. */ public PagedResultsCookie getCookie() { @@ -56,7 +51,6 @@ public class PagedResult { /** * Get the result list. - * * @return the result list. */ public List getResultList() { @@ -65,13 +59,17 @@ public class PagedResult { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; PagedResult that = (PagedResult) o; - if (cookie != null ? !cookie.equals(that.cookie) : that.cookie != null) return false; - if (resultList != null ? !resultList.equals(that.resultList) : that.resultList != null) return false; + if (cookie != null ? !cookie.equals(that.cookie) : that.cookie != null) + return false; + if (resultList != null ? !resultList.equals(that.resultList) : that.resultList != null) + return false; return true; } @@ -82,4 +80,5 @@ public class PagedResult { result = 31 * result + (cookie != null ? cookie.hashCode() : 0); return result; } + } diff --git a/core/src/main/java/org/springframework/ldap/control/PagedResultsCookie.java b/core/src/main/java/org/springframework/ldap/control/PagedResultsCookie.java index 6fff0d7b..71161985 100644 --- a/core/src/main/java/org/springframework/ldap/control/PagedResultsCookie.java +++ b/core/src/main/java/org/springframework/ldap/control/PagedResultsCookie.java @@ -19,9 +19,8 @@ import javax.naming.ldap.PagedResultsControl; import java.util.Arrays; /** - * Wrapper class for the cookie returned when using the - * {@link PagedResultsControl}. - * + * Wrapper class for the cookie returned when using the {@link PagedResultsControl}. + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ @@ -31,40 +30,42 @@ public class PagedResultsCookie { /** * Constructor. - * - * @param cookie - * the cookie returned by a PagedResultsResponseControl. + * @param cookie the cookie returned by a PagedResultsResponseControl. */ public PagedResultsCookie(byte[] cookie) { if (cookie != null) { this.cookie = Arrays.copyOf(cookie, cookie.length); - } else { + } + else { this.cookie = null; } } /** * Get the cookie. - * - * @return the cookie. This value may be null, indicating that there are no more requests, - * or that the control wasn't supported by the server. + * @return the cookie. This value may be null, indicating that there are + * no more requests, or that the control wasn't supported by the server. */ public byte[] getCookie() { if (cookie != null) { return Arrays.copyOf(cookie, cookie.length); - } else { + } + else { return null; } } @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; PagedResultsCookie that = (PagedResultsCookie) o; - if (!Arrays.equals(cookie, that.cookie)) return false; + if (!Arrays.equals(cookie, that.cookie)) + return false; return true; } @@ -73,4 +74,5 @@ public class PagedResultsCookie { public int hashCode() { return cookie != null ? Arrays.hashCode(cookie) : 0; } + } diff --git a/core/src/main/java/org/springframework/ldap/control/PagedResultsDirContextProcessor.java b/core/src/main/java/org/springframework/ldap/control/PagedResultsDirContextProcessor.java index b3a6d600..0a7371e2 100644 --- a/core/src/main/java/org/springframework/ldap/control/PagedResultsDirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/control/PagedResultsDirContextProcessor.java @@ -19,15 +19,14 @@ package org.springframework.ldap.control; import javax.naming.ldap.Control; /** - * DirContextProcessor implementation for managing the paged results control. - * Note that due to the internal workings of LdapTemplate, the - * target connection is closed after each LDAP call. The PagedResults control - * require the same connection be used for each call, which means we need to - * make sure the target connection is never actually closed. There's basically - * two ways of making this happen: use the SingleContextSource - * implementation or make sure all calls happen within a single LDAP transaction - * (using ContextSourceTransactionManager). - * + * DirContextProcessor implementation for managing the paged results control. Note that + * due to the internal workings of LdapTemplate, the target connection is + * closed after each LDAP call. The PagedResults control require the same connection be + * used for each call, which means we need to make sure the target connection is never + * actually closed. There's basically two ways of making this happen: use the + * SingleContextSource implementation or make sure all calls happen within a + * single LDAP transaction (using ContextSourceTransactionManager). + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ @@ -50,10 +49,8 @@ public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndR private boolean more = true; /** - * Constructs a new instance. This constructor should be used when - * performing the first paged search operation, when no other results have - * been retrieved. - * + * Constructs a new instance. This constructor should be used when performing the + * first paged search operation, when no other results have been retrieved. * @param pageSize the page size. */ public PagedResultsDirContextProcessor(int pageSize) { @@ -61,11 +58,9 @@ public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndR } /** - * Constructs a new instance with the supplied page size and cookie. The - * cookie must be the exact same instance as received from a previous paged - * results search, or null if it is the first in an operation - * sequence. - * + * Constructs a new instance with the supplied page size and cookie. The cookie must + * be the exact same instance as received from a previous paged results search, or + * null if it is the first in an operation sequence. * @param pageSize the page size. * @param cookie the cookie, as received from a previous search. */ @@ -77,16 +72,15 @@ public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndR defaultResponseControl = DEFAULT_RESPONSE_CONTROL; fallbackRequestControl = FALLBACK_REQUEST_CONTROL; fallbackResponseControl = FALLBACK_RESPONSE_CONTROL; - + loadControlClasses(); } /** * Get the cookie. - * - * @return the cookie. The cookie will always be set after at leas one query, however the actual cookie content - * can be null, indicating that there are no more results, in which case {@link #hasMore()} will return - * false. + * @return the cookie. The cookie will always be set after at leas one query, however + * the actual cookie content can be null, indicating that there are no + * more results, in which case {@link #hasMore()} will return false. * @see #hasMore() */ public PagedResultsCookie getCookie() { @@ -95,7 +89,6 @@ public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndR /** * Get the page size. - * * @return the page size. */ public int getPageSize() { @@ -103,10 +96,9 @@ public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndR } /** - * Get the total estimated number of entries that matches the issued search. - * Note that this value is optional for the LDAP server to return, so it - * does not always contain any valid data. - * + * Get the total estimated number of entries that matches the issued search. Note that + * this value is optional for the LDAP server to return, so it does not always contain + * any valid data. * @return the estimated result size, if returned from the server. */ public int getResultSize() { @@ -114,8 +106,7 @@ public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndR } /* - * @see - * org.springframework.ldap.control.AbstractRequestControlDirContextProcessor + * @see org.springframework.ldap.control.AbstractRequestControlDirContextProcessor * #createRequestControl() */ public Control createRequestControl() { @@ -124,15 +115,15 @@ public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndR actualCookie = cookie.getCookie(); } return super.createRequestControl(new Class[] { int.class, byte[].class, boolean.class }, - new Object[] {pageSize, actualCookie, critical}); + new Object[] { pageSize, actualCookie, critical }); } /** - * Check whether there are more results to retrieved. When there are no more results to retrieve, - * this is indicated by a null cookie being returned from the server. - * When this happen, the internal status will set to false. - * - * @return true if there are more results to retrieve, false otherwise. + * Check whether there are more results to retrieved. When there are no more results + * to retrieve, this is indicated by a null cookie being returned from + * the server. When this happen, the internal status will set to false. + * @return true if there are more results to retrieve, false + * otherwise. * @since 2.0 */ public boolean hasMore() { @@ -146,10 +137,11 @@ public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndR */ protected void handleResponse(Object control) { byte[] result = (byte[]) invokeMethod("getCookie", responseControlClass, control); - if(result == null) { + if (result == null) { more = false; } this.cookie = new PagedResultsCookie(result); this.resultSize = (Integer) invokeMethod("getResultSize", responseControlClass, control); } + } diff --git a/core/src/main/java/org/springframework/ldap/control/PagedResultsRequestControl.java b/core/src/main/java/org/springframework/ldap/control/PagedResultsRequestControl.java index 11a151a3..51223f65 100644 --- a/core/src/main/java/org/springframework/ldap/control/PagedResultsRequestControl.java +++ b/core/src/main/java/org/springframework/ldap/control/PagedResultsRequestControl.java @@ -28,15 +28,14 @@ import java.lang.reflect.Constructor; import java.lang.reflect.Method; /** - * DirContextProcessor implementation for managing the paged results control. - * Note that due to the internal workings of LdapTemplate, the - * target connection is closed after each LDAP call. The PagedResults control - * require the same connection be used for each call, which means we need to - * make sure the target connection is never actually closed. There's basically - * two ways of making this happen: use the SingleContextSource - * implementation or make sure all calls happen within a single LDAP transaction - * (using ContextSourceTransactionManager). - * + * DirContextProcessor implementation for managing the paged results control. Note that + * due to the internal workings of LdapTemplate, the target connection is + * closed after each LDAP call. The PagedResults control require the same connection be + * used for each call, which means we need to make sure the target connection is never + * actually closed. There's basically two ways of making this happen: use the + * SingleContextSource implementation or make sure all calls happen within a + * single LDAP transaction (using ContextSourceTransactionManager). + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg * @deprecated Use PagedResultsDirContextProcessor instead. @@ -66,10 +65,8 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext private Class requestControlClass; /** - * Constructs a new instance. This constructor should be used when - * performing the first paged search operation, when no other results have - * been retrieved. - * + * Constructs a new instance. This constructor should be used when performing the + * first paged search operation, when no other results have been retrieved. * @param pageSize the page size. */ public PagedResultsRequestControl(int pageSize) { @@ -77,11 +74,9 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext } /** - * Constructs a new instance with the supplied page size and cookie. The - * cookie must be the exact same instance as received from a previous paged - * resullts search, or null if it is the first in an operation - * sequence. - * + * Constructs a new instance with the supplied page size and cookie. The cookie must + * be the exact same instance as received from a previous paged resullts search, or + * null if it is the first in an operation sequence. * @param pageSize the page size. * @param cookie the cookie, as received from a previous search. */ @@ -114,7 +109,6 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext /** * Get the cookie. - * * @return the cookie. */ public PagedResultsCookie getCookie() { @@ -123,7 +117,6 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext /** * Get the page size. - * * @return the page size. */ public int getPageSize() { @@ -131,10 +124,9 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext } /** - * Get the total estimated number of entries that matches the issued search. - * Note that this value is optional for the LDAP server to return, so it - * does not always contain any valid data. - * + * Get the total estimated number of entries that matches the issued search. Note that + * this value is optional for the LDAP server to return, so it does not always contain + * any valid data. * @return the estimated result size, if returned from the server. */ public int getResultSize() { @@ -142,9 +134,7 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext } /** - * Set the class of the expected ResponseControl for the paged results - * response. - * + * Set the class of the expected ResponseControl for the paged results response. * @param responseControlClass Class of the expected response control. */ public void setResponseControlClass(Class responseControlClass) { @@ -156,8 +146,7 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext } /* - * @see - * org.springframework.ldap.control.AbstractRequestControlDirContextProcessor + * @see org.springframework.ldap.control.AbstractRequestControlDirContextProcessor * #createRequestControl() */ @@ -166,16 +155,15 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext if (cookie != null) { actualCookie = cookie.getCookie(); } - Constructor constructor = ClassUtils.getConstructorIfAvailable(requestControlClass, new Class[] { int.class, - byte[].class, boolean.class }); + Constructor constructor = ClassUtils.getConstructorIfAvailable(requestControlClass, + new Class[] { int.class, byte[].class, boolean.class }); if (constructor == null) { throw new IllegalArgumentException("Failed to find an appropriate RequestControl constructor"); } Control result = null; try { - result = (Control) constructor.newInstance(pageSize, actualCookie, - critical); + result = (Control) constructor.newInstance(pageSize, actualCookie, critical); } catch (Exception e) { ReflectionUtils.handleReflectionException(e); @@ -185,8 +173,7 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext } /* - * @see - * org.springframework.ldap.core.DirContextProcessor#postProcess(javax.naming + * @see org.springframework.ldap.core.DirContextProcessor#postProcess(javax.naming * .directory.DirContext) */ @@ -220,4 +207,5 @@ public class PagedResultsRequestControl extends AbstractRequestControlDirContext Method actualMethod = ReflectionUtils.findMethod(clazz, method); return ReflectionUtils.invokeMethod(actualMethod, control); } + } diff --git a/core/src/main/java/org/springframework/ldap/control/SortControlDirContextProcessor.java b/core/src/main/java/org/springframework/ldap/control/SortControlDirContextProcessor.java index bff3d209..375af4bf 100644 --- a/core/src/main/java/org/springframework/ldap/control/SortControlDirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/control/SortControlDirContextProcessor.java @@ -19,10 +19,9 @@ package org.springframework.ldap.control; import javax.naming.ldap.Control; /** - * DirContextProcessor implementation for managing the SortControl. Note that - * this class is stateful, so a new instance needs to be instantiated for each - * new search. - * + * DirContextProcessor implementation for managing the SortControl. Note that this class + * is stateful, so a new instance needs to be instantiated for each new search. + * * @author Ulrik Sandberg */ public class SortControlDirContextProcessor extends AbstractFallbackRequestAndResponseControlDirContextProcessor { @@ -52,7 +51,6 @@ public class SortControlDirContextProcessor extends AbstractFallbackRequestAndRe /** * Constructs a new instance using the supplied sort key. - * * @param sortKey the sort key, i.e. the attribute name to sort on. */ public SortControlDirContextProcessor(String sortKey) { @@ -71,9 +69,7 @@ public class SortControlDirContextProcessor extends AbstractFallbackRequestAndRe /** * Check whether the returned values were actually sorted by the server. - * - * @return true if the result was sorted, false - * otherwise. + * @return true if the result was sorted, false otherwise. */ public boolean isSorted() { return sorted; @@ -81,7 +77,6 @@ public class SortControlDirContextProcessor extends AbstractFallbackRequestAndRe /** * Get the result code returned by the control. - * * @return result code. */ public int getResultCode() { @@ -90,7 +85,6 @@ public class SortControlDirContextProcessor extends AbstractFallbackRequestAndRe /** * Get the sort key. - * * @return the sort key. */ public String getSortKey() { @@ -98,13 +92,12 @@ public class SortControlDirContextProcessor extends AbstractFallbackRequestAndRe } /* - * @see - * org.springframework.ldap.control.AbstractRequestControlDirContextProcessor + * @see org.springframework.ldap.control.AbstractRequestControlDirContextProcessor * #createRequestControl() */ public Control createRequestControl() { - return super.createRequestControl(new Class[] { String[].class, boolean.class }, new Object[] { - new String[] { sortKey }, critical}); + return super.createRequestControl(new Class[] { String[].class, boolean.class }, + new Object[] { new String[] { sortKey }, critical }); } /* @@ -116,4 +109,5 @@ public class SortControlDirContextProcessor extends AbstractFallbackRequestAndRe this.sorted = (Boolean) invokeMethod("isSorted", responseControlClass, control); this.resultCode = (Integer) invokeMethod("getResultCode", responseControlClass, control); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/AttributeModificationsAware.java b/core/src/main/java/org/springframework/ldap/core/AttributeModificationsAware.java index dcc02258..c167556d 100644 --- a/core/src/main/java/org/springframework/ldap/core/AttributeModificationsAware.java +++ b/core/src/main/java/org/springframework/ldap/core/AttributeModificationsAware.java @@ -19,19 +19,19 @@ package org.springframework.ldap.core; import javax.naming.directory.ModificationItem; /** - * Indicates that the implementing class is capable of keeping track of any - * attribute modifications and return them as ModificationItems. - * + * Indicates that the implementing class is capable of keeping track of any attribute + * modifications and return them as ModificationItems. + * * @author Mattias Hellborg Arthursson - * + * */ public interface AttributeModificationsAware { /** - * Creates an array of which attributes have been changed, added or removed - * since the initialization of this object. - * + * Creates an array of which attributes have been changed, added or removed since the + * initialization of this object. * @return an array of modification items. */ ModificationItem[] getModificationItems(); + } diff --git a/core/src/main/java/org/springframework/ldap/core/AttributesMapper.java b/core/src/main/java/org/springframework/ldap/core/AttributesMapper.java index 5f2b14f2..caf3161b 100644 --- a/core/src/main/java/org/springframework/ldap/core/AttributesMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/AttributesMapper.java @@ -21,35 +21,31 @@ import javax.naming.NamingException; import javax.naming.directory.Attributes; /** - * An interface used by LdapTemplate for mapping LDAP Attributes to beans. - * Implementions of this interface perform the actual work of extracting - * results, but need not worry about exception handling. NamingExceptions will - * be caught and handled correctly by the {@link LdapTemplate} class. + * An interface used by LdapTemplate for mapping LDAP Attributes to beans. Implementions + * of this interface perform the actual work of extracting results, but need not worry + * about exception handling. NamingExceptions will be caught and handled + * correctly by the {@link LdapTemplate} class. *

- * Typically used in search methods of {@link LdapTemplate}. - * AttributeMapper objects are normally stateless and thus - * reusable; they are ideal for implementing attribute-mapping logic in one - * place. + * Typically used in search methods of {@link LdapTemplate}. AttributeMapper + * objects are normally stateless and thus reusable; they are ideal for implementing + * attribute-mapping logic in one place. *

* Alternatively, consider using a {@link ContextMapper} in stead. - * + * * @see LdapTemplate#search(Name, String, AttributesMapper) * @see LdapTemplate#lookup(Name, AttributesMapper) * @see ContextMapper - * * @author Mattias Hellborg Arthursson */ public interface AttributesMapper { + /** - * Map Attributes to an object. The supplied attributes are the attributes - * from a single SearchResult. - * - * @param attributes - * attributes from a SearchResult. + * Map Attributes to an object. The supplied attributes are the attributes from a + * single SearchResult. + * @param attributes attributes from a SearchResult. * @return an object built from the attributes. - * @throws NamingException - * if any error occurs mapping the attributes + * @throws NamingException if any error occurs mapping the attributes */ - T mapFromAttributes(Attributes attributes) - throws NamingException; + T mapFromAttributes(Attributes attributes) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/AttributesMapperCallbackHandler.java b/core/src/main/java/org/springframework/ldap/core/AttributesMapperCallbackHandler.java index f06acfa1..0544edc1 100644 --- a/core/src/main/java/org/springframework/ldap/core/AttributesMapperCallbackHandler.java +++ b/core/src/main/java/org/springframework/ldap/core/AttributesMapperCallbackHandler.java @@ -23,21 +23,20 @@ import javax.naming.directory.Attributes; import javax.naming.directory.SearchResult; /** - * A CollectingNameClassPairCallbackHandler to wrap an {@link AttributesMapper}. - * That is, the found object is extracted from the {@link Attributes} of each - * {@link SearchResult}, and then passed to the specified - * {@link AttributesMapper} for translation. - * + * A CollectingNameClassPairCallbackHandler to wrap an {@link AttributesMapper}. That is, + * the found object is extracted from the {@link Attributes} of each {@link SearchResult}, + * and then passed to the specified {@link AttributesMapper} for translation. + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg * @since 1.2 */ public class AttributesMapperCallbackHandler extends CollectingNameClassPairCallbackHandler { + private AttributesMapper mapper; /** * Constructs a new instance around the specified {@link AttributesMapper}. - * * @param mapper the target mapper. */ public AttributesMapperCallbackHandler(AttributesMapper mapper) { @@ -47,7 +46,6 @@ public class AttributesMapperCallbackHandler extends CollectingNameClassPairC /** * Cast the NameClassPair to a SearchResult and pass its attributes to the * {@link AttributesMapper}. - * * @param nameClassPair a SearchResult instance. * @return the Object returned from the mapper. */ @@ -65,4 +63,5 @@ public class AttributesMapperCallbackHandler extends CollectingNameClassPairC throw LdapUtils.convertLdapException(e); } } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/core/AuthenticatedLdapEntryContextCallback.java b/core/src/main/java/org/springframework/ldap/core/AuthenticatedLdapEntryContextCallback.java index eafd5d7a..90c2481e 100644 --- a/core/src/main/java/org/springframework/ldap/core/AuthenticatedLdapEntryContextCallback.java +++ b/core/src/main/java/org/springframework/ldap/core/AuthenticatedLdapEntryContextCallback.java @@ -18,23 +18,21 @@ package org.springframework.ldap.core; import javax.naming.directory.DirContext; /** - * Callback interface to be used in the authentication methods in - * {@link LdapOperations} for performing operations on individually - * authenticated contexts. - * + * Callback interface to be used in the authentication methods in {@link LdapOperations} + * for performing operations on individually authenticated contexts. + * * @author Mattias Hellborg Arthursson * @since 1.3 */ public interface AuthenticatedLdapEntryContextCallback { + /** - * Perform some LDAP operation on the supplied authenticated - * DirContext instance. The target context will be - * automatically closed. - * - * @param ctx the DirContext instance to perform an operation - * on. - * @param ldapEntryIdentification the identification of the LDAP entry used - * to authenticate the supplied DirContext. + * Perform some LDAP operation on the supplied authenticated DirContext + * instance. The target context will be automatically closed. + * @param ctx the DirContext instance to perform an operation on. + * @param ldapEntryIdentification the identification of the LDAP entry used to + * authenticate the supplied DirContext. */ void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification); + } diff --git a/core/src/main/java/org/springframework/ldap/core/AuthenticatedLdapEntryContextMapper.java b/core/src/main/java/org/springframework/ldap/core/AuthenticatedLdapEntryContextMapper.java index ef5a6953..9951c0c2 100644 --- a/core/src/main/java/org/springframework/ldap/core/AuthenticatedLdapEntryContextMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/AuthenticatedLdapEntryContextMapper.java @@ -19,24 +19,22 @@ package org.springframework.ldap.core; import javax.naming.directory.DirContext; /** - * Callback interface to be used in the authentication methods in - * {@link LdapOperations} for performing operations on individually - * authenticated contexts. + * Callback interface to be used in the authentication methods in {@link LdapOperations} + * for performing operations on individually authenticated contexts. * * @author Mattias Hellborg Arthursson * @since 2.0 */ public interface AuthenticatedLdapEntryContextMapper { + /** - * Perform some LDAP operation on the supplied authenticated - * DirContext instance. The target context will be - * automatically closed. - * - * @param ctx the DirContext instance to perform an operation - * on. - * @param ldapEntryIdentification the identification of the LDAP entry used - * to authenticate the supplied DirContext. + * Perform some LDAP operation on the supplied authenticated DirContext + * instance. The target context will be automatically closed. + * @param ctx the DirContext instance to perform an operation on. + * @param ldapEntryIdentification the identification of the LDAP entry used to + * authenticate the supplied DirContext. * @return the result of the operation, if any. */ T mapWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification); + } diff --git a/core/src/main/java/org/springframework/ldap/core/AuthenticationErrorCallback.java b/core/src/main/java/org/springframework/ldap/core/AuthenticationErrorCallback.java index a73332f2..b8db6514 100644 --- a/core/src/main/java/org/springframework/ldap/core/AuthenticationErrorCallback.java +++ b/core/src/main/java/org/springframework/ldap/core/AuthenticationErrorCallback.java @@ -1,20 +1,20 @@ package org.springframework.ldap.core; /** - * Callback interface to be used in the authentication methods in - * {@link LdapOperations} for performing operations when there - * are authentication errors. Can be useful when the cause of the - * authentication failure needs to be retrieved. + * Callback interface to be used in the authentication methods in {@link LdapOperations} + * for performing operations when there are authentication errors. Can be useful when the + * cause of the authentication failure needs to be retrieved. * * @author Ulrik Sandberg * @since 1.3.1 */ public interface AuthenticationErrorCallback { + /** - * This method will be called with the authentication exception in - * case there is a problem with the authentication. - * + * This method will be called with the authentication exception in case there is a + * problem with the authentication. * @param e the exception that was caught in the authentication method */ void execute(Exception e); + } diff --git a/core/src/main/java/org/springframework/ldap/core/AuthenticationSource.java b/core/src/main/java/org/springframework/ldap/core/AuthenticationSource.java index b94a1083..f5e7946b 100644 --- a/core/src/main/java/org/springframework/ldap/core/AuthenticationSource.java +++ b/core/src/main/java/org/springframework/ldap/core/AuthenticationSource.java @@ -17,24 +17,24 @@ package org.springframework.ldap.core; /** - * An AuthenticationSource is responsible for providing the - * principal (user DN) and credentials to be used when creating a new context. - * + * An AuthenticationSource is responsible for providing the principal (user + * DN) and credentials to be used when creating a new context. + * * @author Mattias Hellborg Arthursson - * + * */ public interface AuthenticationSource { + /** * Get the principal to use when creating an authenticated context. - * * @return the principal (userDn). */ String getPrincipal(); /** * Get the credentials to use when creating an authenticated context. - * * @return the credentials (password). */ String getCredentials(); + } diff --git a/core/src/main/java/org/springframework/ldap/core/CollectingAuthenticationErrorCallback.java b/core/src/main/java/org/springframework/ldap/core/CollectingAuthenticationErrorCallback.java index 455e51ac..c4fbc562 100644 --- a/core/src/main/java/org/springframework/ldap/core/CollectingAuthenticationErrorCallback.java +++ b/core/src/main/java/org/springframework/ldap/core/CollectingAuthenticationErrorCallback.java @@ -16,23 +16,23 @@ package org.springframework.ldap.core; /** - * Convenience implementation of AuthenticationErrorCallback that stores the - * given exception and provides a method for retrieving it. The caller of the - * authenticate method can provide an instance of this class as an error - * callback. If the authentication fails, the caller can ask the callback - * instance for the actual authentication exception. - * + * Convenience implementation of AuthenticationErrorCallback that stores the given + * exception and provides a method for retrieving it. The caller of the authenticate + * method can provide an instance of this class as an error callback. If the + * authentication fails, the caller can ask the callback instance for the actual + * authentication exception. + * * @author Ulrik Sandberg * @since 1.3.1 */ public final class CollectingAuthenticationErrorCallback implements AuthenticationErrorCallback { + private Exception error; /* * (non-Javadoc) - * - * @see - * org.springframework.ldap.core.AuthenticationErrorCallback#execute(java + * + * @see org.springframework.ldap.core.AuthenticationErrorCallback#execute(java * .lang.Exception) */ public void execute(Exception e) { @@ -48,10 +48,11 @@ public final class CollectingAuthenticationErrorCallback implements Authenticati /** * Check whether this callback has collected an error. - * - * @return true if an error has been collected, false otherwise. + * @return true if an error has been collected, false + * otherwise. */ public boolean hasError() { return error != null; } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandler.java b/core/src/main/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandler.java index 110aa95c..b6ce8950 100644 --- a/core/src/main/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandler.java +++ b/core/src/main/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandler.java @@ -22,19 +22,16 @@ import java.util.List; /** * A NameClassPairCallbackHandler to collect all results in an internal List. - * + * * @see LdapTemplate - * * @author Mattias Hellborg Arthursson */ -public abstract class CollectingNameClassPairCallbackHandler implements - NameClassPairCallbackHandler { +public abstract class CollectingNameClassPairCallbackHandler implements NameClassPairCallbackHandler { private List list = new LinkedList(); /** * Get the assembled list. - * * @return the list of all assembled objects. */ public List getList() { @@ -43,22 +40,20 @@ public abstract class CollectingNameClassPairCallbackHandler implements /** * Pass on the supplied NameClassPair to - * {@link #getObjectFromNameClassPair(NameClassPair)} and add the result to - * the internal list. + * {@link #getObjectFromNameClassPair(NameClassPair)} and add the result to the + * internal list. */ public final void handleNameClassPair(NameClassPair nameClassPair) throws NamingException { list.add(getObjectFromNameClassPair(nameClassPair)); } /** - * Handle a NameClassPair and transform it to an Object of the desired type - * and with data from the NameClassPair. - * - * @param nameClassPair - * a NameClassPair from a search operation. + * Handle a NameClassPair and transform it to an Object of the desired type and with + * data from the NameClassPair. + * @param nameClassPair a NameClassPair from a search operation. * @return an object constructed from the data in the NameClassPair. * @throws NamingException if an error occurs. */ - public abstract T getObjectFromNameClassPair( - NameClassPair nameClassPair) throws NamingException; + public abstract T getObjectFromNameClassPair(NameClassPair nameClassPair) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/ContextAssembler.java b/core/src/main/java/org/springframework/ldap/core/ContextAssembler.java index cd7ca83f..f9edf320 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextAssembler.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextAssembler.java @@ -17,20 +17,19 @@ package org.springframework.ldap.core; /** - * Helper interface to be used by Dao implementations for assembling to and from - * context. Useful if we have assembler classes responsible for mapping to and - * from a specific entry. - * + * Helper interface to be used by Dao implementations for assembling to and from context. + * Useful if we have assembler classes responsible for mapping to and from a specific + * entry. + * * @author Mattias Hellborg Arthursson */ public interface ContextAssembler extends ContextMapper { + /** * Map the supplied object to the specified context. - * - * @param obj - * the object to read data from. - * @param ctx - * the context to map to. + * @param obj the object to read data from. + * @param ctx the context to map to. */ void mapToContext(Object obj, Object ctx); + } diff --git a/core/src/main/java/org/springframework/ldap/core/ContextExecutor.java b/core/src/main/java/org/springframework/ldap/core/ContextExecutor.java index f884d058..6fb72e53 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextExecutor.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextExecutor.java @@ -20,9 +20,9 @@ import javax.naming.directory.DirContext; /** * Interface for delegating an actual operation to be performed on a - * DirContext. For searches, use {@link SearchExecutor} in - * stead. A typical usage of this interface could be e.g.: - * + * DirContext. For searches, use {@link SearchExecutor} in stead. A typical + * usage of this interface could be e.g.: + * *

  * ContextExecutor executor = new ContextExecutor() {
  *	 public Object executeWithContext(DirContext ctx) throws NamingException {
@@ -30,21 +30,19 @@ import javax.naming.directory.DirContext;
  *	 }
  * };
  * 
- * + * * @see LdapTemplate#executeReadOnly(ContextExecutor) * @see LdapTemplate#executeReadWrite(ContextExecutor) - * * @author Mattias Hellborg Arthursson */ public interface ContextExecutor { + /** * Perform any operation on the context. - * - * @param ctx - * the DirContext to perform the operation on. + * @param ctx the DirContext to perform the operation on. * @return any object resulting from the operation - might be null. - * @throws NamingException - * if the operation resulted in one. + * @throws NamingException if the operation resulted in one. */ T executeWithContext(DirContext ctx) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/ContextMapper.java b/core/src/main/java/org/springframework/ldap/core/ContextMapper.java index 7b441c35..7f6b6031 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextMapper.java @@ -27,18 +27,17 @@ import javax.naming.directory.SearchResult; /** * An interface used by LdapTemplate to map LDAP Contexts to beans. When a * DirObjectFactory is set on the ContextSource, the objects returned from - * search and listBindings operations are - * automatically transformed to DirContext objects (when using the - * {@link DefaultDirObjectFactory} - which is typically the case, unless - * something else has been explicitly specified - you get a - * {@link DirContextAdapter} object). This object will then be passed to the + * search and listBindings operations are automatically + * transformed to DirContext objects (when using the {@link DefaultDirObjectFactory} - + * which is typically the case, unless something else has been explicitly specified - you + * get a {@link DirContextAdapter} object). This object will then be passed to the * ContextMapper implementation for transformation to the desired bean. *

- * ContextMapper implementations are typically stateless and thus reusable; they - * are ideal for implementing mapping logic in one place. + * ContextMapper implementations are typically stateless and thus reusable; they are ideal + * for implementing mapping logic in one place. *

* Alternatively, consider using an {@link AttributesMapper} in stead. - * + * * @see LdapTemplate#search(Name, String, ContextMapper) * @see LdapTemplate#listBindings(Name, ContextMapper) * @see LdapTemplate#lookup(Name, ContextMapper) @@ -46,22 +45,19 @@ import javax.naming.directory.SearchResult; * @see DefaultDirObjectFactory * @see DirContextAdapter * @see AbstractContextMapper - * * @author Mattias Hellborg Arthursson */ public interface ContextMapper { + /** - * Map a single LDAP Context to an object. The supplied Object - * ctx is the object from a single {@link SearchResult}, - * {@link Binding}, or a lookup operation. - * - * @param ctx - * the context to map to an object. Typically this will be a - * {@link DirContextAdapter} instance, unless a project specific - * DirObjectFactory has been specified on the - * ContextSource. + * Map a single LDAP Context to an object. The supplied Object ctx is the + * object from a single {@link SearchResult}, {@link Binding}, or a lookup operation. + * @param ctx the context to map to an object. Typically this will be a + * {@link DirContextAdapter} instance, unless a project specific + * DirObjectFactory has been specified on the ContextSource. * @return an object built from the data in the context. * @throws NamingException if an error occurs. */ T mapFromContext(Object ctx) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/ContextMapperCallbackHandler.java b/core/src/main/java/org/springframework/ldap/core/ContextMapperCallbackHandler.java index 3da9e991..089320b4 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextMapperCallbackHandler.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextMapperCallbackHandler.java @@ -22,23 +22,21 @@ import javax.naming.NameClassPair; import javax.naming.NamingException; /** - * A CollectingNameClassPairCallbackHandler to wrap a ContextMapper. That is, - * the found object is extracted from each {@link Binding}, and then passed to - * the specified ContextMapper for translation. - * + * A CollectingNameClassPairCallbackHandler to wrap a ContextMapper. That is, the found + * object is extracted from each {@link Binding}, and then passed to the specified + * ContextMapper for translation. + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg * @since 1.2 */ -public class ContextMapperCallbackHandler extends - CollectingNameClassPairCallbackHandler { +public class ContextMapperCallbackHandler extends CollectingNameClassPairCallbackHandler { + private ContextMapper mapper; /** * Constructs a new instance wrapping the supplied {@link ContextMapper}. - * - * @param mapper - * the mapper to be called for each entry. + * @param mapper the mapper to be called for each entry. */ public ContextMapperCallbackHandler(ContextMapper mapper) { Assert.notNull(mapper, "Mapper must not be empty"); @@ -46,11 +44,9 @@ public class ContextMapperCallbackHandler extends } /** - * Cast the NameClassPair to a {@link Binding} and pass its object to - * the ContextMapper. - * - * @param nameClassPair - * a Binding instance. + * Cast the NameClassPair to a {@link Binding} and pass its object to the + * ContextMapper. + * @param nameClassPair a Binding instance. * @return the Object returned from the mapper. * @throws NamingException if an error occurs. * @throws ObjectRetrievalException if the object of the nameClassPair is null. @@ -63,9 +59,9 @@ public class ContextMapperCallbackHandler extends Binding binding = (Binding) nameClassPair; Object object = binding.getObject(); if (object == null) { - throw new ObjectRetrievalException( - "Binding did not contain any object."); + throw new ObjectRetrievalException("Binding did not contain any object."); } return mapper.mapFromContext(object); } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/core/ContextSource.java b/core/src/main/java/org/springframework/ldap/core/ContextSource.java index 0c2dd5fe..2862dd9e 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextSource.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextSource.java @@ -22,22 +22,19 @@ import javax.naming.directory.DirContext; /** * A ContextSource is responsible for configuring and creating - * DirContext instances. It is typically used from - * {@link LdapTemplate} to acquiring contexts for LDAP operations, but may be - * used standalone to perform LDAP authentication. - * + * DirContext instances. It is typically used from {@link LdapTemplate} to + * acquiring contexts for LDAP operations, but may be used standalone to perform LDAP + * authentication. + * * @see org.springframework.ldap.core.LdapTemplate - * * @author Adam Skogman * @author Mattias Hellborg Arthursson */ public interface ContextSource { /** - * Gets a read-only DirContext. The returned - * DirContext must be possible to perform read-only operations - * on. - * + * Gets a read-only DirContext. The returned DirContext must + * be possible to perform read-only operations on. * @return A DirContext instance, never null. * @throws NamingException if some error occurs creating an DirContext. */ @@ -45,27 +42,23 @@ public interface ContextSource { /** * Gets a read-write DirContext instance. - * * @return A DirContext instance, never null. - * @throws NamingException if some error occurs creating an - * DirContext. + * @throws NamingException if some error occurs creating an DirContext. */ DirContext getReadWriteContext() throws NamingException; /** - * Gets a DirContext instance authenticated using the supplied - * principal and credentials. Typically to be used for plain authentication - * purposes. Note that this method will never make use - * of native Java LDAP pooling, even though this instance is configured to do so. - * This is to force password changes in the target directory to take effect - * as soon as possible. - * - * @param principal The principal (typically a distinguished name of a user - * in the LDAP tree) to use for authentication. + * Gets a DirContext instance authenticated using the supplied principal + * and credentials. Typically to be used for plain authentication purposes. + * Note that this method will never make use of native Java LDAP + * pooling, even though this instance is configured to do so. This is to force + * password changes in the target directory to take effect as soon as possible. + * @param principal The principal (typically a distinguished name of a user in the + * LDAP tree) to use for authentication. * @param credentials The credentials to use for authentication. - * @return an authenticated DirContext instance, never - * null. + * @return an authenticated DirContext instance, never null. * @since 1.3 */ DirContext getContext(String principal, String credentials) throws NamingException; + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/core/DefaultDnParserFactory.java b/core/src/main/java/org/springframework/ldap/core/DefaultDnParserFactory.java index 13aa1377..b31eb194 100644 --- a/core/src/main/java/org/springframework/ldap/core/DefaultDnParserFactory.java +++ b/core/src/main/java/org/springframework/ldap/core/DefaultDnParserFactory.java @@ -18,13 +18,14 @@ package org.springframework.ldap.core; import java.io.StringReader; /** - * A factory for creating DnParser instances. The actual implementation of - * DnParser is generated using javacc and should not be constructed directly. - * + * A factory for creating DnParser instances. The actual implementation of DnParser is + * generated using javacc and should not be constructed directly. + * * @author Mattias Hellborg Arthursson * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. */ public final class DefaultDnParserFactory { + /** * Not to be instantiated. */ @@ -34,12 +35,11 @@ public final class DefaultDnParserFactory { /** * Create a new DnParser instance. - * - * @param string - * the DN String to be parsed. + * @param string the DN String to be parsed. * @return a new DnParser instance for parsing the supplied DN string. */ public static DnParser createDnParser(String string) { return new DnParserImpl(new StringReader(string)); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/DefaultLdapClient.java b/core/src/main/java/org/springframework/ldap/core/DefaultLdapClient.java index 25062f7a..55e3dbbf 100644 --- a/core/src/main/java/org/springframework/ldap/core/DefaultLdapClient.java +++ b/core/src/main/java/org/springframework/ldap/core/DefaultLdapClient.java @@ -62,6 +62,7 @@ import org.springframework.util.Assert; * @since 3.1 */ class DefaultLdapClient implements LdapClient { + private final Logger logger = LoggerFactory.getLogger(DefaultLdapClient.class); private static final boolean DONT_RETURN_OBJ_FLAG = false; @@ -151,13 +152,13 @@ class DefaultLdapClient implements LdapClient { */ @Override public Builder mutate() { - return new DefaultLdapClientBuilder(this.contextSource, this.searchControlsSupplier); + return new DefaultLdapClientBuilder(this.contextSource, this.searchControlsSupplier); } /** * Ignore {@link PartialResultException}s. - * - * @param ignorePartialResultException whether to ignore {@link PartialResultException}s + * @param ignorePartialResultException whether to ignore + * {@link PartialResultException}s */ void setIgnorePartialResultException(boolean ignorePartialResultException) { this.ignorePartialResultException = ignorePartialResultException; @@ -165,24 +166,23 @@ class DefaultLdapClient implements LdapClient { /** * Ignore {@link NameNotFoundException}s. - * * @param ignoreNameNotFoundException whether to ignore {@link NameNotFoundException}s */ void setIgnoreNameNotFoundException(boolean ignoreNameNotFoundException) { this.ignoreNameNotFoundException = ignoreNameNotFoundException; } - /** * Ignore {@link SizeLimitExceededException}s. - * - * @param ignoreSizeLimitExceededException whether to ignore {@link SizeLimitExceededException}s + * @param ignoreSizeLimitExceededException whether to ignore + * {@link SizeLimitExceededException}s */ void setIgnoreSizeLimitExceededException(boolean ignoreSizeLimitExceededException) { this.ignoreSizeLimitExceededException = ignoreSizeLimitExceededException; } private final class DefaultListSpec implements ListSpec { + private final Name name; private DefaultListSpec(Name name) { @@ -202,9 +202,11 @@ class DefaultLdapClient implements LdapClient { NamingEnumeration results = computeWithReadOnlyContext(executor); return DefaultLdapClient.this.toStream(results, mapper::mapFromNameClassPair); } + } private final class DefaultListBindingsSpec implements ListBindingsSpec { + private final Name name; private DefaultListBindingsSpec(Name name) { @@ -238,9 +240,11 @@ class DefaultLdapClient implements LdapClient { NamingEnumeration results = computeWithReadOnlyContext(executor); return DefaultLdapClient.this.toStream(results, function(mapper)); } + } private final class DefaultAuthenticateSpec implements AuthenticateSpec { + LdapClient.SearchSpec search = new DefaultSearchSpec(); char[] password; @@ -277,14 +281,17 @@ class DefaultLdapClient implements LdapClient { String password = (this.password != null) ? new String(this.password) : null; ctx = contextSource.getContext(identification.get(0).getAbsoluteName().toString(), password); return mapper.mapWithContext(ctx, identification.get(0)); - } finally { + } + finally { this.password = null; closeContext(ctx); } } + } private final class DefaultSearchSpec implements SearchSpec { + LdapQuery query = LdapQueryBuilder.query().filter("(objectClass=*)"); SearchControls controls; @@ -373,12 +380,17 @@ class DefaultLdapClient implements LdapClient { } return controls; } + } private final class DefaultBindSpec implements BindSpec { + private final Name name; + private Object obj; + private Attributes attributes; + private boolean rebind = false; private DefaultBindSpec(Name name) { @@ -409,15 +421,20 @@ class DefaultLdapClient implements LdapClient { public void execute() { if (this.rebind) { runWithReadWriteContext((ctx) -> ctx.rebind(this.name, this.obj, this.attributes)); - } else { + } + else { runWithReadWriteContext((ctx) -> ctx.bind(this.name, this.obj, this.attributes)); } } + } private final class DefaultModifySpec implements ModifySpec { + private final DirContextOperations entry; + private Name name; + private ModificationItem[] items; private DefaultModifySpec(DirContextOperations entry) { @@ -455,7 +472,8 @@ class DefaultLdapClient implements LdapClient { if (this.items.length > 0) { runWithReadWriteContext((ctx) -> ctx.modifyAttributes(this.name, this.items)); } - } catch (Throwable t) { + } + catch (Throwable t) { if (renamed) { // attempt to change the name back runWithReadWriteContext((ctx) -> ctx.rename(this.name, this.entry.getDn())); @@ -463,10 +481,13 @@ class DefaultLdapClient implements LdapClient { throw t; } } + } private final class DefaultUnbindSpec implements UnbindSpec { + private final Name name; + private boolean recursive = false; private DefaultUnbindSpec(Name name) { @@ -502,20 +523,24 @@ class DefaultLdapClient implements LdapClient { if (DefaultLdapClient.this.logger.isDebugEnabled()) { DefaultLdapClient.this.logger.debug("Entry " + name + " deleted"); } - } finally { + } + finally { closeNamingEnumeration(bindings); } } + } T computeWithReadOnlyContext(ContextExecutor executor) { DirContext context = this.contextSource.getReadOnlyContext(); try { return executor.executeWithContext(context); - } catch (NamingException ex) { + } + catch (NamingException ex) { this.namingExceptionHandler.accept(ex); return null; - } finally { + } + finally { closeContext(context); } } @@ -524,9 +549,11 @@ class DefaultLdapClient implements LdapClient { DirContext context = this.contextSource.getReadWriteContext(); try { runnable.run(context); - } catch (NamingException ex) { + } + catch (NamingException ex) { this.namingExceptionHandler.accept(ex); - } finally { + } + finally { closeContext(context); } } @@ -545,7 +572,8 @@ class DefaultLdapClient implements LdapClient { public boolean hasMoreElements() { try { return enumeration.hasMore(); - } catch (NamingException ex) { + } + catch (NamingException ex) { namingExceptionHandler.accept(ex); return false; } @@ -555,7 +583,8 @@ class DefaultLdapClient implements LdapClient { public T nextElement() { try { return enumeration.next(); - } catch (NamingException ex) { + } + catch (NamingException ex) { namingExceptionHandler.accept(ex); throw new NoSuchElementException("no such element", ex); } @@ -589,7 +618,8 @@ class DefaultLdapClient implements LdapClient { throw LdapUtils.convertLdapException(ex); }; - private T toObject(NamingEnumeration results, NamingExceptionFunction mapper) { + private T toObject(NamingEnumeration results, + NamingExceptionFunction mapper) { try { Enumeration enumeration = enumeration(results); Function function = mapper.wrap(this.namingExceptionHandler); @@ -601,12 +631,14 @@ class DefaultLdapClient implements LdapClient { throw new IncorrectResultSizeDataAccessException(1); } return result; - } finally { + } + finally { closeNamingEnumeration(results); } } - private List toList(NamingEnumeration results, NamingExceptionFunction mapper) { + private List toList(NamingEnumeration results, + NamingExceptionFunction mapper) { if (results == null) { return Collections.emptyList(); } @@ -621,20 +653,22 @@ class DefaultLdapClient implements LdapClient { } } return mapped; - } finally { + } + finally { closeNamingEnumeration(results); } } - private Stream toStream(NamingEnumeration results, NamingExceptionFunction mapper) { + private Stream toStream(NamingEnumeration results, + NamingExceptionFunction mapper) { if (results == null) { return Stream.empty(); } Enumeration enumeration = enumeration(results); Function function = mapper.wrap(this.namingExceptionHandler); - return StreamSupport.stream(Spliterators.spliteratorUnknownSize(enumeration.asIterator(), Spliterator.ORDERED), false) - .map(function::apply).filter(Objects::nonNull) - .onClose(() -> closeNamingEnumeration(results)); + return StreamSupport + .stream(Spliterators.spliteratorUnknownSize(enumeration.asIterator(), Spliterator.ORDERED), false) + .map(function::apply).filter(Objects::nonNull).onClose(() -> closeNamingEnumeration(results)); } private void closeContext(DirContext ctx) { @@ -660,22 +694,27 @@ class DefaultLdapClient implements LdapClient { } interface ContextRunnable { + void run(DirContext ctx) throws NamingException; + } interface NamingExceptionFunction { + T apply(S element) throws NamingException; default Function wrap(Consumer handler) { return (s) -> { try { return apply(s); - } catch (NamingException ex) { + } + catch (NamingException ex) { handler.accept(ex); return null; } }; } - } -} + } + +} diff --git a/core/src/main/java/org/springframework/ldap/core/DefaultLdapClientBuilder.java b/core/src/main/java/org/springframework/ldap/core/DefaultLdapClientBuilder.java index 2f2ebdfd..27eeb9a6 100644 --- a/core/src/main/java/org/springframework/ldap/core/DefaultLdapClientBuilder.java +++ b/core/src/main/java/org/springframework/ldap/core/DefaultLdapClientBuilder.java @@ -6,6 +6,7 @@ import java.util.function.Supplier; import javax.naming.directory.SearchControls; class DefaultLdapClientBuilder implements LdapClient.Builder { + private ContextSource contextSource; private Supplier searchControlsSupplier = () -> { @@ -22,10 +23,10 @@ class DefaultLdapClientBuilder implements LdapClient.Builder { private boolean ignoreSizeLimitExceededException = true; - DefaultLdapClientBuilder() {} + DefaultLdapClientBuilder() { + } - DefaultLdapClientBuilder(ContextSource contextSource, - Supplier searchControlsSupplier) { + DefaultLdapClientBuilder(ContextSource contextSource, Supplier searchControlsSupplier) { this.contextSource = contextSource; this.searchControlsSupplier = searchControlsSupplier; } @@ -88,4 +89,5 @@ class DefaultLdapClientBuilder implements LdapClient.Builder { client.setIgnoreNameNotFoundException(this.ignoreNameNotFoundException); return client; } + } diff --git a/core/src/main/java/org/springframework/ldap/core/DefaultNameClassPairMapper.java b/core/src/main/java/org/springframework/ldap/core/DefaultNameClassPairMapper.java index 5d986371..fb25f6fd 100644 --- a/core/src/main/java/org/springframework/ldap/core/DefaultNameClassPairMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/DefaultNameClassPairMapper.java @@ -20,26 +20,21 @@ import javax.naming.NameClassPair; import javax.naming.NamingException; /** - * The default NameClassPairMapper implementation. This implementation simply - * takes the Name string from the supplied NameClassPair and returns it as - * result. - * + * The default NameClassPairMapper implementation. This implementation simply takes the + * Name string from the supplied NameClassPair and returns it as result. + * * @author Mattias Hellborg Arthursson - * + * */ public class DefaultNameClassPairMapper implements NameClassPairMapper { /** - * Gets the Name from the supplied NameClassPair and returns it as the - * result. - * - * @param nameClassPair - * the NameClassPair to transform. + * Gets the Name from the supplied NameClassPair and returns it as the result. + * @param nameClassPair the NameClassPair to transform. * @return the Name string from the NameClassPair. */ @Override - public String mapFromNameClassPair(NameClassPair nameClassPair) - throws NamingException { + public String mapFromNameClassPair(NameClassPair nameClassPair) throws NamingException { return nameClassPair.getName(); } diff --git a/core/src/main/java/org/springframework/ldap/core/DirContextAdapter.java b/core/src/main/java/org/springframework/ldap/core/DirContextAdapter.java index 0d777618..50f2af17 100644 --- a/core/src/main/java/org/springframework/ldap/core/DirContextAdapter.java +++ b/core/src/main/java/org/springframework/ldap/core/DirContextAdapter.java @@ -46,38 +46,37 @@ import java.util.SortedSet; import java.util.TreeSet; /** - * Adapter that implements the interesting methods of the DirContext interface. - * In particular it contains utility methods for getting and setting attributes. - * Using the + * Adapter that implements the interesting methods of the DirContext interface. In + * particular it contains utility methods for getting and setting attributes. Using the * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory} in your - * ContextSource (which is the default) you will receive instances - * of this class from searches and lookups. This can be particularly useful when - * updating data, since this class implements - * {@link AttributeModificationsAware}, providing a - * {@link #getModificationItems()} method. When in update mode, an object of - * this class keeps track of the changes made to its attributes, making them - * available as an array of ModificationItem objects, suitable as - * input to {@link LdapTemplate#modifyAttributes(DirContextOperations)}. + * ContextSource (which is the default) you will receive instances of this + * class from searches and lookups. This can be particularly useful when updating data, + * since this class implements {@link AttributeModificationsAware}, providing a + * {@link #getModificationItems()} method. When in update mode, an object of this class + * keeps track of the changes made to its attributes, making them available as an array of + * ModificationItem objects, suitable as input to + * {@link LdapTemplate#modifyAttributes(DirContextOperations)}. * *

- * This class is aware of the specifics of {@link Name} instances with regards - * to equality when working with attribute values. This comes in very handy - * when working with e.g. security groups and modifications of them. If - * {@link Name} instances are supplied to one of the Attribute manipulation - * methods (e.g. {@link #addAttributeValue(String, Object)}, - * {@link #removeAttributeValue(String, Object)}, {@link #setAttributeValue(String, Object)}, - * or {@link #setAttributeValues(String, Object[])}), the produced modifications - * will be calculated using {@link Name} equality. This means that if an the member - * has a value of "cn=John Doe,ou=People", and we call - * addAttributeValue("member", LdapUtils.newLdapName("CN=John Doe,OU=People"), - * this will not be considered a modification since the two DN - * strings represent the same distinguished name (case and spacing between attributes is - * disregarded). + * This class is aware of the specifics of {@link Name} instances with regards to equality + * when working with attribute values. This comes in very handy when working with e.g. + * security groups and modifications of them. If {@link Name} instances are supplied to + * one of the Attribute manipulation methods (e.g. + * {@link #addAttributeValue(String, Object)}, + * {@link #removeAttributeValue(String, Object)}, + * {@link #setAttributeValue(String, Object)}, or + * {@link #setAttributeValues(String, Object[])}), the produced modifications will be + * calculated using {@link Name} equality. This means that if an the member + * has a value of "cn=John Doe,ou=People", and we call + * addAttributeValue("member", LdapUtils.newLdapName("CN=John Doe,OU=People"), + * this will not be considered a modification since the two DN strings + * represent the same distinguished name (case and spacing between attributes is + * disregarded). *

*

- * Note that this is not a complete implementation of DirContext. Several - * methods are not relevant for the intended usage of this class, so they - * throw UnsupportOperationException. + * Note that this is not a complete implementation of DirContext. Several methods are not + * relevant for the intended usage of this class, so they throw + * UnsupportOperationException. *

* * @see #setAttributeValue(String, Object) @@ -89,7 +88,6 @@ import java.util.TreeSet; * @see #removeAttributeValue(String, Object) * @see #setUpdateMode(boolean) * @see #isUpdateMode() - * * @author Magnus Robertsson * @author Andreas Ronge * @author Adam Skogman @@ -102,6 +100,7 @@ public class DirContextAdapter implements DirContextOperations { private static final String EMPTY_STRING = ""; private static final boolean ORDER_DOESNT_MATTER = false; + private static final String NOT_IMPLEMENTED = "Not implemented."; private static Logger log = LoggerFactory.getLogger(DirContextAdapter.class); @@ -127,8 +126,8 @@ public class DirContextAdapter implements DirContextOperations { /** * Create a new DirContextAdapter from the supplied DN String. - * @param dnString the DN string. Must be syntactically correct, or an - * exception will be thrown. + * @param dnString the DN string. Must be syntactically correct, or an exception will + * be thrown. */ public DirContextAdapter(String dnString) { this(LdapUtils.newLdapName(dnString)); @@ -136,7 +135,6 @@ public class DirContextAdapter implements DirContextOperations { /** * Create a new adapter from the supplied dn. - * * @param dn the dn. */ public DirContextAdapter(Name dn) { @@ -145,7 +143,6 @@ public class DirContextAdapter implements DirContextOperations { /** * Create a new adapter from the supplied attributes and dn. - * * @param attrs the attributes. * @param dn the dn. */ @@ -155,7 +152,6 @@ public class DirContextAdapter implements DirContextOperations { /** * Create a new adapter from the supplied attributes, dn, and base. - * * @param attrs the attributes. * @param dn the dn. * @param base the base name. @@ -165,16 +161,13 @@ public class DirContextAdapter implements DirContextOperations { } /** - * Create a new adapter from the supplied attributes, dn, base, and referral - * url. + * Create a new adapter from the supplied attributes, dn, base, and referral url. * @param attrs the attributes. * @param dn the dn. * @param base the base. - * @param referralUrl the referral url (if this instance results from a - * referral). + * @param referralUrl the referral url (if this instance results from a referral). */ - public DirContextAdapter(Attributes attrs, Name dn, Name base, - String referralUrl) { + public DirContextAdapter(Attributes attrs, Name dn, Name base, String referralUrl) { if (attrs != null) { this.originalAttrs = new NameAwareAttributes(attrs); } @@ -205,7 +198,6 @@ public class DirContextAdapter implements DirContextOperations { /** * Constructor for cloning an existing adapter. - * * @param main The adapter to be copied. */ protected DirContextAdapter(DirContextAdapter main) { @@ -216,10 +208,8 @@ public class DirContextAdapter implements DirContextOperations { } /** - * Sets the update mode. The update mode should be false for a - * new entry and true for an existing entry that is being - * updated. - * + * Sets the update mode. The update mode should be false for a new entry + * and true for an existing entry that is being updated. * @param mode Update mode. */ public void setUpdateMode(boolean mode) { @@ -255,8 +245,7 @@ public class DirContextAdapter implements DirContextOperations { try { while (attributesEnumeration.hasMore()) { - Attribute oneAttribute = attributesEnumeration - .next(); + Attribute oneAttribute = attributesEnumeration.next(); tmpList.add(oneAttribute.getID()); } } @@ -317,28 +306,27 @@ public class DirContextAdapter implements DirContextOperations { } /** - * Collect all modifications for the changed attribute. If no changes have - * been made, return immediately. If modifications have been made, and the - * original size as well as the updated size of the attribute is 1, replace - * the attribute. If the size of the updated attribute is 0, remove the - * attribute. Otherwise, the attribute is a multi-value attribute; if it's - * an ordered one it should be replaced in its entirety to preserve the new - * ordering, if not all modifications to the original value (removals and - * additions) will be collected individually. - * + * Collect all modifications for the changed attribute. If no changes have been made, + * return immediately. If modifications have been made, and the original size as well + * as the updated size of the attribute is 1, replace the attribute. If the size of + * the updated attribute is 0, remove the attribute. Otherwise, the attribute is a + * multi-value attribute; if it's an ordered one it should be replaced in its entirety + * to preserve the new ordering, if not all modifications to the original value + * (removals and additions) will be collected individually. * @param changedAttr the value of the changed attribute. * @param modificationList the list in which to add the modifications. * @throws NamingException if thrown by called Attribute methods. */ - private void collectModifications(NameAwareAttribute changedAttr, - List modificationList) throws NamingException { + private void collectModifications(NameAwareAttribute changedAttr, List modificationList) + throws NamingException { NameAwareAttribute currentAttribute = originalAttrs.get(changedAttr.getID()); - if(currentAttribute != null && changedAttr.hasValuesAsNames()) { + if (currentAttribute != null && changedAttr.hasValuesAsNames()) { try { currentAttribute.initValuesAsNames(); - } catch(IllegalArgumentException e) { - log.warn("Incompatible attributes; changed attribute has Name values but " + - "original cannot be converted to this"); + } + catch (IllegalArgumentException e) { + log.warn("Incompatible attributes; changed attribute has Name values but " + + "original cannot be converted to this"); } } @@ -346,29 +334,23 @@ public class DirContextAdapter implements DirContextOperations { // No changes return; } - else if (currentAttribute != null && currentAttribute.size() == 1 - && changedAttr.size() == 1) { + else if (currentAttribute != null && currentAttribute.size() == 1 && changedAttr.size() == 1) { // Replace single-vale attribute. - modificationList.add(new ModificationItem( - DirContext.REPLACE_ATTRIBUTE, changedAttr)); + modificationList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, changedAttr)); } else if (changedAttr.size() == 0 && currentAttribute != null) { // Attribute has been removed. - modificationList.add(new ModificationItem( - DirContext.REMOVE_ATTRIBUTE, changedAttr)); + modificationList.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, changedAttr)); } - else if ((currentAttribute == null || currentAttribute.size() == 0) - && changedAttr.size() > 0) { + else if ((currentAttribute == null || currentAttribute.size() == 0) && changedAttr.size() > 0) { // Attribute has been added. - modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, - changedAttr)); + modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, changedAttr)); } else if (changedAttr.size() > 0 && changedAttr.isOrdered()) { // This is a multivalue attribute and it is ordered - the original // value should be replaced with the new values so that the ordering // is preserved. - modificationList.add(new ModificationItem( - DirContext.REPLACE_ATTRIBUTE, changedAttr)); + modificationList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, changedAttr)); } else if (changedAttr.size() > 0) { // Change of multivalue Attribute. Collect additions and removals @@ -380,24 +362,21 @@ public class DirContextAdapter implements DirContextOperations { // This means that the attributes are not equal, but the // actual values are the same - thus the order must have // changed. This should result in a REPLACE_ATTRIBUTE operation. - myModifications.add(new ModificationItem( - DirContext.REPLACE_ATTRIBUTE, changedAttr)); + myModifications.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, changedAttr)); } modificationList.addAll(myModifications); } } - private void collectModifications(Attribute originalAttr, - Attribute changedAttr, List modificationList) - throws NamingException { + private void collectModifications(Attribute originalAttr, Attribute changedAttr, + List modificationList) throws NamingException { Attribute originalClone = (Attribute) originalAttr.clone(); - Attribute addedValuesAttribute = new NameAwareAttribute(originalAttr - .getID()); + Attribute addedValuesAttribute = new NameAwareAttribute(originalAttr.getID()); NamingEnumeration allValues = changedAttr.getAll(); - while(allValues.hasMoreElements()) { + while (allValues.hasMoreElements()) { Object attributeValue = allValues.nextElement(); if (!originalClone.remove(attributeValue)) { addedValuesAttribute.add(attributeValue); @@ -407,28 +386,25 @@ public class DirContextAdapter implements DirContextOperations { // We have now traversed and removed all values from the original that // were also present in the new values. The remaining values in the // original must be the ones that were removed. - if(originalClone.size() > 0 && originalClone.size() == originalAttr.size()) { + if (originalClone.size() > 0 && originalClone.size() == originalAttr.size()) { // This is actually a complete replacement of the attribute values. // Fall back to REPLACE - modificationList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, - addedValuesAttribute)); - } else { + modificationList.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, addedValuesAttribute)); + } + else { if (originalClone.size() > 0) { - modificationList.add(new ModificationItem( - DirContext.REMOVE_ATTRIBUTE, originalClone)); + modificationList.add(new ModificationItem(DirContext.REMOVE_ATTRIBUTE, originalClone)); } if (addedValuesAttribute.size() > 0) { - modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, - addedValuesAttribute)); + modificationList.add(new ModificationItem(DirContext.ADD_ATTRIBUTE, addedValuesAttribute)); } } } /** - * returns true if the attribute is empty. It is empty if a == null, size == - * 0 or get() == null or an exception if thrown when accessing the get - * method + * returns true if the attribute is empty. It is empty if a == null, size == 0 or + * get() == null or an exception if thrown when accessing the get method */ private boolean isEmptyAttribute(Attribute a) { try { @@ -440,21 +416,18 @@ public class DirContextAdapter implements DirContextOperations { } /** - * Compare the existing attribute name with the values on the - * array values. The order of the array must be the same order - * as the existing multivalued attribute. + * Compare the existing attribute name with the values on the array + * values. The order of the array must be the same order as the existing + * multivalued attribute. *

- * Also handles the case where the values have been reset to the original - * values after a previous change. For example, changing - * [a,b,c] to [a,b] and then back to - * [a,b,c] again must result in this method returning - * true so the first change can be overwritten with the latest - * change. - * + * Also handles the case where the values have been reset to the original values after + * a previous change. For example, changing [a,b,c] to [a,b] + * and then back to [a,b,c] again must result in this method returning + * true so the first change can be overwritten with the latest change. * @param name Name of the original multi-valued attribute. * @param values Array of values to check if they have been changed. - * @return true if there has been a change compared to original attribute, - * or a previous update + * @return true if there has been a change compared to original attribute, or a + * previous update */ private boolean isChanged(String name, Object[] values, boolean orderMatters) { @@ -533,9 +506,8 @@ public class DirContextAdapter implements DirContextOperations { /** * Checks if an entry has a specific attribute. - * + * * This method simply calls exists(String) with the attribute name. - * * @param attr the attribute to check. * @return true if attribute exists in entry. */ @@ -544,9 +516,8 @@ public class DirContextAdapter implements DirContextOperations { } /** - * Checks if the attribute exists in this entry, either it was read or it - * has been added and update() has been called. - * + * Checks if the attribute exists in this entry, either it was read or it has been + * added and update() has been called. * @param attrId id of the attribute to check. * @return true if the attribute exists in the entry. */ @@ -621,8 +592,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void addAttributeValue(String name, Object value, - boolean addIfDuplicateExists) { + public void addAttributeValue(String name, Object value, boolean addIfDuplicateExists) { if (!updateMode && value != null) { Attribute attr = originalAttrs.get(name); if (attr == null) { @@ -697,8 +667,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void setAttributeValues(String name, Object[] values, - boolean orderMatters) { + public void setAttributeValues(String name, Object[] values, boolean orderMatters) { Attribute a = new NameAwareAttribute(name, orderMatters); for (int i = 0; values != null && i < values.length; i++) { @@ -806,7 +775,6 @@ public class DirContextAdapter implements DirContextOperations { /** * Set the supplied attribute. - * * @param attribute the attribute to set. */ public void setAttribute(Attribute attribute) { @@ -820,7 +788,6 @@ public class DirContextAdapter implements DirContextOperations { /** * Get all attributes. - * * @return all attributes. */ public Attributes getAttributes() { @@ -850,8 +817,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public Attributes getAttributes(Name name, String[] attrIds) - throws NamingException { + public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { return getAttributes(name.toString(), attrIds); } @@ -859,8 +825,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public Attributes getAttributes(String name, String[] attrIds) - throws NamingException { + public Attributes getAttributes(String name, String[] attrIds) throws NamingException { if (StringUtils.hasLength(name)) { throw new NameNotFoundException(); } @@ -881,8 +846,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void modifyAttributes(Name name, int modOp, Attributes attrs) - throws NamingException { + public void modifyAttributes(Name name, int modOp, Attributes attrs) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -890,8 +854,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void modifyAttributes(String name, int modOp, Attributes attrs) - throws NamingException { + public void modifyAttributes(String name, int modOp, Attributes attrs) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -899,8 +862,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void modifyAttributes(Name name, ModificationItem[] mods) - throws NamingException { + public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -908,8 +870,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void modifyAttributes(String name, ModificationItem[] mods) - throws NamingException { + public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -917,8 +878,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void bind(Name name, Object obj, Attributes attrs) - throws NamingException { + public void bind(Name name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -926,8 +886,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void bind(String name, Object obj, Attributes attrs) - throws NamingException { + public void bind(String name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -935,8 +894,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void rebind(Name name, Object obj, Attributes attrs) - throws NamingException { + public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -944,8 +902,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public void rebind(String name, Object obj, Attributes attrs) - throws NamingException { + public void rebind(String name, Object obj, Attributes attrs) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -953,8 +910,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public DirContext createSubcontext(Name name, Attributes attrs) - throws NamingException { + public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -962,8 +918,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public DirContext createSubcontext(String name, Attributes attrs) - throws NamingException { + public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -987,8 +942,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public DirContext getSchemaClassDefinition(Name name) - throws NamingException { + public DirContext getSchemaClassDefinition(Name name) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -996,8 +950,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public DirContext getSchemaClassDefinition(String name) - throws NamingException { + public DirContext getSchemaClassDefinition(String name) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -1005,8 +958,8 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public NamingEnumeration search(Name name, Attributes matchingAttributes, - String[] attributesToReturn) throws NamingException { + public NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) + throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -1023,7 +976,23 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public NamingEnumeration search(Name name, Attributes matchingAttributes) + public NamingEnumeration search(Name name, Attributes matchingAttributes) throws NamingException { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /** + * {@inheritDoc} + */ + @Override + public NamingEnumeration search(String name, Attributes matchingAttributes) throws NamingException { + throw new UnsupportedOperationException(NOT_IMPLEMENTED); + } + + /** + * {@inheritDoc} + */ + @Override + public NamingEnumeration search(Name name, String filter, SearchControls cons) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -1032,7 +1001,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public NamingEnumeration search(String name, Attributes matchingAttributes) + public NamingEnumeration search(String name, String filter, SearchControls cons) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -1041,7 +1010,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public NamingEnumeration search(Name name, String filter, + public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -1050,29 +1019,11 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public NamingEnumeration search(String name, String filter, + public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } - /** - * {@inheritDoc} - */ - @Override - public NamingEnumeration search(Name name, String filterExpr, - Object[] filterArgs, SearchControls cons) throws NamingException { - throw new UnsupportedOperationException(NOT_IMPLEMENTED); - } - - /** - * {@inheritDoc} - */ - @Override - public NamingEnumeration search(String name, String filterExpr, - Object[] filterArgs, SearchControls cons) throws NamingException { - throw new UnsupportedOperationException(NOT_IMPLEMENTED); - } - /** * {@inheritDoc} */ @@ -1261,8 +1212,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public String composeName(String name, String prefix) - throws NamingException { + public String composeName(String name, String prefix) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -1270,8 +1220,7 @@ public class DirContextAdapter implements DirContextOperations { * {@inheritDoc} */ @Override - public Object addToEnvironment(String propName, Object propVal) - throws NamingException { + public Object addToEnvironment(String propName, Object propVal) throws NamingException { throw new UnsupportedOperationException(NOT_IMPLEMENTED); } @@ -1304,7 +1253,7 @@ public class DirContextAdapter implements DirContextOperations { */ @Override public String getNameInNamespace() { - if(base.size() == 0) { + if (base.size() == 0) { return dn.toString(); } @@ -1312,7 +1261,8 @@ public class DirContextAdapter implements DirContextOperations { LdapName result = (LdapName) dn.clone(); result.addAll(0, base); return result.toString(); - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw new org.springframework.ldap.InvalidNameException(e); } } @@ -1334,8 +1284,7 @@ public class DirContextAdapter implements DirContextOperations { this.dn = LdapUtils.newLdapName(dn); } else { - throw new IllegalStateException( - "Not possible to call setDn() on a DirContextAdapter in update mode"); + throw new IllegalStateException("Not possible to call setDn() on a DirContextAdapter in update mode"); } } @@ -1345,18 +1294,25 @@ public class DirContextAdapter implements DirContextOperations { */ @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; DirContextAdapter that = (DirContextAdapter) o; - if (updateMode != that.updateMode) return false; - if (base != null ? !base.equals(that.base) : that.base != null) return false; - if (dn != null ? !dn.equals(that.dn) : that.dn != null) return false; + if (updateMode != that.updateMode) + return false; + if (base != null ? !base.equals(that.base) : that.base != null) + return false; + if (dn != null ? !dn.equals(that.dn) : that.dn != null) + return false; if (originalAttrs != null ? !originalAttrs.equals(that.originalAttrs) : that.originalAttrs != null) return false; - if (referralUrl != null ? !referralUrl.equals(that.referralUrl) : that.referralUrl != null) return false; - if (updatedAttrs != null ? !updatedAttrs.equals(that.updatedAttrs) : that.updatedAttrs != null) return false; + if (referralUrl != null ? !referralUrl.equals(that.referralUrl) : that.referralUrl != null) + return false; + if (updatedAttrs != null ? !updatedAttrs.equals(that.updatedAttrs) : that.updatedAttrs != null) + return false; return true; } @@ -1417,7 +1373,8 @@ public class DirContextAdapter implements DirContextOperations { return builder.toString(); } - private void appendAttributeValue(StringBuilder builder, String attributeID, Object value, int index) throws NamingException { + private void appendAttributeValue(StringBuilder builder, String attributeID, Object value, int index) + throws NamingException { if (index > 0) { builder.append(", "); } diff --git a/core/src/main/java/org/springframework/ldap/core/DirContextOperations.java b/core/src/main/java/org/springframework/ldap/core/DirContextOperations.java index e1fdf278..b308b55a 100644 --- a/core/src/main/java/org/springframework/ldap/core/DirContextOperations.java +++ b/core/src/main/java/org/springframework/ldap/core/DirContextOperations.java @@ -23,75 +23,68 @@ import javax.naming.directory.DirContext; /** * Interface for DirContextAdapter. - * + * * @author Mattias Hellborg Arthursson * @see DirContextAdapter */ -public interface DirContextOperations extends DirContext, LdapDataEntry, - AttributeModificationsAware { +public interface DirContextOperations extends DirContext, LdapDataEntry, AttributeModificationsAware { /** - * Gets the update mode. An entry in update mode will keep track of its - * modifications so that they can be retrieved using - * {@link AttributeModificationsAware#getModificationItems()}. The update - * mode should be true for a new entry and true - * for an existing entry that is being updated. - * + * Gets the update mode. An entry in update mode will keep track of its modifications + * so that they can be retrieved using + * {@link AttributeModificationsAware#getModificationItems()}. The update mode should + * be true for a new entry and true for an existing entry + * that is being updated. * @return update mode. */ boolean isUpdateMode(); /** - * Creates a String array of the names of the attributes which have been - * changed. - * - * If this is a new entry, all set entries will be in the list. If this is - * an updated entry, only changed and removed entries will be in the array. - * + * Creates a String array of the names of the attributes which have been changed. + * + * If this is a new entry, all set entries will be in the list. If this is an updated + * entry, only changed and removed entries will be in the array. * @return Array of String */ String[] getNamesOfModifiedAttributes(); /** * Update the attributes.This will mean that the getters ( - * getStringAttribute methods) will return the updated values, - * and the modifications will be forgotten (i.e. - * {@link AttributeModificationsAware#getModificationItems()} will return an - * empty array. + * getStringAttribute methods) will return the updated values, and the + * modifications will be forgotten (i.e. + * {@link AttributeModificationsAware#getModificationItems()} will return an empty + * array. */ void update(); /** * Set the dn of this entry. - * * @param dn the dn. */ void setDn(Name dn); /* * (non-Javadoc) - * + * * @see javax.naming.Context#getNameInNamespace() */ String getNameInNamespace(); /** - * If this instance results from a referral, this method returns the url of - * the referred server. - * - * @return The url of the referred server, e.g. - * ldap://localhost:389, or the empty string if this is not a - * referral. + * If this instance results from a referral, this method returns the url of the + * referred server. + * @return The url of the referred server, e.g. ldap://localhost:389, or + * the empty string if this is not a referral. * @since 1.3 */ String getReferralUrl(); /** * Checks whether this instance results from a referral. - * * @return true if this instance results from a referral, * false otherwise. * @since 1.3 */ boolean isReferral(); + } diff --git a/core/src/main/java/org/springframework/ldap/core/DirContextProcessor.java b/core/src/main/java/org/springframework/ldap/core/DirContextProcessor.java index dfe6d7f5..f8137108 100644 --- a/core/src/main/java/org/springframework/ldap/core/DirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/core/DirContextProcessor.java @@ -20,32 +20,27 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; /** - * Interface to be called in search by {@link LdapTemplate} before and after the - * actual search and enumeration traversal. Implementations may be used to apply - * search controls on the Context and retrieve the results of - * such controls afterwards. - * + * Interface to be called in search by {@link LdapTemplate} before and after the actual + * search and enumeration traversal. Implementations may be used to apply search controls + * on the Context and retrieve the results of such controls afterwards. + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ public interface DirContextProcessor { + /** * Perform pre-processing on the supplied DirContext. - * - * @param ctx - * the DirContext instance. - * @throws NamingException - * if thrown by the underlying operation. + * @param ctx the DirContext instance. + * @throws NamingException if thrown by the underlying operation. */ void preProcess(DirContext ctx) throws NamingException; /** * Perform post-processing on the supplied DirContext. - * - * @param ctx - * the DirContext instance. - * @throws NamingException - * if thrown by the underlying operation. + * @param ctx the DirContext instance. + * @throws NamingException if thrown by the underlying operation. */ void postProcess(DirContext ctx) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/DirContextProxy.java b/core/src/main/java/org/springframework/ldap/core/DirContextProxy.java index cb58e824..3ff6c6a2 100644 --- a/core/src/main/java/org/springframework/ldap/core/DirContextProxy.java +++ b/core/src/main/java/org/springframework/ldap/core/DirContextProxy.java @@ -18,17 +18,18 @@ package org.springframework.ldap.core; import javax.naming.directory.DirContext; /** - * Helper interface to be able to get hold of the target DirContext - * from proxies created by ContextSource proxies. - * + * Helper interface to be able to get hold of the target DirContext from + * proxies created by ContextSource proxies. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ public interface DirContextProxy { + /** * Get the target DirContext of the proxy. - * * @return the target DirContext. */ DirContext getTargetContext(); + } diff --git a/core/src/main/java/org/springframework/ldap/core/DistinguishedName.java b/core/src/main/java/org/springframework/ldap/core/DistinguishedName.java index 2d174c71..9c52fd35 100644 --- a/core/src/main/java/org/springframework/ldap/core/DistinguishedName.java +++ b/core/src/main/java/org/springframework/ldap/core/DistinguishedName.java @@ -38,18 +38,18 @@ import java.util.List; import java.util.ListIterator; /** - * Default implementation of a {@link Name} corresponding to an LDAP path. A - * Distinguished Name manipulation implementation is included in JDK1.5 - * (LdapName), but not in prior releases. - * - * A DistinguishedName is particularly useful when building or - * modifying an LDAP path dynamically, as escaping will be taken care of. - * - * A path is split into several names. The {@link Name} interface specifies that - * the most significant part be in position 0. + * Default implementation of a {@link Name} corresponding to an LDAP path. A Distinguished + * Name manipulation implementation is included in JDK1.5 (LdapName), but not in prior + * releases. + * + * A DistinguishedName is particularly useful when building or modifying an + * LDAP path dynamically, as escaping will be taken care of. + * + * A path is split into several names. The {@link Name} interface specifies that the most + * significant part be in position 0. *

* Example: - * + * *

*
The path
*
uid=adam.skogman, ou=People, ou=EU
@@ -61,49 +61,46 @@ import java.util.ListIterator; *
uid=adam.skogman
*
*

- * Name instances, and consequently DistinguishedName - * instances are naturally mutable, which is useful when constructing - * DistinguishedNames. Example: - * + * Name instances, and consequently DistinguishedName instances + * are naturally mutable, which is useful when constructing DistinguishedNames. Example: + * *

  * DistinguishedName path = new DistinguishedName("dc=jayway,dc=se");
  * path.add("ou", "People");
  * path.add("uid", "adam.skogman");
  * String dn = path.toString();
  * 
- * + * * will render uid=adam.skogman,ou=People,dc=jayway,dc=se. *

- * NOTE: The fact that DistinguishedName instances are mutable needs to - * be taken into careful account, as this means that they may be modified - * involuntarily. This means that whenever a DistinguishedName - * instance is kept for reference (e.g. for identification of a domain entry) or - * as a constant, you should consider getting an immutable copy of the instance - * using {@link #immutableDistinguishedName()} or + * NOTE: The fact that DistinguishedName instances are mutable needs to be taken + * into careful account, as this means that they may be modified involuntarily. This means + * that whenever a DistinguishedName instance is kept for reference (e.g. for + * identification of a domain entry) or as a constant, you should consider getting an + * immutable copy of the instance using {@link #immutableDistinguishedName()} or * {@link #immutableDistinguishedName(String)}. *

- * NB:As of version 1.3 the default toString representation of - * DistinguishedName now defaults to a compact one, without spaces between the - * respective RDNs. For backward compatibility, set the - * {@link #SPACED_DN_FORMAT_PROPERTY} ({@value #SPACED_DN_FORMAT_PROPERTY}) to - * true. + * NB:As of version 1.3 the default toString representation of DistinguishedName + * now defaults to a compact one, without spaces between the respective RDNs. For backward + * compatibility, set the {@link #SPACED_DN_FORMAT_PROPERTY} + * ({@value #SPACED_DN_FORMAT_PROPERTY}) to true. + * * @author Adam Skogman * @author Mattias Hellborg Arthursson - * - * @deprecated As of 2.0 it is recommended to use {@link javax.naming.ldap.LdapName} along with - * utility methods in {@link LdapUtils} instead. + * @deprecated As of 2.0 it is recommended to use {@link javax.naming.ldap.LdapName} along + * with utility methods in {@link LdapUtils} instead. * @see javax.naming.ldap.LdapName * @see LdapUtils#newLdapName(javax.naming.Name) * @see LdapUtils#newLdapName(String) * @see org.springframework.ldap.support.LdapUtils#emptyLdapName() */ public class DistinguishedName implements Name { + /** - * System property that will be inspected to determine whether - * {@link #toString()} will format the DN with spaces after each comma or - * use a more compact representation, i.e.: - * uid=adam.skogman, ou=People, dc=jayway, dc=se rather than - * uid=adam.skogman,ou=People,dc=jayway,dc=se. A value other + * System property that will be inspected to determine whether {@link #toString()} + * will format the DN with spaces after each comma or use a more compact + * representation, i.e.: uid=adam.skogman, ou=People, dc=jayway, dc=se + * rather than uid=adam.skogman,ou=People,dc=jayway,dc=se. A value other * than null or blank will trigger the spaced format. Default is the compact * representation. *

@@ -119,10 +116,9 @@ public class DistinguishedName implements Name { /** * System property that will be inspected to determine whether creating a - * DistinguishedName will convert the keys to lowercase, convert - * the keys to uppercase, or leave the keys as they were in the - * original String, ie none. Default is to convert the keys to - * lowercase. + * DistinguishedName will convert the keys to lowercase, convert the keys to + * uppercase, or leave the keys as they were in the original String, ie + * none. Default is to convert the keys to lowercase. *

* Valid values are: *

    @@ -144,6 +140,7 @@ public class DistinguishedName implements Name { public static final String KEY_CASE_FOLD_NONE = "none"; private static final String MANGLED_DOUBLE_QUOTES = "\\\\\""; + private static final String PROPER_DOUBLE_QUOTES = "\\\""; private static final Logger LOG = LoggerFactory.getLogger(DistinguishedName.class); @@ -158,6 +155,7 @@ public class DistinguishedName implements Name { * An empty, unmodifiable DistinguishedName. */ public static final DistinguishedName EMPTY_PATH = new DistinguishedName(Collections.EMPTY_LIST); + private static final int DEFAULT_BUFFER_SIZE = 256; private List names; @@ -171,7 +169,6 @@ public class DistinguishedName implements Name { /** * Construct a new DistinguishedName from a String. - * * @param path a String corresponding to a (syntactically) valid LDAP path. */ public DistinguishedName(String path) { @@ -184,9 +181,8 @@ public class DistinguishedName implements Name { } /** - * Construct a new DistinguishedName from the supplied - * List of {@link LdapRdn} objects. - * + * Construct a new DistinguishedName from the supplied List + * of {@link LdapRdn} objects. * @param list the components that this instance will consist of. */ public DistinguishedName(List list) { @@ -194,12 +190,10 @@ public class DistinguishedName implements Name { } /** - * Construct a new DistinguishedName from the supplied - * {@link Name}. The parts of the supplied {@link Name} must be - * syntactically correct {@link LdapRdn}s. - * - * @param name the {@link Name} to construct a new - * DistinguishedName from. + * Construct a new DistinguishedName from the supplied {@link Name}. The + * parts of the supplied {@link Name} must be syntactically correct {@link LdapRdn}s. + * @param name the {@link Name} to construct a new DistinguishedName + * from. */ public DistinguishedName(Name name) { Assert.notNull(name, "name cannot be null"); @@ -214,9 +208,8 @@ public class DistinguishedName implements Name { } /** - * Parse the supplied String and make this instance represent the - * corresponding distinguished name. - * + * Parse the supplied String and make this instance represent the corresponding + * distinguished name. * @param path the LDAP path to parse. */ protected final void parse(String path) { @@ -235,11 +228,9 @@ public class DistinguishedName implements Name { } /** - * If path is surrounded by quotes, strip them. JNDI considers forward slash - * ('/') special, but LDAP doesn't. {@link CompositeName#toString()} tends - * to mangle a {@link Name} with a slash by surrounding it with quotes - * ('"'). - * + * If path is surrounded by quotes, strip them. JNDI considers forward slash ('/') + * special, but LDAP doesn't. {@link CompositeName#toString()} tends to mangle a + * {@link Name} with a slash by surrounding it with quotes ('"'). * @param path Path to check and possibly strip. * @return A String with the possibly stripped path. */ @@ -259,7 +250,6 @@ public class DistinguishedName implements Name { /** * Get the {@link LdapRdn} at a specified position. - * * @param index the {@link LdapRdn} to retrieve. * @return the {@link LdapRdn} at the requested position. */ @@ -268,10 +258,8 @@ public class DistinguishedName implements Name { } /** - * Get the {@link LdapRdn} with the specified key. If there are several - * {@link Rdn}s with the same key, the first one found (in order of - * significance) will be returned. - * + * Get the {@link LdapRdn} with the specified key. If there are several {@link Rdn}s + * with the same key, the first one found (in order of significance) will be returned. * @param key Attribute name of the {@link LdapRdn} to retrieve. * @return the {@link LdapRdn} with the requested key. * @throws IllegalArgumentException if no Rdn matches the given key. @@ -288,10 +276,9 @@ public class DistinguishedName implements Name { } /** - * Get the value of the {@link LdapRdnComponent} with the specified key - * (Attribute value). If there are several Rdns with the same key, the value - * of the first one found (in order of significance) will be returned. - * + * Get the value of the {@link LdapRdnComponent} with the specified key (Attribute + * value). If there are several Rdns with the same key, the value of the first one + * found (in order of significance) will be returned. * @param key Attribute name of the {@link LdapRdn} to retrieve. * @return the value. * @throws IllegalArgumentException if no Rdn matches the given key. @@ -302,23 +289,20 @@ public class DistinguishedName implements Name { /** * Get the name List. - * - * @return the list of {@link LdapRdn}s that this - * DistinguishedName consists of. + * @return the list of {@link LdapRdn}s that this DistinguishedName + * consists of. */ public List getNames() { return names; } /** - * Get the String representation of this DistinguishedName. - * Depending on the setting of property - * org.springframework.ldap.core.spacedDnFormat a space will be - * added after each comma, to make the result more readable. Default is + * Get the String representation of this DistinguishedName. Depending on + * the setting of property org.springframework.ldap.core.spacedDnFormat a + * space will be added after each comma, to make the result more readable. Default is * compact representation, i.e. without any spaces. - * - * @return a syntactically correct, properly escaped String representation - * of the DistinguishedName. + * @return a syntactically correct, properly escaped String representation of the + * DistinguishedName. * @see #SPACED_DN_FORMAT_PROPERTY */ public String toString() { @@ -332,12 +316,10 @@ public class DistinguishedName implements Name { } /** - * Get the compact String representation of this - * DistinguishedName. Add no space after each comma, to make it - * compact. - * - * @return a syntactically correct, properly escaped String representation - * of the DistinguishedName. + * Get the compact String representation of this DistinguishedName. Add + * no space after each comma, to make it compact. + * @return a syntactically correct, properly escaped String representation of the + * DistinguishedName. */ public String toCompactString() { return format(COMPACT); @@ -345,9 +327,8 @@ public class DistinguishedName implements Name { /** * Builds a complete LDAP path, ldap encoded, useful as a DN. - * + * * Always uses lowercase, always separates with ", " i.e. comma and a space. - * * @return the LDAP path. */ public String encode() { @@ -383,9 +364,7 @@ public class DistinguishedName implements Name { } /** - * Builds a complete LDAP path, ldap and url encoded. Separates only with - * ",". - * + * Builds a complete LDAP path, ldap and url encoded. Separates only with ",". * @return the LDAP path, for use in an url. */ public String toUrl() { @@ -402,12 +381,10 @@ public class DistinguishedName implements Name { } /** - * Determines if this DistinguishedName path contains another - * path. - * + * Determines if this DistinguishedName path contains another path. * @param path the path to check. - * @return true if the supplied path is conained in this - * instance, false otherwise. + * @return true if the supplied path is conained in this instance, + * false otherwise. */ public boolean contains(DistinguishedName path) { @@ -455,15 +432,14 @@ public class DistinguishedName implements Name { /** * Add an LDAP path last in this DistinguishedName. E.g.: - * + * *
     	 * DistinguishedName name1 = new DistinguishedName("c=SE, dc=jayway, dc=se");
     	 * DistinguishedName name2 = new DistinguishedName("ou=people");
     	 * name1.append(name2);
     	 * 
    - * + * * will result in ou=people, c=SE, dc=jayway, dc=se - * * @param path the path to append. * @return this instance. */ @@ -474,7 +450,6 @@ public class DistinguishedName implements Name { /** * Append a new {@link LdapRdn} using the supplied key and value. - * * @param key the key of the {@link LdapRdn}. * @param value the value of the {@link LdapRdn}. * @return this instance. @@ -486,15 +461,14 @@ public class DistinguishedName implements Name { /** * Add an LDAP path first in this DistinguishedName. E.g.: - * + * *
     	 * DistinguishedName name1 = new DistinguishedName("ou=people");
     	 * DistinguishedName name2 = new DistinguishedName("c=SE, dc=jayway, dc=se");
     	 * name1.prepend(name2);
     	 * 
    - * + * * will result in ou=people, c=SE, dc=jayway, dc=se - * * @param path the path to prepend. */ public void prepend(DistinguishedName path) { @@ -506,7 +480,6 @@ public class DistinguishedName implements Name { /** * Remove the first part of this DistinguishedName. - * * @return the removed entry. */ public LdapRdn removeFirst() { @@ -514,11 +487,9 @@ public class DistinguishedName implements Name { } /** - * Remove the supplied path from the beginning of this - * DistinguishedName if this instance starts with - * path. Useful for stripping base path suffix from a - * DistinguishedName. - * + * Remove the supplied path from the beginning of this DistinguishedName + * if this instance starts with path. Useful for stripping base path + * suffix from a DistinguishedName. * @param path the path to remove from the beginning of this instance. */ public void removeFirst(Name path) { @@ -568,10 +539,10 @@ public class DistinguishedName implements Name { } /** - * Compare this instance to another object. Note that the comparison is done - * in order of significance, so the most significant Rdn is compared first, - * then the second and so on. - * + * Compare this instance to another object. Note that the comparison is done in order + * of significance, so the most significant Rdn is compared first, then the second and + * so on. + * * @see javax.naming.Name#compareTo(java.lang.Object) */ public int compareTo(Object obj) { @@ -590,7 +561,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#getAll() */ public Enumeration getAll() { @@ -605,7 +576,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#get(int) */ public String get(int index) { @@ -615,7 +586,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#getPrefix(int) */ public Name getPrefix(int index) { @@ -629,7 +600,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#getSuffix(int) */ public Name getSuffix(int index) { @@ -647,7 +618,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#startsWith(javax.naming.Name) */ public boolean startsWith(Name name) { @@ -684,14 +655,12 @@ public class DistinguishedName implements Name { } /** - * Determines if this DistinguishedName ends with a certian - * path. - * + * Determines if this DistinguishedName ends with a certian path. + * * If the argument path is empty (no names in path) this method will return * false. - * * @param name The suffix to check for. - * + * */ public boolean endsWith(Name name) { DistinguishedName path = null; @@ -732,7 +701,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#addAll(javax.naming.Name) */ public Name addAll(Name name) throws InvalidNameException { @@ -741,7 +710,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#addAll(int, javax.naming.Name) */ public Name addAll(int arg0, Name name) throws InvalidNameException { @@ -759,7 +728,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#add(java.lang.String) */ public Name add(String string) throws InvalidNameException { @@ -768,7 +737,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#add(int, java.lang.String) */ public Name add(int index, String string) throws InvalidNameException { @@ -783,7 +752,7 @@ public class DistinguishedName implements Name { /* * (non-Javadoc) - * + * * @see javax.naming.Name#remove(int) */ public Object remove(int arg0) throws InvalidNameException { @@ -793,7 +762,6 @@ public class DistinguishedName implements Name { /** * Remove the last part of this DistinguishedName. - * * @return the removed {@link LdapRdn}. */ public LdapRdn removeLast() { @@ -802,7 +770,6 @@ public class DistinguishedName implements Name { /** * Add a new {@link LdapRdn} using the supplied key and value. - * * @param key the key of the {@link LdapRdn}. * @param value the value of the {@link LdapRdn}. */ @@ -812,7 +779,6 @@ public class DistinguishedName implements Name { /** * Add the supplied {@link LdapRdn} last in the list of Rdns. - * * @param rdn the {@link LdapRdn} to add. */ public void add(LdapRdn rdn) { @@ -821,7 +787,6 @@ public class DistinguishedName implements Name { /** * Add the supplied {@link LdapRdn} att the specified index. - * * @param idx the index at which to add the LdapRdn. * @param rdn the LdapRdn to add. */ @@ -830,10 +795,9 @@ public class DistinguishedName implements Name { } /** - * Return an immutable copy of this instance. It will not be possible to add - * or remove any Rdns to or from the returned instance, and the respective - * Rdns will also be immutable in turn. - * + * Return an immutable copy of this instance. It will not be possible to add or remove + * any Rdns to or from the returned instance, and the respective Rdns will also be + * immutable in turn. * @return a copy of this instance backed by an immutable list. * @since 1.2 */ @@ -849,13 +813,12 @@ public class DistinguishedName implements Name { /** * Create an immutable DistinguishedName instance, suitable as a constant. - * * @param dnString the DN string to parse. - * @return an immutable DistinguishedName corresponding to the supplied DN - * string. + * @return an immutable DistinguishedName corresponding to the supplied DN string. * @since 1.3 */ public static final DistinguishedName immutableDistinguishedName(String dnString) { return new DistinguishedName(dnString).immutableDistinguishedName(); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/DistinguishedNameEditor.java b/core/src/main/java/org/springframework/ldap/core/DistinguishedNameEditor.java index 0188408f..eff4f133 100644 --- a/core/src/main/java/org/springframework/ldap/core/DistinguishedNameEditor.java +++ b/core/src/main/java/org/springframework/ldap/core/DistinguishedNameEditor.java @@ -19,9 +19,9 @@ import java.beans.PropertyEditorSupport; /** * Property editor for use with {@link DistinguishedName} instances. The - * {@link #setAsText(String)} method sets the value as an immutable - * instance of a DistinguishedName. - * + * {@link #setAsText(String)} method sets the value as an immutable instance of a + * DistinguishedName. + * * @author Mattias Hellborg Arthursson * @since 1.2 * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. @@ -30,6 +30,7 @@ public class DistinguishedNameEditor extends PropertyEditorSupport { /* * (non-Javadoc) + * * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String) */ public void setAsText(String text) throws IllegalArgumentException { @@ -43,6 +44,7 @@ public class DistinguishedNameEditor extends PropertyEditorSupport { /* * (non-Javadoc) + * * @see java.beans.PropertyEditorSupport#getAsText() */ public String getAsText() { diff --git a/core/src/main/java/org/springframework/ldap/core/DnParser.java b/core/src/main/java/org/springframework/ldap/core/DnParser.java index 646a20e3..cfa2a88c 100644 --- a/core/src/main/java/org/springframework/ldap/core/DnParser.java +++ b/core/src/main/java/org/springframework/ldap/core/DnParser.java @@ -17,23 +17,22 @@ package org.springframework.ldap.core; /** * A parser for RFC2253-compliant Distinguished Names. - * + * * @author Mattias Hellborg Arthursson * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. */ public interface DnParser { + /** * Parse a full Distinguished Name. - * - * @return the DistinguishedName corresponding to the parsed - * stream. + * @return the DistinguishedName corresponding to the parsed stream. */ public DistinguishedName dn() throws ParseException; /** * Parse a Relative Distinguished Name. - * * @return the next rdn on the stream. */ public LdapRdn rdn() throws ParseException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/IncrementalAttributesMapper.java b/core/src/main/java/org/springframework/ldap/core/IncrementalAttributesMapper.java index 803b0aa7..aafde0d8 100644 --- a/core/src/main/java/org/springframework/ldap/core/IncrementalAttributesMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/IncrementalAttributesMapper.java @@ -21,57 +21,57 @@ import javax.naming.directory.Attributes; import java.util.List; /** - * Utility that helps with reading all attribute values from Active Directory using Incremental Retrieval of - * Multi-valued Properties. + * Utility that helps with reading all attribute values from Active Directory using + * Incremental Retrieval of Multi-valued Properties. * * @author Mattias Hellborg Arthursson * @since 1.3.2 - * @see Incremental Retrieval of Multi-valued Properties + * @see Incremental + * Retrieval of Multi-valued Properties * @see org.springframework.ldap.core.support.DefaultIncrementalAttributesMapper */ public interface IncrementalAttributesMapper extends AttributesMapper { + /** * Get all of the collected values for the specified attribute. - * * @param attributeName the attribute to get values for. * @return the collected values for the specified attribute. Will be null - * if the requested attribute has not been returned by the server (attribute did not exist). + * if the requested attribute has not been returned by the server (attribute did not + * exist). */ List getValues(String attributeName); /** * Get all collected values for all managed attributes as an Attributes instance. - * * @return an Attributes instance populated with all collected values. */ Attributes getCollectedAttributes(); /** - * Check whether another query iteration is required to get all values for all attributes. - * - * @return true if there are more values for at least one of the managed attributes, - * false otherwise. + * Check whether another query iteration is required to get all values for all + * attributes. + * @return true if there are more values for at least one of the managed + * attributes, false otherwise. */ boolean hasMore(); /** - * Get properly formatted attributes for use in the next query. The attribute names included will - * include Range specifiers as needed and only the attributes that have not been retrieved in full - * will be included. - * + * Get properly formatted attributes for use in the next query. The attribute names + * included will include Range specifiers as needed and only the attributes that have + * not been retrieved in full will be included. * @return an array of Strings to be used as input to e.g. - * {@link org.springframework.ldap.core.LdapTemplate#lookup(javax.naming.Name, String[], org.springframework.ldap.core.AttributesMapper)} - * in the next iteration. + * {@link org.springframework.ldap.core.LdapTemplate#lookup(javax.naming.Name, String[], org.springframework.ldap.core.AttributesMapper)} + * in the next iteration. */ String[] getAttributesForLookup(); /** - * Goes through all of the attributes to record their values and figure out whether a new query iteration - * is needed to get more values. - * + * Goes through all of the attributes to record their values and figure out whether a + * new query iteration is needed to get more values. * @param attributes attributes from a SearchResult. * @return this instance. * @throws javax.naming.NamingException */ T mapFromAttributes(Attributes attributes) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/IterableNamingEnumeration.java b/core/src/main/java/org/springframework/ldap/core/IterableNamingEnumeration.java index 0fc595df..6c498084 100644 --- a/core/src/main/java/org/springframework/ldap/core/IterableNamingEnumeration.java +++ b/core/src/main/java/org/springframework/ldap/core/IterableNamingEnumeration.java @@ -5,9 +5,10 @@ import javax.naming.NamingException; import java.util.Iterator; /** -* @author Mattias Hellborg Arthursson -*/ + * @author Mattias Hellborg Arthursson + */ final class IterableNamingEnumeration implements NamingEnumeration { + private final Iterator iterator; IterableNamingEnumeration(Iterable iterable) { @@ -37,4 +38,5 @@ final class IterableNamingEnumeration implements NamingEnumeration { public T nextElement() { return next(); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/LdapAttribute.java b/core/src/main/java/org/springframework/ldap/core/LdapAttribute.java index 037f5272..4bf5952b 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapAttribute.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapAttribute.java @@ -21,29 +21,28 @@ import java.util.HashSet; import java.util.Set; /** - * Extends {@link javax.naming.directory.BasicAttribute} to add support for - * options as defined in RFC2849. + * Extends {@link javax.naming.directory.BasicAttribute} to add support for options as + * defined in RFC2849. *

    - * While uncommon, options can be used to specify additional descriptors for - * the attribute. Options are backed by a {@link java.util.HashSet} of + * While uncommon, options can be used to specify additional descriptors for the + * attribute. Options are backed by a {@link java.util.HashSet} of * {@link java.lang.String}. - * + * * @author Keith Barlow * */ public class LdapAttribute extends BasicAttribute { private static final long serialVersionUID = -5263905906016179429L; - + /** * Holds the attributes options. */ protected Set options = new HashSet(); - + /** * Creates an unordered attribute with the specified ID. - * - * @param id {@link java.lang.String} ID of the attribute. + * @param id {@link java.lang.String} ID of the attribute. */ public LdapAttribute(String id) { super(id); @@ -51,8 +50,7 @@ public class LdapAttribute extends BasicAttribute { /** * Creates an unordered attribute with the specified ID and value. - * - * @param id {@link java.lang.String} ID of the attribute. + * @param id {@link java.lang.String} ID of the attribute. * @param value Attribute value. */ public LdapAttribute(String id, Object value) { @@ -61,10 +59,10 @@ public class LdapAttribute extends BasicAttribute { /** * Creates an unordered attribute with the specified ID, value, and options. - * - * @param id {@link java.lang.String} ID of the attribute. + * @param id {@link java.lang.String} ID of the attribute. * @param value Attribute value. - * @param options {@link java.util.Collection} of {@link java.lang.String} attribute options. + * @param options {@link java.util.Collection} of {@link java.lang.String} attribute + * options. */ public LdapAttribute(String id, Object value, Collection options) { super(id, value); @@ -73,8 +71,7 @@ public class LdapAttribute extends BasicAttribute { /** * Creates an attribute with the specified ID whose values may be ordered. - * - * @param id {@link java.lang.String} ID of the attribute. + * @param id {@link java.lang.String} ID of the attribute. * @param ordered boolean indicating whether or not the attributes values are ordered. */ public LdapAttribute(String id, boolean ordered) { @@ -83,9 +80,9 @@ public class LdapAttribute extends BasicAttribute { /** * Creates an attribute with the specified ID and options whose values may be ordered. - * - * @param id {@link java.lang.String} ID of the attribute. - * @param options {@link java.util.Collection} of {@link java.lang.String} attribute options. + * @param id {@link java.lang.String} ID of the attribute. + * @param options {@link java.util.Collection} of {@link java.lang.String} attribute + * options. * @param ordered boolean indicating whether or not the attributes values are ordered. */ public LdapAttribute(String id, Collection options, boolean ordered) { @@ -95,8 +92,7 @@ public class LdapAttribute extends BasicAttribute { /** * Creates an attribute with the specified ID and value whose values may be ordered. - * - * @param id {@link java.lang.String} ID of the attribute. + * @param id {@link java.lang.String} ID of the attribute. * @param value Attribute value. * @param ordered boolean indicating whether or not the attributes values are ordered. */ @@ -105,11 +101,12 @@ public class LdapAttribute extends BasicAttribute { } /** - * Creates an attribute with the specified ID, value, and options whose values may be ordered. - * + * Creates an attribute with the specified ID, value, and options whose values may be + * ordered. * @param id {@link java.lang.String} ID of the attribute. * @param value Attribute value. - * @param options {@link java.util.Collection} of {@link java.lang.String} attribute options. + * @param options {@link java.util.Collection} of {@link java.lang.String} attribute + * options. * @param ordered boolean indicating whether or not the attributes values are ordered. */ public LdapAttribute(String id, Object value, Collection options, boolean ordered) { @@ -119,106 +116,96 @@ public class LdapAttribute extends BasicAttribute { /** * Get options. - * * @return returns a {@link java.util.Set} of {@link java.lang.String} */ public Set getOptions() { return this.options; } - + /** * Set options. - * * @param options {@link java.util.Set} of {@link java.lang.String} */ public void setOptions(Set options) { this.options = options; } - + /** * Add an option. - * * @param option {@link java.lang.String} option. * @return boolean indication successful addition of option. */ public boolean addOption(String option) { return this.options.add(option); } - + /** * Add all values in the collection to the options. - * * @param options {@link java.util.Collection} of {@link java.lang.String} values. * @return boolean indication successful addition of options. */ public boolean addAllOptions(Collection options) { return this.options.addAll(options); } - + /** * Clears all stored options. */ public void clearOptions() { this.options.clear(); } - + /** * Checks for existence of a particular option on the set. - * * @param option {@link java.lang.String} option. * @return boolean indicating result. */ public boolean contains(String option) { return this.options.contains(option); } - + /** * Checks for existence of a series of options on the set. - * * @param options {@link java.util.Collection} of {@link java.lang.String} options. * @return boolean indicating result. */ public boolean containsAll(Collection options) { return this.options.containsAll(options); } - + /** * Tests for the presence of options. - * * @return boolean indicating result. */ public boolean hasOptions() { return !options.isEmpty(); } - + /** * Removes an option from the the set. - * * @param option {@link java.lang.String} option. * @return boolean indicating successful removal of option. */ public boolean removeOption(String option) { return this.options.remove(option); } - + /** * Removes all options listed in the supplied set. - * * @param options {@link java.util.Collection} of {@link java.lang.String} options. * @return boolean indicating successful removal of options. */ public boolean removeAllOptions(Collection options) { return this.options.removeAll(options); } - + /** * Removes any options not on the set of supplied options. - * * @param options {@link java.util.Collection} of {@link java.lang.String} options. * @return boolean indicating successful retention of options. */ public boolean retainAllOptions(Collection options) { return this.options.retainAll(options); } - + } diff --git a/core/src/main/java/org/springframework/ldap/core/LdapAttributes.java b/core/src/main/java/org/springframework/ldap/core/LdapAttributes.java index 5d2e86a6..04f0cd20 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapAttributes.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapAttributes.java @@ -30,45 +30,58 @@ import javax.naming.ldap.LdapName; import java.net.URI; /** - * Extends {@link javax.naming.directory.BasicAttributes} to add specialized support - * for DNs. + * Extends {@link javax.naming.directory.BasicAttributes} to add specialized support for + * DNs. *

    - * While DNs appear to be and can be treated as attributes, they have a special - * meaning in that they define the address to which the object is bound. DNs must - * conform to special formatting rules and are typically required to be handled - * separately from other attributes. + * While DNs appear to be and can be treated as attributes, they have a special meaning in + * that they define the address to which the object is bound. DNs must conform to special + * formatting rules and are typically required to be handled separately from other + * attributes. *

    - * This class makes this distinction between the DN and other - * attributes prominent and apparent. - * + * This class makes this distinction between the DN and other attributes prominent and + * apparent. + * * @author Keith Barlow * */ public class LdapAttributes extends BasicAttributes { private static final long serialVersionUID = 97903297123869138L; - + private static Logger log = LoggerFactory.getLogger(LdapAttributes.class); - private static final String SAFE_CHAR = "[\\p{ASCII}&&[^\\x00\\x0A\\x0D]]"; //Any ASCII except NUL, LF, and CR - - private static final String SAFE_INIT_CHAR = "[\\p{ASCII}&&[^ \\x00\\x0A\\x0D\\x3A\\x3C]]"; //Any ASCII except NUL, LF, CR, SPACE, colon, and less-than - + private static final String SAFE_CHAR = "[\\p{ASCII}&&[^\\x00\\x0A\\x0D]]"; // Any + // ASCII + // except + // NUL, + // LF, and + // CR + + private static final String SAFE_INIT_CHAR = "[\\p{ASCII}&&[^ \\x00\\x0A\\x0D\\x3A\\x3C]]"; // Any + // ASCII + // except + // NUL, + // LF, + // CR, + // SPACE, + // colon, + // and + // less-than + /** * Distinguished name to which the object is bound. */ protected LdapName dn = LdapUtils.emptyLdapName(); - + /** * Default constructor. */ public LdapAttributes() { - + } /** * Constructor for specifying whether or not the object is case sensitive. - * * @param ignoreCase boolean indicator. */ public LdapAttributes(boolean ignoreCase) { @@ -77,10 +90,10 @@ public class LdapAttributes extends BasicAttributes { /** * Returns the distinguished name to which the object is bound. - * - * @return {@link org.springframework.ldap.core.DistinguishedName} specifying the name to which the object is bound. - * @deprecated {@link DistinguishedName and associated classes and methods are deprecated as of 2.0}. - * use {@link #getName()} instead. + * @return {@link org.springframework.ldap.core.DistinguishedName} specifying the name + * to which the object is bound. + * @deprecated {@link DistinguishedName and associated classes and methods are + * deprecated as of 2.0}. use {@link #getName()} instead. */ public DistinguishedName getDN() { return new DistinguishedName(dn); @@ -88,7 +101,6 @@ public class LdapAttributes extends BasicAttributes { /** * Returns the distinguished name to which the object is bound. - * * @return {@link LdapName} specifying the name to which the object is bound. */ public LdapName getName() { @@ -97,10 +109,10 @@ public class LdapAttributes extends BasicAttributes { /** * Sets the distinguished name of the object. - * - * @param dn {@link org.springframework.ldap.core.DistinguishedName} specifying the name to which the object is bound. - * @deprecated {@link DistinguishedName and associated classes and methods are deprecated as of 2.0}. - * use {@link #setName(javax.naming.Name)} instead. + * @param dn {@link org.springframework.ldap.core.DistinguishedName} specifying the + * name to which the object is bound. + * @deprecated {@link DistinguishedName and associated classes and methods are + * deprecated as of 2.0}. use {@link #setName(javax.naming.Name)} instead. */ public void setDN(DistinguishedName dn) { this.dn = LdapUtils.newLdapName(dn); @@ -109,54 +121,59 @@ public class LdapAttributes extends BasicAttributes { public void setName(Name name) { this.dn = LdapUtils.newLdapName(name); } - + /** * Returns a string representation of the object in LDIF format. - * * @return {@link java.lang.String} formated to RFC2849 LDIF specifications. */ public String toString() { - StringBuilder sb = new StringBuilder(); - + StringBuilder sb = new StringBuilder(); + try { - + LdapName dn = getName(); - + if (!dn.toString().matches(SAFE_INIT_CHAR + SAFE_CHAR + "*")) { sb.append("dn:: " + LdapEncoder.printBase64Binary(dn.toString().getBytes()) + "\n"); - } else { + } + else { sb.append("dn: " + getDN() + "\n"); } - + NamingEnumeration attributes = getAll(); - + while (attributes.hasMore()) { Attribute attribute = attributes.next(); NamingEnumeration values = attribute.getAll(); - + while (values.hasMore()) { Object value = values.next(); - + if (value instanceof String) { sb.append(attribute.getID() + ": " + (String) value + "\n"); - - } else if (value instanceof byte[]) { + + } + else if (value instanceof byte[]) { sb.append(attribute.getID() + ":: " + LdapEncoder.printBase64Binary((byte[]) value) + "\n"); - } else if (value instanceof URI) { + } + else if (value instanceof URI) { sb.append(attribute.getID() + ":< " + (URI) value + "\n"); - - } else { + + } + else { sb.append(attribute.getID() + ": " + value + "\n"); } } } - - } catch (NamingException e) { + + } + catch (NamingException e) { log.error("Error formating attributes for output.", e); sb = new StringBuilder(); } - + return sb.toString(); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/LdapClient.java b/core/src/main/java/org/springframework/ldap/core/LdapClient.java index 887e40d4..1f977cb9 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapClient.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapClient.java @@ -43,38 +43,30 @@ import org.springframework.ldap.query.LdapQueryBuilder; public interface LdapClient { /** - * Start building a request for all children of the - * given {@code name}. - * + * Start building a request for all children of the given {@code name}. * @param name the distinguished name to find children for * @return a spec for specifying the list parameters */ ListSpec list(String name); /** - * Start building a request for all children of the - * given {@code name}. - * + * Start building a request for all children of the given {@code name}. * @param name the distinguished name to find children for * @return a spec for specifying the list parameters */ ListSpec list(Name name); /** - * Start building a request for all children of the - * given {@code name}. The result will include the object bound to - * the name. - * + * Start building a request for all children of the given {@code name}. The result + * will include the object bound to the name. * @param name the distinguished name to find children for * @return a spec for specifying the list parameters */ ListBindingsSpec listBindings(String name); /** - * Start building a request for all children of the - * given {@code name}. The result will include the object bound to - * the name. - * + * Start building a request for all children of the given {@code name}. The result + * will include the object bound to the name. * @param name the distinguished name to find children for * @return a spec for specifying the list parameters */ @@ -82,67 +74,62 @@ public interface LdapClient { /** * Start building a search request. - * * @return a spec for specifying the search parameters */ SearchSpec search(); /** * Start building an authentication request. - * * @return a spec for specifying the authentication parameters */ AuthenticateSpec authenticate(); /** - * Start building a bind request, using the given {@code name} - * as the identifier. - * + * Start building a bind request, using the given {@code name} as the identifier. * @return a spec for specifying the bind parameters */ BindSpec bind(String name); /** - * Start building a bind or rebind request, using the given {@code name} - * as the identifier. - * + * Start building a bind or rebind request, using the given {@code name} as the + * identifier. * @return a spec for specifying the bind parameters */ BindSpec bind(Name name); /** - * Start building a request to modify name or attributes of an entry, using the given {@code name} - * as the identifier. + * Start building a request to modify name or attributes of an entry, using the given + * {@code name} as the identifier. * *

    - * Note that a {@link #modify(Name)} is different from a rebind in that - * entries are changed instead of removed and recreated. + * Note that a {@link #modify(Name)} is different from a rebind in that entries are + * changed instead of removed and recreated. * *

    - * A change in name uses LDAP's {@link DirContext#rename} function. - * A change in attributes uses LDAP's {@link DirContext#modifyAttributes} function. - * The {@code rename} action is optimistically performed before the {@code modify} function. - * A rollback of the name is attempted in the event that attribute modification fails. - * + * A change in name uses LDAP's {@link DirContext#rename} function. A change in + * attributes uses LDAP's {@link DirContext#modifyAttributes} function. The + * {@code rename} action is optimistically performed before the {@code modify} + * function. A rollback of the name is attempted in the event that attribute + * modification fails. * @param name the name of the entry to modify * @return a spec for specifying the modify parameters */ ModifySpec modify(String name); /** - * Start building a request to modify name or attributes of an entry, using the given {@code name} - * as the identifier. + * Start building a request to modify name or attributes of an entry, using the given + * {@code name} as the identifier. * *

    - * Note that a {@link #modify(Name)} is different from a rebind in that - * entries are changed instead of removed and recreated. + * Note that a {@link #modify(Name)} is different from a rebind in that entries are + * changed instead of removed and recreated. * *

    - * A change in name uses LDAP's {@link DirContext#rename} function. - * A change in attributes uses LDAP's {@link DirContext#modifyAttributes} function. - * The {@code rename} action is optimistically performed before the {@code modify} function. - * A rollback of the name is attempted in the event that attribute modification fails. - * + * A change in name uses LDAP's {@link DirContext#rename} function. A change in + * attributes uses LDAP's {@link DirContext#modifyAttributes} function. The + * {@code rename} action is optimistically performed before the {@code modify} + * function. A rollback of the name is attempted in the event that attribute + * modification fails. * @param name the name of the entry to modify * @return a spec for specifying the modify parameters */ @@ -150,7 +137,6 @@ public interface LdapClient { /** * Start building a request to remove the {@code name} entry. - * * @param name the name of the entry to remove * @return a spec for specifying the unbind parameters */ @@ -158,19 +144,17 @@ public interface LdapClient { /** * Start building a request to remove the {@code name} entry. - * * @param name the name of the entry to remove * @return a spec for specifying the unbind parameters */ UnbindSpec unbind(Name name); /** - * Return a builder to create a new {@code LdapClient} whose settings are - * replicated from the current {@code LdapClient}. + * Return a builder to create a new {@code LdapClient} whose settings are replicated + * from the current {@code LdapClient}. */ Builder mutate(); - // Static, factory methods /** @@ -189,7 +173,6 @@ public interface LdapClient { return new DefaultLdapClientBuilder(); } - /** * A mutable builder for creating an {@link LdapClient}. */ @@ -202,8 +185,8 @@ public interface LdapClient { Builder contextSource(ContextSource contextSource); /** - * Use this {@link Supplier} to generate a {@link SearchControls}. - * It should generate a new {@link SearchControls} on each call. + * Use this {@link Supplier} to generate a {@link SearchControls}. It should + * generate a new {@link SearchControls} on each call. * @param searchControlsSupplier the {@link Supplier} to use * @return the {@link Builder} for further customizations */ @@ -212,7 +195,6 @@ public interface LdapClient { /** * Whether to ignore the {@link org.springframework.ldap.PartialResultException}. * Defaults to {@code true}. - * * @param ignore whether to ignore the {@link PartialResultException} * @return the {@link LdapClient.Builder} for further customizations */ @@ -221,16 +203,15 @@ public interface LdapClient { /** * Whether to ignore the {@link org.springframework.ldap.NameNotFoundException}. * Defaults to {@code true}. - * * @param ignore whether to ignore the {@link NameNotFoundException} * @return the {@link LdapClient.Builder} for further customizations */ Builder ignoreNameNotFoundException(boolean ignore); /** - * Whether to ignore the {@link org.springframework.ldap.SizeLimitExceededException}. - * Defaults to {@code true}. - * + * Whether to ignore the + * {@link org.springframework.ldap.SizeLimitExceededException}. Defaults to + * {@code true}. * @param ignore whether to ignore the {@link SizeLimitExceededException} * @return the {@link LdapClient.Builder} for further customizations */ @@ -238,7 +219,8 @@ public interface LdapClient { /** * Apply the given {@code Consumer} to this builder instance. - *

    This can be useful for applying pre-packaged customizations. + *

    + * This can be useful for applying pre-packaged customizations. * @param builderConsumer the consumer to apply */ Builder apply(Consumer builderConsumer); @@ -252,97 +234,100 @@ public interface LdapClient { * Build the {@link LdapClient} instance. */ LdapClient build(); + } /** * The specifications for the {@link #list} request. */ interface ListSpec { + /** * Return the entry's children as a list of mapped results - * - * @param mapper the {@link NameClassPairMapper} strategy to mapping each search result + * @param mapper the {@link NameClassPairMapper} strategy to mapping each search + * result * @return the entry's children or an empty list */ List toList(NameClassPairMapper mapper); /** - * Return the entry's children as a stream of mapped results. Note that - * the {@link Stream} must be closed when done reading from it. - * - * @param mapper the {@link NameClassPairMapper} strategy to mapping each search result + * Return the entry's children as a stream of mapped results. Note that the + * {@link Stream} must be closed when done reading from it. + * @param mapper the {@link NameClassPairMapper} strategy to mapping each search + * result * @return the entry's children or an empty stream */ Stream toStream(NameClassPairMapper mapper); + } /** * The specifications for the {@link #listBindings} request. */ interface ListBindingsSpec { + /** * Return the entry's children as a list of mapped results - * - * @param mapper the {@link NameClassPairMapper} strategy to mapping each search result + * @param mapper the {@link NameClassPairMapper} strategy to mapping each search + * result * @return the entry's children or an empty list */ List toList(NameClassPairMapper mapper); /** * Return the entry's children as a list of mapped results - * * @param mapper the {@link ContextMapper} strategy to mapping each search result * @return the entry's children or an empty list */ List toList(ContextMapper mapper); /** - * Return the entry's children as a stream of mapped results. Note that - * the {@link Stream} must be closed when done reading from it. - * - * @param mapper the {@link NameClassPairMapper} strategy to mapping each search result + * Return the entry's children as a stream of mapped results. Note that the + * {@link Stream} must be closed when done reading from it. + * @param mapper the {@link NameClassPairMapper} strategy to mapping each search + * result * @return the entry's children or an empty stream */ Stream toStream(NameClassPairMapper mapper); /** - * Return the entry's children as a stream of mapped results. Note that - * the {@link Stream} must be closed when done reading from it. - * + * Return the entry's children as a stream of mapped results. Note that the + * {@link Stream} must be closed when done reading from it. * @param mapper the {@link ContextMapper} strategy to mapping each search result * @return the entry's children or an empty stream */ Stream toStream(ContextMapper mapper); + } /** * The specifications for the {@link #search} request. */ interface SearchSpec { + /** - * The name to search for. This is a convenience method for - * creating an {@link LdapQuery} based only on the {@code name}. - * + * The name to search for. This is a convenience method for creating an + * {@link LdapQuery} based only on the {@code name}. * @param name the name to search for * @return the {@link SearchSpec} for further configuration */ SearchSpec name(String name); /** - * The name to search for. This is a convenience method for - * creating an {@link LdapQuery} based only on the {@code name}. - * + * The name to search for. This is a convenience method for creating an + * {@link LdapQuery} based only on the {@code name}. * @param name the name to search for * @return the {@link SearchSpec} for further configuration */ SearchSpec name(Name name); /** - * The no-filter query to execute. Or, that is, the filter is {@code (objectclass=*)}. - * - *

    This is helpful when searching by name and needing to customize the {@link SearchControls} or the - * returned attribute set. + * The no-filter query to execute. Or, that is, the filter is + * {@code (objectclass=*)}. * + *

    + * This is helpful when searching by name and needing to customize the + * {@link SearchControls} or the returned attribute set. * @param consumer the consumer to alter a default query * @return the {@link SearchSpec} for further configuration */ @@ -350,7 +335,6 @@ public interface LdapClient { /** * The query to execute. - * * @param query the query to execute * @return the {@link SearchSpec} for further configuration */ @@ -364,22 +348,21 @@ public interface LdapClient { /** * Expect at most one search result, mapped by the given strategy. * - *

    Returns {@code null} if no result is found. - * + *

    + * Returns {@code null} if no result is found. * @param mapper the {@link ContextMapper} strategy to use to map the result * @return the single search result, or {@code null} if none was found - * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the result - * set contains more than one result + * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the + * result set contains more than one result */ O toObject(ContextMapper mapper); /** * Expect at most one search result, mapped by the given strategy. - * * @param mapper the {@link AttributesMapper} strategy to use to map the result * @return the single search result, or {@code null} if none was found - * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the result - * set contains more than one result + * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the + * result set contains more than one result */ O toObject(AttributesMapper mapper); @@ -390,21 +373,19 @@ public interface LdapClient { /** * Return a list of search results, each mapped by the given strategy. - * * @param mapper the {@link ContextMapper} strategy to use to map the result * @return the single search result, or empty list if none was found - * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the result - * set contains more than one result + * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the + * result set contains more than one result */ List toList(ContextMapper mapper); /** * Return a list of search results, each mapped by the given strategy. - * * @param mapper the {@link AttributesMapper} strategy to use to map the result * @return the single search result, or empty list if none was found - * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the result - * set contains more than one result + * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the + * result set contains more than one result */ List toList(AttributesMapper mapper); @@ -415,32 +396,31 @@ public interface LdapClient { /** * Return a stream of search results, each mapped by the given strategy. - * * @param mapper the {@link ContextMapper} strategy to use to map the result * @return the single search result, or empty stream if none was found - * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the result - * set contains more than one result + * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the + * result set contains more than one result */ Stream toStream(ContextMapper mapper); /** * Return a stream of search results, each mapped by the given strategy. - * * @param mapper the {@link AttributesMapper} strategy to use to map the result * @return the single search result, or empty stream if none was found - * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the result - * set contains more than one result + * @throws org.springframework.dao.IncorrectResultSizeDataAccessException if the + * result set contains more than one result */ Stream toStream(AttributesMapper mapper); + } /** * The specifications for the {@link #authenticate} request. */ interface AuthenticateSpec { + /** * The query to authenticate - * * @param query the query to authenticate * @return the {@link AuthenticateSpec} for further configuration */ @@ -448,7 +428,6 @@ public interface LdapClient { /** * The password to use - * * @param password the password to use * @return the {@link AuthenticateSpec} for further configuration */ @@ -456,32 +435,34 @@ public interface LdapClient { /** * Authenticate the query against the provided password - * - * @throws org.springframework.ldap.AuthenticationException if authentication fails or the query returns no results + * @throws org.springframework.ldap.AuthenticationException if authentication + * fails or the query returns no results */ void execute(); /** * Authenticate the query against the provided password. - * - * @param mapper a strategy for mapping the query results against another datasource - * @throws org.springframework.ldap.AuthenticationException if authentication fails or the query returns no results + * @param mapper a strategy for mapping the query results against another + * datasource + * @throws org.springframework.ldap.AuthenticationException if authentication + * fails or the query returns no results */ T execute(AuthenticatedLdapEntryContextMapper mapper); + } /** * The specifications for the {@link #bind} request. */ interface BindSpec { + /** * The object to associate with this binding. * *

    - * Note that this object is encoded into a set of attributes. If the object is - * of type {@link DirContext}, then it will be converted into attributes via + * Note that this object is encoded into a set of attributes. If the object is of + * type {@link DirContext}, then it will be converted into attributes via * {@link DirContext#getAttributes}. - * * @param object the object to associate * @return the {@link BindSpec} for further configuration */ @@ -498,9 +479,8 @@ public interface LdapClient { * Replace any existing binding with this one (equivalent to "rebind"). * *

    - * If {@code false}, then bind will throw a {@link NameAlreadyBoundException} if the entry - * already exists. - * + * If {@code false}, then bind will throw a {@link NameAlreadyBoundException} if + * the entry already exists. * @param replaceExisting whether to replace any existing entry * @return the {@link BindSpec} for further configuration */ @@ -508,19 +488,20 @@ public interface LdapClient { /** * Bind the name, object, and attributes together - * - * @throws NameAlreadyBoundException if {@code name} is already bound and {@link #replaceExisting} is {@code false} + * @throws NameAlreadyBoundException if {@code name} is already bound and + * {@link #replaceExisting} is {@code false} */ void execute(); + } /** * The specifications for the {@link #modify} request. */ interface ModifySpec { + /** * The new name for this entry. - * * @param name the new name * @return the {@link ModifySpec} for further configuration */ @@ -528,7 +509,6 @@ public interface LdapClient { /** * The new name for this entry. - * * @param name the new name * @return the {@link ModifySpec} for further configuration */ @@ -536,7 +516,6 @@ public interface LdapClient { /** * The attribute modifications to apply to this entry - * * @param modifications the attribute modifications * @return the {@link ModifySpec} for further configuration */ @@ -546,15 +525,16 @@ public interface LdapClient { * Modify the name and attributes for this entry */ void execute(); + } /** * The specifications for the {@link #unbind} request. */ interface UnbindSpec { + /** * Delete all children related to this entry - * * @param recursive whether to delete all children as well * @return the {@link UnbindSpec} for further configuration */ @@ -564,5 +544,7 @@ public interface LdapClient { * Delete the entry */ void execute(); + } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/core/LdapEntryIdentification.java b/core/src/main/java/org/springframework/ldap/core/LdapEntryIdentification.java index 0f2072a4..dee28642 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapEntryIdentification.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapEntryIdentification.java @@ -22,34 +22,36 @@ import javax.naming.directory.DirContext; import javax.naming.ldap.LdapName; /** - * Wrapper class to handle the full identification of an LDAP entry. An LDAP - * entry is identified by its Distinguished Name, in Spring LDAP represented by - * the {@link DistinguishedName} class. A Distinguished Name can be absolute - - * i.e. complete including the very root (base) of the LDAP tree - or relative - - * i.e relative to the base LDAP path of the current LDAP connection (specified - * as base to the {@link ContextSource}). + * Wrapper class to handle the full identification of an LDAP entry. An LDAP entry is + * identified by its Distinguished Name, in Spring LDAP represented by the + * {@link DistinguishedName} class. A Distinguished Name can be absolute - i.e. complete + * including the very root (base) of the LDAP tree - or relative - i.e relative to the + * base LDAP path of the current LDAP connection (specified as base to the + * {@link ContextSource}). *

    - * The different representations are needed on different occasions, e.g. the - * relative DN is typically what is needed to perform lookups and searches in - * the LDAP tree, whereas the absolute DN is needed when authenticating and when - * an LDAP entry is referred to in e.g. a group. This wrapper class contains - * both of these representations. - * + * The different representations are needed on different occasions, e.g. the relative DN + * is typically what is needed to perform lookups and searches in the LDAP tree, whereas + * the absolute DN is needed when authenticating and when an LDAP entry is referred to in + * e.g. a group. This wrapper class contains both of these representations. + * * @author Mattias Hellborg Arthursson */ public class LdapEntryIdentification { + private final LdapName relativeDn; private final LdapName absoluteDn; /** * Construct an LdapEntryIdentification instance. - * @param absoluteDn the absolute DN of the identified entry, e.g. as - * returned by {@link DirContext#getNameInNamespace()}. - * @param relativeDn the DN of the identified entry relative to the base - * LDAP path, e.g. as returned by {@link DirContextOperations#getDn()}. - * @deprecated {@link DistinguishedName} and associated classes and methods are deprecated as of 2.0. - * use {@link #LdapEntryIdentification(javax.naming.ldap.LdapName, javax.naming.ldap.LdapName)} instead. + * @param absoluteDn the absolute DN of the identified entry, e.g. as returned by + * {@link DirContext#getNameInNamespace()}. + * @param relativeDn the DN of the identified entry relative to the base LDAP path, + * e.g. as returned by {@link DirContextOperations#getDn()}. + * @deprecated {@link DistinguishedName} and associated classes and methods are + * deprecated as of 2.0. use + * {@link #LdapEntryIdentification(javax.naming.ldap.LdapName, javax.naming.ldap.LdapName)} + * instead. */ public LdapEntryIdentification(DistinguishedName absoluteDn, DistinguishedName relativeDn) { Assert.notNull(absoluteDn, "Absolute DN must not be null"); @@ -60,10 +62,10 @@ public class LdapEntryIdentification { /** * Construct an LdapEntryIdentification instance. - * @param absoluteDn the absolute DN of the identified entry, e.g. as - * returned by {@link DirContext#getNameInNamespace()}. - * @param relativeDn the DN of the identified entry relative to the base - * LDAP path, e.g. as returned by {@link DirContextOperations#getDn()}. + * @param absoluteDn the absolute DN of the identified entry, e.g. as returned by + * {@link DirContext#getNameInNamespace()}. + * @param relativeDn the DN of the identified entry relative to the base LDAP path, + * e.g. as returned by {@link DirContextOperations#getDn()}. * @since 2.0 */ public LdapEntryIdentification(LdapName absoluteDn, LdapName relativeDn) { @@ -74,8 +76,8 @@ public class LdapEntryIdentification { } /** - * Get the DN of the identified entry relative to the base LDAP path, e.g. - * as returned by {@link DirContextOperations#getDn()}. + * Get the DN of the identified entry relative to the base LDAP path, e.g. as returned + * by {@link DirContextOperations#getDn()}. * @return the relative DN. * @since 2.0 */ @@ -94,11 +96,11 @@ public class LdapEntryIdentification { } /** - * Get the DN of the identified entry relative to the base LDAP path, e.g. - * as returned by {@link DirContextOperations#getDn()}. + * Get the DN of the identified entry relative to the base LDAP path, e.g. as returned + * by {@link DirContextOperations#getDn()}. * @return the relative DN. - * @deprecated {@link DistinguishedName} and associated classes and methods are deprecated as of 2.0. - * use {@link #getRelativeName()} instead. + * @deprecated {@link DistinguishedName} and associated classes and methods are + * deprecated as of 2.0. use {@link #getRelativeName()} instead. */ public DistinguishedName getRelativeDn() { return new DistinguishedName(relativeDn); @@ -108,8 +110,8 @@ public class LdapEntryIdentification { * Get the absolute DN of the identified entry, e.g. as returned by * {@link DirContext#getNameInNamespace()}. * @return the absolute DN. - * @deprecated {@link DistinguishedName} and associated classes and methods are deprecated as of 2.0. - * use {@link #getAbsoluteName()} instead. + * @deprecated {@link DistinguishedName} and associated classes and methods are + * deprecated as of 2.0. use {@link #getAbsoluteName()} instead. */ public DistinguishedName getAbsoluteDn() { return new DistinguishedName(absoluteDn); @@ -127,4 +129,5 @@ public class LdapEntryIdentification { public int hashCode() { return absoluteDn.hashCode() ^ relativeDn.hashCode(); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/LdapEntryIdentificationContextMapper.java b/core/src/main/java/org/springframework/ldap/core/LdapEntryIdentificationContextMapper.java index 00165836..6e9e66b5 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapEntryIdentificationContextMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapEntryIdentificationContextMapper.java @@ -28,8 +28,8 @@ public class LdapEntryIdentificationContextMapper implements ContextMapperNamingEnumeration and - * closing the context and enumeration. The actual search is delegated to - * the SearchExecutor and each found NameClassPair is passed to - * the CallbackHandler. Any encountered + * Perform a search using a particular {@link SearchExecutor} and context processor. + * Use this method only if especially needed - for the most cases there is an + * overloaded convenience method which calls this one with suitable argments. This + * method handles all the plumbing; getting a readonly context; looping through the + * NamingEnumeration and closing the context and enumeration. The actual + * search is delegated to the SearchExecutor and each found NameClassPair + * is passed to the CallbackHandler. Any encountered * NamingException will be translated using * {@link LdapUtils#convertLdapException(javax.naming.NamingException)}. - * - * @param se The SearchExecutor to use for performing the - * actual search. - * @param handler The NameClassPairCallbackHandler to which - * each found entry will be passed. + * @param se The SearchExecutor to use for performing the actual search. + * @param handler The NameClassPairCallbackHandler to which each found + * entry will be passed. * @param processor DirContextProcessor for custom pre- and * post-processing. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted as no entries being found. + * NameNotFoundException will be ignored. Instead this is interpreted as + * no entries being found. */ void search(SearchExecutor se, NameClassPairCallbackHandler handler, DirContextProcessor processor) throws NamingException; /** - * Perform a search using a particular {@link SearchExecutor}. Use this - * method only if especially needed - for the most cases there is an - * overloaded convenience method which calls this one with suitable - * argments. This method handles all the plumbing; getting a readonly - * context; looping through the NamingEnumeration and closing - * the context and enumeration. The actual search is delegated to the - * SearchExecutor and each found NameClassPair is - * passed to the CallbackHandler. Any encountered - * NamingException will be translated using the + * Perform a search using a particular {@link SearchExecutor}. Use this method only if + * especially needed - for the most cases there is an overloaded convenience method + * which calls this one with suitable argments. This method handles all the plumbing; + * getting a readonly context; looping through the NamingEnumeration and + * closing the context and enumeration. The actual search is delegated to the + * SearchExecutor and each found NameClassPair is passed to + * the CallbackHandler. Any encountered NamingException will + * be translated using the * {@link LdapUtils#convertLdapException(javax.naming.NamingException)}. - * - * @param se The SearchExecutor to use for performing the - * actual search. - * @param handler The NameClassPairCallbackHandler to which - * each found entry will be passed. + * @param se The SearchExecutor to use for performing the actual search. + * @param handler The NameClassPairCallbackHandler to which each found + * entry will be passed. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted as no entries being found. + * NameNotFoundException will be ignored. Instead this is interpreted as + * no entries being found. * @see #search(Name, String, AttributesMapper) * @see #search(Name, String, ContextMapper) */ void search(SearchExecutor se, NameClassPairCallbackHandler handler) throws NamingException; /** - * Perform an operation (or series of operations) on a read-only context. - * This method handles the plumbing - getting a DirContext, - * translating any Exceptions and closing the context afterwards. This - * method is not intended for searches; use - * {@link #search(SearchExecutor, NameClassPairCallbackHandler)} or any of - * the overloaded search methods for this. - * - * @param ce The ContextExecutor to which the actual operation - * on the DirContext will be delegated. + * Perform an operation (or series of operations) on a read-only context. This method + * handles the plumbing - getting a DirContext, translating any + * Exceptions and closing the context afterwards. This method is not intended for + * searches; use {@link #search(SearchExecutor, NameClassPairCallbackHandler)} or any + * of the overloaded search methods for this. + * @param ce The ContextExecutor to which the actual operation on the + * DirContext will be delegated. * @return the result from the ContextExecutor's operation. * @throws NamingException if the operation resulted in a * NamingException. - * + * * @see #search(SearchExecutor, NameClassPairCallbackHandler) * @see #search(Name, String, AttributesMapper) * @see #search(Name, String, ContextMapper) @@ -113,14 +105,12 @@ public interface LdapOperations { T executeReadOnly(ContextExecutor ce) throws NamingException; /** - * Perform an operation (or series of operations) on a read-write context. - * This method handles the plumbing - getting a DirContext, - * translating any exceptions and closing the context afterwards. This - * method is intended only for very particular cases, where there is no - * suitable method in this interface to use. - * - * @param ce The ContextExecutor to which the actual operation - * on the DirContext will be delegated. + * Perform an operation (or series of operations) on a read-write context. This method + * handles the plumbing - getting a DirContext, translating any + * exceptions and closing the context afterwards. This method is intended only for + * very particular cases, where there is no suitable method in this interface to use. + * @param ce The ContextExecutor to which the actual operation on the + * DirContext will be delegated. * @return the result from the ContextExecutor's operation. * @throws NamingException if the operation resulted in a * NamingException. @@ -133,791 +123,689 @@ public interface LdapOperations { T executeReadWrite(ContextExecutor ce) throws NamingException; /** - * Search for all objects matching the supplied filter. Each - * SearchResult is supplied to the specified - * NameClassPairCallbackHandler. The SearchScope - * specified in the supplied SearchControls will be used in the - * search. Note that if you are using a ContextMapper, the - * returningObjFlag needs to be set to true in the - * SearchControls. - * + * Search for all objects matching the supplied filter. Each SearchResult + * is supplied to the specified NameClassPairCallbackHandler. The + * SearchScope specified in the supplied SearchControls will + * be used in the search. Note that if you are using a ContextMapper, the + * returningObjFlag needs to be set to true in the SearchControls. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. * @param controls The SearchControls to use in the search. - * @param handler The NameClassPairCallbackHandler to supply - * the SearchResult to. + * @param handler The NameClassPairCallbackHandler to supply the + * SearchResult to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void search(Name base, String filter, SearchControls controls, NameClassPairCallbackHandler handler) throws NamingException; /** * Search for all objects matching the supplied filter. See - * {@link #search(Name, String, SearchControls, NameClassPairCallbackHandler)} - * for details. - * + * {@link #search(Name, String, SearchControls, NameClassPairCallbackHandler)} for + * details. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. * @param controls The SearchControls to use in the search. - * @param handler The NameClassPairCallbackHandler to supply - * the SearchResult to. + * @param handler The NameClassPairCallbackHandler to supply the + * SearchResult to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void search(String base, String filter, SearchControls controls, NameClassPairCallbackHandler handler) throws NamingException; /** - * Search for all objects matching the supplied filter. Each - * SearchResult is supplied to the specified - * NameClassPairCallbackHandler. The SearchScope - * specified in the supplied SearchControls will be used in the - * search. Note that if you are using a ContextMapper, the - * returningObjFlag needs to be set to true in the - * SearchControls. The given DirContextProcessor - * will be called before and after the search. - * + * Search for all objects matching the supplied filter. Each SearchResult + * is supplied to the specified NameClassPairCallbackHandler. The + * SearchScope specified in the supplied SearchControls will + * be used in the search. Note that if you are using a ContextMapper, the + * returningObjFlag needs to be set to true in the SearchControls. The + * given DirContextProcessor will be called before and after the search. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. * @param controls The SearchControls to use in the search. - * @param handler The NameClassPairCallbackHandler to supply - * the SearchResult to. - * @param processor The DirContextProcessor to use before and - * after the search. + * @param handler The NameClassPairCallbackHandler to supply the + * SearchResult to. + * @param processor The DirContextProcessor to use before and after the + * search. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void search(Name base, String filter, SearchControls controls, NameClassPairCallbackHandler handler, DirContextProcessor processor) throws NamingException; /** - * Search for all objects matching the supplied filter. The Attributes in - * each SearchResult is supplied to the specified - * AttributesMapper. The SearchScope specified in - * the supplied SearchControls will be used in the search. The - * given DirContextProcessor will be called before and after - * the search. - * + * Search for all objects matching the supplied filter. The Attributes in each + * SearchResult is supplied to the specified + * AttributesMapper. The SearchScope specified in the + * supplied SearchControls will be used in the search. The given + * DirContextProcessor will be called before and after the search. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. * @param controls The SearchControls to use in the search. - * @param mapper The AttributesMapper to use for translating - * each entry. - * @param processor The DirContextProcessor to use before and - * after the search. + * @param mapper The AttributesMapper to use for translating each entry. + * @param processor The DirContextProcessor to use before and after the + * search. * @return a List containing all entries received from the * AttributesMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(String base, String filter, SearchControls controls, AttributesMapper mapper, DirContextProcessor processor) throws NamingException; /** - * Search for all objects matching the supplied filter. The Attributes in - * each SearchResult is supplied to the specified - * AttributesMapper. The SearchScope specified in - * the supplied SearchControls will be used in the search. The - * given DirContextProcessor will be called before and after - * the search. - * + * Search for all objects matching the supplied filter. The Attributes in each + * SearchResult is supplied to the specified + * AttributesMapper. The SearchScope specified in the + * supplied SearchControls will be used in the search. The given + * DirContextProcessor will be called before and after the search. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. * @param controls The SearchControls to use in the search. - * @param mapper The AttributesMapper to use for translating - * each entry. - * @param processor The DirContextProcessor to use before and - * after the search. + * @param mapper The AttributesMapper to use for translating each entry. + * @param processor The DirContextProcessor to use before and after the + * search. * @return a List containing all entries received from the * AttributesMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(Name base, String filter, SearchControls controls, AttributesMapper mapper, DirContextProcessor processor) throws NamingException; /** - * Search for all objects matching the supplied filter. The Object returned - * in each SearchResult is supplied to the specified - * ContextMapper. The SearchScope specified in the - * supplied SearchControls will be used in the search. The - * given DirContextProcessor will be called before and after - * the search. - * + * Search for all objects matching the supplied filter. The Object returned in each + * SearchResult is supplied to the specified ContextMapper. + * The SearchScope specified in the supplied SearchControls + * will be used in the search. The given DirContextProcessor will be + * called before and after the search. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param controls The SearchControls to use in the search. If - * the returnObjFlag is not set in the SearchControls, this - * method will set it automatically, as this is required for the - * ContextMapper to work. - * @param mapper The ContextMapper to use for translating each - * entry. - * @param processor The DirContextProcessor to use before and - * after the search. + * @param controls The SearchControls to use in the search. If the + * returnObjFlag is not set in the SearchControls, this method will set + * it automatically, as this is required for the ContextMapper to work. + * @param mapper The ContextMapper to use for translating each entry. + * @param processor The DirContextProcessor to use before and after the + * search. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ - List search(String base, String filter, SearchControls controls, ContextMapper mapper, DirContextProcessor processor) - throws NamingException; + List search(String base, String filter, SearchControls controls, ContextMapper mapper, + DirContextProcessor processor) throws NamingException; /** - * Search for all objects matching the supplied filter. The Object returned - * in each SearchResult is supplied to the specified - * ContextMapper. The SearchScope specified in the - * supplied SearchControls will be used in the search. The - * given DirContextProcessor will be called before and after - * the search. - * + * Search for all objects matching the supplied filter. The Object returned in each + * SearchResult is supplied to the specified ContextMapper. + * The SearchScope specified in the supplied SearchControls + * will be used in the search. The given DirContextProcessor will be + * called before and after the search. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param controls The SearchControls to use in the search. If - * the returnObjFlag is not set in the SearchControls, this - * method will set it automatically, as this is required for the - * ContextMapper to work. - * @param mapper The ContextMapper to use for translating each - * entry. - * @param processor The DirContextProcessor to use before and - * after the search. + * @param controls The SearchControls to use in the search. If the + * returnObjFlag is not set in the SearchControls, this method will set + * it automatically, as this is required for the ContextMapper to work. + * @param mapper The ContextMapper to use for translating each entry. + * @param processor The DirContextProcessor to use before and after the + * search. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ - List search(Name base, String filter, SearchControls controls, ContextMapper mapper, DirContextProcessor processor) - throws NamingException; + List search(Name base, String filter, SearchControls controls, ContextMapper mapper, + DirContextProcessor processor) throws NamingException; /** * Search for all objects matching the supplied filter. See * {@link #search(Name, String, SearchControls, NameClassPairCallbackHandler, DirContextProcessor)} * for details. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. * @param controls The SearchControls to use in the search. - * @param handler The NameClassPairCallbackHandler to supply - * the SearchResults to. - * @param processor The DirContextProcessor to use before and - * after the search. + * @param handler The NameClassPairCallbackHandler to supply the + * SearchResults to. + * @param processor The DirContextProcessor to use before and after the + * search. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void search(String base, String filter, SearchControls controls, NameClassPairCallbackHandler handler, DirContextProcessor processor) throws NamingException; /** - * Search for all objects matching the supplied filter. Each - * SearchResult is supplied to the specified - * NameClassPairCallbackHandler. Use the specified values for - * search scope and return objects flag. - * + * Search for all objects matching the supplied filter. Each SearchResult + * is supplied to the specified NameClassPairCallbackHandler. Use the + * specified values for search scope and return objects flag. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param returningObjFlag Whether the bound object should be returned in - * search results. Must be set to true if a - * ContextMapper is used. - * @param handler The NameClassPairCallbackHandler to supply - * the SearchResults to. + * @param searchScope The search scope to set in SearchControls . + * @param returningObjFlag Whether the bound object should be returned in search + * results. Must be set to true if a ContextMapper is used. + * @param handler The NameClassPairCallbackHandler to supply the + * SearchResults to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void search(Name base, String filter, int searchScope, boolean returningObjFlag, NameClassPairCallbackHandler handler) throws NamingException; /** - * Search for all objects matching the supplied filter. Each - * SearchResult is supplied to the specified - * NameClassPairCallbackHandler. Use the specified values for - * search scope and return objects flag. - * + * Search for all objects matching the supplied filter. Each SearchResult + * is supplied to the specified NameClassPairCallbackHandler. Use the + * specified values for search scope and return objects flag. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param returningObjFlag Whether the bound object should be returned in - * search results. Must be set to true if a - * ContextMapper is used. - * @param handler The NameClassPairCallbackHandler to supply - * the SearchResults to. + * @param searchScope The search scope to set in SearchControls . + * @param returningObjFlag Whether the bound object should be returned in search + * results. Must be set to true if a ContextMapper is used. + * @param handler The NameClassPairCallbackHandler to supply the + * SearchResults to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void search(String base, String filter, int searchScope, boolean returningObjFlag, NameClassPairCallbackHandler handler) throws NamingException; /** - * Search for all objects matching the supplied filter. Each - * SearchResult is supplied to the specified - * NameClassPairCallbackHandler. The default Search scope ( - * SearchControls.SUBTREE_SCOPE) will be used and the + * Search for all objects matching the supplied filter. Each SearchResult + * is supplied to the specified NameClassPairCallbackHandler. The default + * Search scope ( SearchControls.SUBTREE_SCOPE) will be used and the * returnObjects flag will be set to false. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param handler The NameClassPairCallbackHandler to supply - * the SearchResults to. + * @param handler The NameClassPairCallbackHandler to supply the + * SearchResults to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void search(Name base, String filter, NameClassPairCallbackHandler handler) throws NamingException; /** - * Search for all objects matching the supplied filter. Each - * SearchResult is supplied to the specified - * NameClassPairCallbackHandler. The default Search scope ( - * SearchControls.SUBTREE_SCOPE) will be used and the + * Search for all objects matching the supplied filter. Each SearchResult + * is supplied to the specified NameClassPairCallbackHandler. The default + * Search scope ( SearchControls.SUBTREE_SCOPE) will be used and the * returnObjects flag will be set to false. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param handler The NameClassPairCallbackHandler to supply - * the SearchResults to. + * @param handler The NameClassPairCallbackHandler to supply the + * SearchResults to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void search(String base, String filter, NameClassPairCallbackHandler handler) throws NamingException; /** - * Search for all objects matching the supplied filter. Only return any - * attributes mathing the specified attribute names. The Attributes in each + * Search for all objects matching the supplied filter. Only return any attributes + * mathing the specified attribute names. The Attributes in each * SearchResult is supplied to the specified * AttributesMapper. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param attrs The attributes to return, null means returning - * all attributes. - * @param mapper The AttributesMapper to use for translating - * each entry. + * @param searchScope The search scope to set in SearchControls . + * @param attrs The attributes to return, null means returning all + * attributes. + * @param mapper The AttributesMapper to use for translating each entry. * @return a List containing all entries received from the * AttributesMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(Name base, String filter, int searchScope, String[] attrs, AttributesMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. Only return any - * attributes mathing the specified attribute names. The Attributes in each + * Search for all objects matching the supplied filter. Only return any attributes + * mathing the specified attribute names. The Attributes in each * SearchResult is supplied to the specified * AttributesMapper. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param attrs The attributes to return, null means returning - * all attributes. - * @param mapper The AttributesMapper to use for translating - * each entry. + * @param searchScope The search scope to set in SearchControls . + * @param attrs The attributes to return, null means returning all + * attributes. + * @param mapper The AttributesMapper to use for translating each entry. * @return a List containing all entries received from the * AttributesMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(String base, String filter, int searchScope, String[] attrs, AttributesMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The Attributes in - * each SearchResult is supplied to the specified + * Search for all objects matching the supplied filter. The Attributes in each + * SearchResult is supplied to the specified * AttributesMapper. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param mapper The AttributesMapper to use for translating - * each entry. + * @param searchScope The search scope to set in SearchControls . + * @param mapper The AttributesMapper to use for translating each entry. * @return a List containing all entries received from the * AttributesMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(Name base, String filter, int searchScope, AttributesMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The Attributes in - * each SearchResult is supplied to the specified + * Search for all objects matching the supplied filter. The Attributes in each + * SearchResult is supplied to the specified * AttributesMapper. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param mapper The AttributesMapper to use for translating - * each entry. + * @param searchScope The search scope to set in SearchControls . + * @param mapper The AttributesMapper to use for translating each entry. * @return a List containing all entries received from the * AttributesMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(String base, String filter, int searchScope, AttributesMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The Attributes in - * each SearchResult is supplied to the specified + * Search for all objects matching the supplied filter. The Attributes in each + * SearchResult is supplied to the specified * AttributesMapper. The default search scope will be used. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param mapper The AttributesMapper to use for translating - * each entry. + * @param mapper The AttributesMapper to use for translating each entry. * @return a List containing all entries received from the * AttributesMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(Name base, String filter, AttributesMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The Attributes in - * each SearchResult is supplied to the specified + * Search for all objects matching the supplied filter. The Attributes in each + * SearchResult is supplied to the specified * AttributesMapper. The default search scope will be used. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param mapper The AttributesMapper to use for translating - * each entry. + * @param mapper The AttributesMapper to use for translating each entry. * @return a List containing all entries received from the * AttributesMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(String base, String filter, AttributesMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The - * Object returned in each SearchResult is - * supplied to the specified ContextMapper. Only return the - * supplied attributes. - * + * Search for all objects matching the supplied filter. The Object + * returned in each SearchResult is supplied to the specified + * ContextMapper. Only return the supplied attributes. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param attrs The attributes to return, null means all - * attributes. - * @param mapper The ContextMapper to use for translating each - * entry. + * @param searchScope The search scope to set in SearchControls . + * @param attrs The attributes to return, null means all attributes. + * @param mapper The ContextMapper to use for translating each entry. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ - List search(Name base, String filter, int searchScope, String[] attrs, ContextMapper mapper) throws NamingException; + List search(Name base, String filter, int searchScope, String[] attrs, ContextMapper mapper) + throws NamingException; /** - * Search for all objects matching the supplied filter. The - * Object returned in each SearchResult is - * supplied to the specified ContextMapper. Only return the - * supplied attributes. - * + * Search for all objects matching the supplied filter. The Object + * returned in each SearchResult is supplied to the specified + * ContextMapper. Only return the supplied attributes. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param attrs The attributes to return, null means all - * attributes. - * @param mapper The ContextMapper to use for translating each - * entry. + * @param searchScope The search scope to set in SearchControls . + * @param attrs The attributes to return, null means all attributes. + * @param mapper The ContextMapper to use for translating each entry. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(String base, String filter, int searchScope, String[] attrs, ContextMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The - * Object returned in each SearchResult is - * supplied to the specified ContextMapper. - * + * Search for all objects matching the supplied filter. The Object + * returned in each SearchResult is supplied to the specified + * ContextMapper. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param mapper The ContextMapper to use for translating each - * entry. + * @param searchScope The search scope to set in SearchControls . + * @param mapper The ContextMapper to use for translating each entry. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(Name base, String filter, int searchScope, ContextMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The - * Object returned in each SearchResult is - * supplied to the specified ContextMapper. - * + * Search for all objects matching the supplied filter. The Object + * returned in each SearchResult is supplied to the specified + * ContextMapper. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param searchScope The search scope to set in SearchControls - * . - * @param mapper The ContextMapper to use for translating each - * entry. + * @param searchScope The search scope to set in SearchControls . + * @param mapper The ContextMapper to use for translating each entry. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(String base, String filter, int searchScope, ContextMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The - * Object returned in each SearchResult is - * supplied to the specified ContextMapper. The default search - * scope (SearchControls.SUBTREE_SCOPE) will be used. - * + * Search for all objects matching the supplied filter. The Object + * returned in each SearchResult is supplied to the specified + * ContextMapper. The default search scope + * (SearchControls.SUBTREE_SCOPE) will be used. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param mapper The ContextMapper to use for translating each - * entry. + * @param mapper The ContextMapper to use for translating each entry. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(Name base, String filter, ContextMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The - * Object returned in each SearchResult is - * supplied to the specified ContextMapper. The default search - * scope (SearchControls.SUBTREE_SCOPE) will be used. - * + * Search for all objects matching the supplied filter. The Object + * returned in each SearchResult is supplied to the specified + * ContextMapper. The default search scope + * (SearchControls.SUBTREE_SCOPE) will be used. * @param base The base DN where the search should begin. * @param filter The filter to use in the search. - * @param mapper The ContextMapper to use for translating each - * entry. + * @param mapper The ContextMapper to use for translating each entry. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List search(String base, String filter, ContextMapper mapper) throws NamingException; /** - * Search for all objects matching the supplied filter. The - * Object returned in each SearchResult is - * supplied to the specified ContextMapper. The default search - * scope (SearchControls.SUBTREE_SCOPE) will be used. - * - * @param base The base DN where the search should begin. - * @param filter The filter to use in the search. - * @param mapper The ContextMapper to use for translating each - * entry. - * @return a List containing all entries received from the - * ContextMapper. - * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. - */ - List search(String base, String filter, SearchControls controls, ContextMapper mapper) throws NamingException; - - /** - * Search for all objects matching the supplied filter. The Object returned - * in each SearchResult is supplied to the specified - * ContextMapper. - * - * @param base The base DN where the search should begin. - * @param filter The filter to use in the search. - * @param controls The SearchControls to use in the search. If - * the returnObjFlag is not set in the SearchControls, this - * method will set it automatically, as this is required for the - * ContextMapper to work. - * @param mapper The ContextMapper to use for translating each - * entry. - * @return a List containing all entries received from the - * ContextMapper. - * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. - */ - List search(Name base, String filter, SearchControls controls, ContextMapper mapper) throws NamingException; - - /** - * Search for all objects matching the supplied filter. The Attributes + * Search for all objects matching the supplied filter. The Object * returned in each SearchResult is supplied to the specified + * ContextMapper. The default search scope + * (SearchControls.SUBTREE_SCOPE) will be used. + * @param base The base DN where the search should begin. + * @param filter The filter to use in the search. + * @param mapper The ContextMapper to use for translating each entry. + * @return a List containing all entries received from the + * ContextMapper. + * @throws NamingException if any error occurs. Note that a + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. + */ + List search(String base, String filter, SearchControls controls, ContextMapper mapper) + throws NamingException; + + /** + * Search for all objects matching the supplied filter. The Object returned in each + * SearchResult is supplied to the specified ContextMapper. + * @param base The base DN where the search should begin. + * @param filter The filter to use in the search. + * @param controls The SearchControls to use in the search. If the + * returnObjFlag is not set in the SearchControls, this method will set + * it automatically, as this is required for the ContextMapper to work. + * @param mapper The ContextMapper to use for translating each entry. + * @return a List containing all entries received from the + * ContextMapper. + * @throws NamingException if any error occurs. Note that a + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. + */ + List search(Name base, String filter, SearchControls controls, ContextMapper mapper) + throws NamingException; + + /** + * Search for all objects matching the supplied filter. The Attributes returned in + * each SearchResult is supplied to the specified * AttributesMapper. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. * @param controls The SearchControls to use in the search. - * @param mapper The AttributesMapper to use for translating - * each entry. + * @param mapper The AttributesMapper to use for translating each entry. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ - List search(String base, String filter, SearchControls controls, AttributesMapper mapper) throws NamingException; + List search(String base, String filter, SearchControls controls, AttributesMapper mapper) + throws NamingException; /** - * Search for all objects matching the supplied filter. The Attributes - * returned in each SearchResult is supplied to the specified + * Search for all objects matching the supplied filter. The Attributes returned in + * each SearchResult is supplied to the specified * AttributesMapper. - * * @param base The base DN where the search should begin. * @param filter The filter to use in the search. * @param controls The SearchControls to use in the search. - * @param mapper The AttributesMapper to use for translating - * each entry. + * @param mapper The AttributesMapper to use for translating each entry. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ - List search(Name base, String filter, SearchControls controls, AttributesMapper mapper) throws NamingException; + List search(Name base, String filter, SearchControls controls, AttributesMapper mapper) + throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. Each resulting NameClassPair is supplied - * to the specified NameClassPairCallbackHandler. - * + * Perform a non-recursive listing of the children of the given base. + * Each resulting NameClassPair is supplied to the specified + * NameClassPairCallbackHandler. * @param base The base DN where the list should be performed. - * @param handler The NameClassPairCallbackHandler to supply - * each {@link NameClassPair} to. + * @param handler The NameClassPairCallbackHandler to supply each + * {@link NameClassPair} to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void list(String base, NameClassPairCallbackHandler handler) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. Each resulting NameClassPair is supplied - * to the specified NameClassPairCallbackHandler. - * + * Perform a non-recursive listing of the children of the given base. + * Each resulting NameClassPair is supplied to the specified + * NameClassPairCallbackHandler. * @param base The base DN where the list should be performed. - * @param handler The NameClassPairCallbackHandler to supply - * each {@link NameClassPair} to. + * @param handler The NameClassPairCallbackHandler to supply each + * {@link NameClassPair} to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void list(Name base, NameClassPairCallbackHandler handler) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. Pass all the found NameClassPair objects - * to the supplied NameClassPairMapper and return all the - * returned values as a List. - * + * Perform a non-recursive listing of the children of the given base. + * Pass all the found NameClassPair objects to the supplied + * NameClassPairMapper and return all the returned values as a + * List. * @param base The base DN where the list should be performed. * @param mapper The NameClassPairMapper to supply each * {@link NameClassPair} to. - * @return a List containing the Objects returned from the - * Mapper. + * @return a List containing the Objects returned from the Mapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List list(String base, NameClassPairMapper mapper) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. Pass all the found NameClassPair objects - * to the supplied NameClassPairMapper and return all the - * returned values as a List. - * + * Perform a non-recursive listing of the children of the given base. + * Pass all the found NameClassPair objects to the supplied + * NameClassPairMapper and return all the returned values as a + * List. * @param base The base DN where the list should be performed. * @param mapper The NameClassPairMapper to supply each * {@link NameClassPair} to. - * @return a List containing the Objects returned from the - * Mapper. + * @return a List containing the Objects returned from the Mapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List list(Name base, NameClassPairMapper mapper) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. - * + * Perform a non-recursive listing of the children of the given base. * @param base The base DN where the list should be performed. - * @return a List containing the names of all the contexts bound to - * base. + * @return a List containing the names of all the contexts bound to base. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List list(String base) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. - * + * Perform a non-recursive listing of the children of the given base. * @param base The base DN where the list should be performed. - * @return a List containing the names of all the contexts bound to - * base. + * @return a List containing the names of all the contexts bound to base. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List list(Name base) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. Each resulting Binding is supplied to the - * specified NameClassPairCallbackHandler. - * + * Perform a non-recursive listing of the children of the given base. + * Each resulting Binding is supplied to the specified + * NameClassPairCallbackHandler. * @param base The base DN where the list should be performed. - * @param handler The NameClassPairCallbackHandler to supply - * each {@link Binding} to. + * @param handler The NameClassPairCallbackHandler to supply each + * {@link Binding} to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void listBindings(final String base, NameClassPairCallbackHandler handler) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. Each resulting Binding is supplied to the - * specified NameClassPairCallbackHandler. - * + * Perform a non-recursive listing of the children of the given base. + * Each resulting Binding is supplied to the specified + * NameClassPairCallbackHandler. * @param base The base DN where the list should be performed. - * @param handler The NameClassPairCallbackHandler to supply - * each {@link Binding} to. + * @param handler The NameClassPairCallbackHandler to supply each + * {@link Binding} to. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ void listBindings(final Name base, NameClassPairCallbackHandler handler) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. Pass all the found Binding objects to the - * supplied NameClassPairMapper and return all the returned - * values as a List. - * + * Perform a non-recursive listing of the children of the given base. + * Pass all the found Binding objects to the supplied + * NameClassPairMapper and return all the returned values as a + * List. * @param base The base DN where the list should be performed. - * @param mapper The NameClassPairMapper to supply each - * {@link Binding} to. - * @return a List containing the Objects returned from the - * Mapper. + * @param mapper The NameClassPairMapper to supply each {@link Binding} + * to. + * @return a List containing the Objects returned from the Mapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List listBindings(String base, NameClassPairMapper mapper) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. Pass all the found Binding objects to the - * supplied NameClassPairMapper and return all the returned - * values as a List. - * + * Perform a non-recursive listing of the children of the given base. + * Pass all the found Binding objects to the supplied + * NameClassPairMapper and return all the returned values as a + * List. * @param base The base DN where the list should be performed. - * @param mapper The NameClassPairMapper to supply each - * {@link Binding} to. - * @return a List containing the Objects returned from the - * Mapper. + * @param mapper The NameClassPairMapper to supply each {@link Binding} + * to. + * @return a List containing the Objects returned from the Mapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List listBindings(Name base, NameClassPairMapper mapper) throws NamingException; /** - * Perform a non-recursive listing of children of the given - * base. - * + * Perform a non-recursive listing of children of the given base. * @param base The base DN where the list should be performed. - * @return a List containing the names of all the contexts - * bound to base. + * @return a List containing the names of all the contexts bound to + * base. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List listBindings(final String base) throws NamingException; /** - * Perform a non-recursive listing of children of the given - * base. - * + * Perform a non-recursive listing of children of the given base. * @param base The base DN where the list should be performed. - * @return a List containing the names of all the contexts - * bound to base. + * @return a List containing the names of all the contexts bound to + * base. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List listBindings(final Name base) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. The Object returned in each {@link Binding} is - * supplied to the specified ContextMapper. - * + * Perform a non-recursive listing of the children of the given base. The + * Object returned in each {@link Binding} is supplied to the specified + * ContextMapper. * @param base The base DN where the list should be performed. - * @param mapper The ContextMapper to use for mapping the found - * object. + * @param mapper The ContextMapper to use for mapping the found object. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List listBindings(String base, ContextMapper mapper) throws NamingException; /** - * Perform a non-recursive listing of the children of the given - * base. The Object returned in each {@link Binding} is - * supplied to the specified ContextMapper. - * + * Perform a non-recursive listing of the children of the given base. The + * Object returned in each {@link Binding} is supplied to the specified + * ContextMapper. * @param base The base DN where the list should be performed. - * @param mapper The ContextMapper to use for mapping the found - * object. + * @param mapper The ContextMapper to use for mapping the found object. * @return a List containing all entries received from the * ContextMapper. * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is - * interpreted that no entries were found. + * NameNotFoundException will be ignored. Instead this is interpreted + * that no entries were found. */ List listBindings(Name base, ContextMapper mapper) throws NamingException; /** - * Lookup the supplied DN and return the found object. This will typically - * be a {@link DirContextAdapter}, unless the DirObjectFactory - * has been modified in the ContextSource. - * + * Lookup the supplied DN and return the found object. This will typically be a + * {@link DirContextAdapter}, unless the DirObjectFactory has been + * modified in the ContextSource. * @param dn The distinguished name of the object to find. * @return the found object, typically a {@link DirContextAdapter} instance. * @throws NamingException if any error occurs. @@ -927,10 +815,9 @@ public interface LdapOperations { Object lookup(Name dn) throws NamingException; /** - * Lookup the supplied DN and return the found object. This will typically - * be a {@link DirContextAdapter}, unless the DirObjectFactory - * has been modified in the ContextSource. - * + * Lookup the supplied DN and return the found object. This will typically be a + * {@link DirContextAdapter}, unless the DirObjectFactory has been + * modified in the ContextSource. * @param dn The distinguished name of the object to find. * @return the found object, typically a {@link DirContextAdapter} instance. * @throws NamingException if any error occurs. @@ -940,48 +827,42 @@ public interface LdapOperations { Object lookup(String dn) throws NamingException; /** - * Convenience method to get the attributes of a specified DN and - * automatically pass them to an AttributesMapper. - * + * Convenience method to get the attributes of a specified DN and automatically pass + * them to an AttributesMapper. * @param dn The distinguished name to find. - * @param mapper The AttributesMapper to use for mapping the - * found object. + * @param mapper The AttributesMapper to use for mapping the found + * object. * @return the object returned from the mapper. * @throws NamingException if any error occurs. */ T lookup(Name dn, AttributesMapper mapper) throws NamingException; /** - * Convenience method to get the attributes of a specified DN and - * automatically pass them to an AttributesMapper. - * + * Convenience method to get the attributes of a specified DN and automatically pass + * them to an AttributesMapper. * @param dn The distinguished name to find. - * @param mapper The AttributesMapper to use for mapping the - * found object. + * @param mapper The AttributesMapper to use for mapping the found + * object. * @return the object returned from the mapper. * @throws NamingException if any error occurs. */ T lookup(String dn, AttributesMapper mapper) throws NamingException; /** - * Convenience method to lookup a specified DN and automatically pass the - * found object to a ContextMapper. - * + * Convenience method to lookup a specified DN and automatically pass the found object + * to a ContextMapper. * @param dn The distinguished name to find. - * @param mapper The ContextMapper to use for mapping the found - * object. + * @param mapper The ContextMapper to use for mapping the found object. * @return the object returned from the mapper. * @throws NamingException if any error occurs. */ T lookup(Name dn, ContextMapper mapper) throws NamingException; /** - * Convenience method to lookup a specified DN and automatically pass the - * found object to a ContextMapper. - * + * Convenience method to lookup a specified DN and automatically pass the found object + * to a ContextMapper. * @param dn The distinguished name to find. - * @param mapper The ContextMapper to use for mapping the found - * object. + * @param mapper The ContextMapper to use for mapping the found object. * @return the object returned from the mapper. * @throws NamingException if any error occurs. */ @@ -990,11 +871,10 @@ public interface LdapOperations { /** * Convenience method to get the specified attributes of a specified DN and * automatically pass them to an AttributesMapper. - * * @param dn The distinguished name to find. * @param attributes The names of the attributes to pass to the mapper. - * @param mapper The AttributesMapper to use for mapping the - * found object. + * @param mapper The AttributesMapper to use for mapping the found + * object. * @return the object returned from the mapper. * @throws NamingException if any error occurs. */ @@ -1003,11 +883,10 @@ public interface LdapOperations { /** * Convenience method to get the specified attributes of a specified DN and * automatically pass them to an AttributesMapper. - * * @param dn The distinguished name to find. * @param attributes The names of the attributes to pass to the mapper. - * @param mapper The AttributesMapper to use for mapping the - * found object. + * @param mapper The AttributesMapper to use for mapping the found + * object. * @return the object returned from the mapper. * @throws NamingException if any error occurs. */ @@ -1016,11 +895,9 @@ public interface LdapOperations { /** * Convenience method to get the specified attributes of a specified DN and * automatically pass them to a ContextMapper. - * * @param dn The distinguished name to find. * @param attributes The names of the attributes to pass to the mapper. - * @param mapper The ContextMapper to use for mapping the found - * object. + * @param mapper The ContextMapper to use for mapping the found object. * @return the object returned from the mapper. * @throws NamingException if any error occurs. */ @@ -1029,20 +906,16 @@ public interface LdapOperations { /** * Convenience method to get the specified attributes of a specified DN and * automatically pass them to a ContextMapper. - * * @param dn The distinguished name to find. * @param attributes The names of the attributes to pass to the mapper. - * @param mapper The ContextMapper to use for mapping the found - * object. + * @param mapper The ContextMapper to use for mapping the found object. * @return the object returned from the mapper. * @throws NamingException if any error occurs. */ T lookup(String dn, String[] attributes, ContextMapper mapper) throws NamingException; /** - * Modify an entry in the LDAP tree using the supplied - * ModificationItems. - * + * Modify an entry in the LDAP tree using the supplied ModificationItems. * @param dn The distinguished name of the node to modify. * @param mods The modifications to perform. * @throws NamingException if any error occurs. @@ -1051,9 +924,7 @@ public interface LdapOperations { void modifyAttributes(Name dn, ModificationItem[] mods) throws NamingException; /** - * Modify an entry in the LDAP tree using the supplied - * ModificationItems. - * + * Modify an entry in the LDAP tree using the supplied ModificationItems. * @param dn The distinguished name of the node to modify. * @param mods The modifications to perform. * @throws NamingException if any error occurs. @@ -1062,11 +933,9 @@ public interface LdapOperations { void modifyAttributes(String dn, ModificationItem[] mods) throws NamingException; /** - * Create an entry in the LDAP tree. The attributes used to create the entry - * are either retrieved from the obj parameter or the - * attributes parameter (or both). One of these parameters may - * be null but not both. - * + * Create an entry in the LDAP tree. The attributes used to create the entry are + * either retrieved from the obj parameter or the attributes + * parameter (or both). One of these parameters may be null but not both. * @param dn The distinguished name to bind the object and attributes to. * @param obj The object to bind, may be null. Typically a * DirContext implementation. @@ -1077,11 +946,9 @@ public interface LdapOperations { void bind(Name dn, Object obj, Attributes attributes) throws NamingException; /** - * Create an entry in the LDAP tree. The attributes used to create the entry - * are either retrieved from the obj parameter or the - * attributes parameter (or both). One of these parameters may - * be null but not both. - * + * Create an entry in the LDAP tree. The attributes used to create the entry are + * either retrieved from the obj parameter or the attributes + * parameter (or both). One of these parameters may be null but not both. * @param dn The distinguished name to bind the object and attributes to. * @param obj The object to bind, may be null. Typically a * DirContext implementation. @@ -1092,59 +959,52 @@ public interface LdapOperations { void bind(String dn, Object obj, Attributes attributes) throws NamingException; /** - * Remove an entry from the LDAP tree. The entry must not have any children - * - if you suspect that the entry might have descendants, use - * {@link #unbind(Name, boolean)} in stead. - * + * Remove an entry from the LDAP tree. The entry must not have any children - if you + * suspect that the entry might have descendants, use {@link #unbind(Name, boolean)} + * in stead. * @param dn The distinguished name of the entry to remove. * @throws NamingException if any error occurs. */ void unbind(Name dn) throws NamingException; /** - * Remove an entry from the LDAP tree. The entry must not have any children - * - if you suspect that the entry might have descendants, use - * {@link #unbind(Name, boolean)} in stead. - * + * Remove an entry from the LDAP tree. The entry must not have any children - if you + * suspect that the entry might have descendants, use {@link #unbind(Name, boolean)} + * in stead. * @param dn The distinguished name to unbind. * @throws NamingException if any error occurs. */ void unbind(String dn) throws NamingException; /** - * Remove an entry from the LDAP tree, optionally removing all descendants - * in the process. - * + * Remove an entry from the LDAP tree, optionally removing all descendants in the + * process. * @param dn The distinguished name to unbind. - * @param recursive Whether to unbind all subcontexts as well. If this - * parameter is false and the entry has children, the operation - * will fail. + * @param recursive Whether to unbind all subcontexts as well. If this parameter is + * false and the entry has children, the operation will fail. * @throws NamingException if any error occurs. */ void unbind(Name dn, boolean recursive) throws NamingException; /** - * Remove an entry from the LDAP tree, optionally removing all descendants - * in the process. - * + * Remove an entry from the LDAP tree, optionally removing all descendants in the + * process. * @param dn The distinguished name to unbind. - * @param recursive Whether to unbind all subcontexts as well. If this - * parameter is false and the entry has children, the operation - * will fail. + * @param recursive Whether to unbind all subcontexts as well. If this parameter is + * false and the entry has children, the operation will fail. * @throws NamingException if any error occurs. */ void unbind(String dn, boolean recursive) throws NamingException; /** - * Remove an entry and replace it with a new one. The attributes used to - * create the entry are either retrieved from the obj parameter - * or the attributes parameter (or both). One of these - * parameters may be null but not both. This method assumes - * that the specified context already exists - if not it will fail. - * + * Remove an entry and replace it with a new one. The attributes used to create the + * entry are either retrieved from the obj parameter or the + * attributes parameter (or both). One of these parameters may be + * null but not both. This method assumes that the specified context + * already exists - if not it will fail. * @param dn The distinguished name to rebind. - * @param obj The object to bind to the DN, may be null. - * Typically a DirContext implementation. + * @param obj The object to bind to the DN, may be null. Typically a + * DirContext implementation. * @param attributes The attributes to bind, may be null. * @throws NamingException if any error occurs. * @see DirContextAdapter @@ -1152,15 +1012,14 @@ public interface LdapOperations { void rebind(Name dn, Object obj, Attributes attributes) throws NamingException; /** - * Remove an entry and replace it with a new one. The attributes used to - * create the entry are either retrieved from the obj parameter - * or the attributes parameter (or both). One of these - * parameters may be null but not both. This method assumes - * that the specified context already exists - if not it will fail. - * + * Remove an entry and replace it with a new one. The attributes used to create the + * entry are either retrieved from the obj parameter or the + * attributes parameter (or both). One of these parameters may be + * null but not both. This method assumes that the specified context + * already exists - if not it will fail. * @param dn The distinguished name to rebind. - * @param obj The object to bind to the DN, may be null. - * Typically a DirContext implementation. + * @param obj The object to bind to the DN, may be null. Typically a + * DirContext implementation. * @param attributes The attributes to bind, may be null. * @throws NamingException if any error occurs. * @see DirContextAdapter @@ -1169,11 +1028,10 @@ public interface LdapOperations { /** * Move an entry in the LDAP tree to a new location. - * * @param oldDn The distinguished name of the entry to move; may not be * null or empty. - * @param newDn The distinguished name where the entry should be moved; may - * not be null or empty. + * @param newDn The distinguished name where the entry should be moved; may not be + * null or empty. * @throws ContextNotEmptyException if newDn is already bound * @throws NamingException if any other error occurs. */ @@ -1181,11 +1039,10 @@ public interface LdapOperations { /** * Move an entry in the LDAP tree to a new location. - * * @param oldDn The distinguished name of the entry to move; may not be * null or empty. - * @param newDn The distinguished name where the entry should be moved; may - * not be null or empty. + * @param newDn The distinguished name where the entry should be moved; may not be + * null or empty. * @throws ContextNotEmptyException if newDn is already bound * @throws NamingException if any other error occurs. */ @@ -1194,13 +1051,11 @@ public interface LdapOperations { /** * Convenience method to lookup the supplied DN and automatically cast it to * {@link DirContextOperations}. - * * @param dn The distinguished name of the object to find. * @return The found object, cast to {@link DirContextOperations}. - * @throws ClassCastException if an alternative - * DirObjectFactory has been registered with the - * ContextSource, causing the actual class of the returned - * object to be something else than {@link DirContextOperations}. + * @throws ClassCastException if an alternative DirObjectFactory has been + * registered with the ContextSource, causing the actual class of the + * returned object to be something else than {@link DirContextOperations}. * @throws NamingException if any other error occurs. * @see #lookup(Name) * @see #modifyAttributes(DirContextOperations) @@ -1211,13 +1066,11 @@ public interface LdapOperations { /** * Convenience method to lookup the supplied DN and automatically cast it to * {@link DirContextOperations}. - * * @param dn The distinguished name of the object to find. * @return The found object, cast to {@link DirContextOperations}. - * @throws ClassCastException if an alternative - * DirObjectFactory has been registered with the - * ContextSource, causing the actual class of the returned - * object to be something else than {@link DirContextOperations}. + * @throws ClassCastException if an alternative DirObjectFactory has been + * registered with the ContextSource, causing the actual class of the + * returned object to be something else than {@link DirContextOperations}. * @throws NamingException if any other error occurs. * @see #lookup(String) * @see #modifyAttributes(DirContextOperations) @@ -1227,33 +1080,31 @@ public interface LdapOperations { /** * Modify the attributes of the entry referenced by the supplied - * {@link DirContextOperations} instance. The DN to update will be the DN of - * the DirContextOperationsinstance, and the - * ModificationItem array is retrieved from the - * DirContextOperations instance using a call to - * {@link AttributeModificationsAware#getModificationItems()}. NB: - * The supplied instance needs to have been properly initialized; this means - * that if it hasn't been received from a lookup operation, its - * DN needs to be initialized and it must have been put in update mode ( + * {@link DirContextOperations} instance. The DN to update will be the DN of the + * DirContextOperationsinstance, and the ModificationItem + * array is retrieved from the DirContextOperations instance using a call + * to {@link AttributeModificationsAware#getModificationItems()}. NB: The + * supplied instance needs to have been properly initialized; this means that if it + * hasn't been received from a lookup operation, its DN needs to be + * initialized and it must have been put in update mode ( * {@link DirContextAdapter#setUpdateMode(boolean)}). *

    * Typical use of this method would be as follows: - * + * *

     	 * public void update(Person person) {
     	 * 	DirContextOperations ctx = ldapOperations.lookupContext(person.getDn());
    -	 * 
    +	 *
     	 * 	ctx.setAttributeValue("description", person.getDescription());
     	 * 	ctx.setAttributeValue("telephoneNumber", person.getPhone());
     	 * 	// More modifications here
    -	 * 
    +	 *
     	 * 	ldapOperations.modifyAttributes(ctx);
     	 * }
     	 * 
    - * * @param ctx the DirContextOperations instance to use in the update. - * @throws IllegalStateException if the supplied instance is not in update - * mode or has not been properly initialized. + * @throws IllegalStateException if the supplied instance is not in update mode or has + * not been properly initialized. * @throws NamingException if any other error occurs. * @since 1.2 * @see #lookupContext(Name) @@ -1262,271 +1113,261 @@ public interface LdapOperations { void modifyAttributes(DirContextOperations ctx) throws IllegalStateException, NamingException; /** - * Bind the data in the supplied context in the tree. All specified - * attributes ctxin will be bound to the DN set on ctx. + * Bind the data in the supplied context in the tree. All specified attributes + * ctxin will be bound to the DN set on ctx. *

    * Example:
    - * + * *

     	 * DirContextOperations ctx = new DirContextAdapter(dn);
     	 * ctx.setAttributeValue("cn", "john doe");
     	 * ctx.setAttributeValue("description", "some description");
     	 * //More initialization here.
    -	 * 
    +	 *
     	 * ldapTemplate.bind(ctx);
     	 * 
    * @param ctx the context to bind - * @throws IllegalStateException if no DN is set or if the instance is in - * update mode. + * @throws IllegalStateException if no DN is set or if the instance is in update mode. * @since 1.3 */ void bind(DirContextOperations ctx); /** - * Remove an entry and replace it with a new one. The attributes used to - * create the entry are retrieved from the ctx parameter. This - * method assumes that the specified context already exists - if not it will - * fail. The entry will be bound to the DN set on ctx. + * Remove an entry and replace it with a new one. The attributes used to create the + * entry are retrieved from the ctx parameter. This method assumes that + * the specified context already exists - if not it will fail. The entry will be bound + * to the DN set on ctx. *

    * Example:
    - * + * *

     	 * DirContextOperations ctx = new DirContextAdapter(dn);
     	 * ctx.setAttributeValue("cn", "john doe");
     	 * ctx.setAttributeValue("description", "some description");
     	 * //More initialization here.
    -	 * 
    +	 *
     	 * ldapTemplate.rebind(ctx);
     	 * 
    * @param ctx the context to rebind - * @throws IllegalStateException if no DN is set or if the instance is in - * update mode. + * @throws IllegalStateException if no DN is set or if the instance is in update mode. * @since 1.3 */ void rebind(DirContextOperations ctx); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. *

    * Example:
    - * + * *

     	 * AndFilter filter = new AndFilter();
     	 * filter.and("objectclass", "person").and("uid", userId);
     	 * boolean authenticated = ldapTemplate.authenticate(LdapUtils.emptyLdapName(), filter.toString(), password);
     	 * 
    - * * @param base the DN to use as the base of the search. * @param filter the search filter - must result in a unique result. * @param password the password to use for authentication. - * @return true if the authentication was successful, - * false otherwise. + * @return true if the authentication was successful, false + * otherwise. * @since 1.3 - * @deprecated use {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} - * or {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} + * @deprecated use + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} or + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} */ boolean authenticate(Name base, String filter, String password); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. *

    * Example:
    - * + * *

     	 * AndFilter filter = new AndFilter();
     	 * filter.and("objectclass", "person").and("uid", userId);
     	 * boolean authenticated = ldapTemplate.authenticate(LdapUtils.emptyLdapName(), filter.toString(), password);
     	 * 
    - * * @param base the DN to use as the base of the search. * @param filter the search filter - must result in a unique result. * @param password the password to use for authentication. - * @return true if the authentication was successful, - * false otherwise. + * @return true if the authentication was successful, false + * otherwise. * @since 1.3 - * @deprecated use {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} - * or {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} + * @deprecated use + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} or + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} */ boolean authenticate(String base, String filter, String password); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. The resulting DirContext instance is then used as input to the - * supplied {@link AuthenticatedLdapEntryContextCallback} to perform any - * additional LDAP operations against the authenticated DirContext. - * + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. + * The resulting DirContext instance is then used as input to the supplied + * {@link AuthenticatedLdapEntryContextCallback} to perform any additional LDAP + * operations against the authenticated DirContext. * @param base the DN to use as the base of the search. * @param filter the search filter - must result in a unique result. * @param password the password to use for authentication. - * @param callback the callback to that will be called to perform operations - * on the DirContext authenticated with the found user. - * @return true if the authentication was successful, - * false otherwise. + * @param callback the callback to that will be called to perform operations on the + * DirContext authenticated with the found user. + * @return true if the authentication was successful, false + * otherwise. * @see #authenticate(Name, String, String) * @since 1.3 - * @deprecated use {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} - * or {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} + * @deprecated use + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} or + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} */ boolean authenticate(Name base, String filter, String password, AuthenticatedLdapEntryContextCallback callback); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. The resulting DirContext instance is then used as input to the - * supplied {@link AuthenticatedLdapEntryContextCallback} to perform any - * additional LDAP operations against the authenticated DirContext. - * + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. + * The resulting DirContext instance is then used as input to the supplied + * {@link AuthenticatedLdapEntryContextCallback} to perform any additional LDAP + * operations against the authenticated DirContext. * @param base the DN to use as the base of the search. * @param filter the search filter - must result in a unique result. * @param password the password to use for authentication. - * @param callback the callback to that will be called to perform operations - * on the DirContext authenticated with the found user. - * @return true if the authentication was successful, - * false otherwise. + * @param callback the callback to that will be called to perform operations on the + * DirContext authenticated with the found user. + * @return true if the authentication was successful, false + * otherwise. * @see #authenticate(String, String, String) * @since 1.3 - * @deprecated use {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} - * or {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} + * @deprecated use + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} or + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} */ boolean authenticate(String base, String filter, String password, AuthenticatedLdapEntryContextCallback callback); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. The resulting DirContext instance is then used as input to the - * supplied {@link AuthenticatedLdapEntryContextCallback} to perform any - * additional LDAP operations against the authenticated DirContext. If an - * exception is caught, the same exception is passed on to the given - * {@link AuthenticationErrorCallback}. This enables the caller to provide a - * callback that, for example, collects the exception for later processing. - * + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. + * The resulting DirContext instance is then used as input to the supplied + * {@link AuthenticatedLdapEntryContextCallback} to perform any additional LDAP + * operations against the authenticated DirContext. If an exception is caught, the + * same exception is passed on to the given {@link AuthenticationErrorCallback}. This + * enables the caller to provide a callback that, for example, collects the exception + * for later processing. * @param base the DN to use as the base of the search. * @param filter the search filter - must result in a unique result. * @param password the password to use for authentication. - * @param callback the callback that will be called to perform operations - * on the DirContext authenticated with the found user. + * @param callback the callback that will be called to perform operations on the + * DirContext authenticated with the found user. * @param errorCallback the callback that will be called if an exception is caught. - * @return true if the authentication was successful, - * false otherwise. + * @return true if the authentication was successful, false + * otherwise. * @see #authenticate(Name, String, String, AuthenticatedLdapEntryContextCallback) * @since 1.3.1 - * @deprecated use {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} - * or {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} + * @deprecated use + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} or + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} */ - boolean authenticate(Name base, String filter, String password, - AuthenticatedLdapEntryContextCallback callback, + boolean authenticate(Name base, String filter, String password, AuthenticatedLdapEntryContextCallback callback, AuthenticationErrorCallback errorCallback); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. The resulting DirContext instance is then used as input to the - * supplied {@link AuthenticatedLdapEntryContextCallback} to perform any - * additional LDAP operations against the authenticated DirContext. If an - * exception is caught, the same exception is passed on to the given - * {@link AuthenticationErrorCallback}. This enables the caller to provide a - * callback that, for example, collects the exception for later processing. - * + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. + * The resulting DirContext instance is then used as input to the supplied + * {@link AuthenticatedLdapEntryContextCallback} to perform any additional LDAP + * operations against the authenticated DirContext. If an exception is caught, the + * same exception is passed on to the given {@link AuthenticationErrorCallback}. This + * enables the caller to provide a callback that, for example, collects the exception + * for later processing. * @param base the DN to use as the base of the search. * @param filter the search filter - must result in a unique result. * @param password the password to use for authentication. - * @param callback the callback that will be called to perform operations - * on the DirContext authenticated with the found user. + * @param callback the callback that will be called to perform operations on the + * DirContext authenticated with the found user. * @param errorCallback the callback that will be called if an exception is caught. - * @return true if the authentication was successful, - * false otherwise. + * @return true if the authentication was successful, false + * otherwise. * @see #authenticate(String, String, String, AuthenticatedLdapEntryContextCallback) * @since 1.3.1 - * @deprecated use {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} - * or {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} + * @deprecated use + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} or + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} */ - boolean authenticate(String base, String filter, String password, - AuthenticatedLdapEntryContextCallback callback, + boolean authenticate(String base, String filter, String password, AuthenticatedLdapEntryContextCallback callback, AuthenticationErrorCallback errorCallback); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. If an exception is caught, the same exception is passed on to the given - * {@link AuthenticationErrorCallback}. This enables the caller to provide a - * callback that, for example, collects the exception for later processing. - * + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. If + * an exception is caught, the same exception is passed on to the given + * {@link AuthenticationErrorCallback}. This enables the caller to provide a callback + * that, for example, collects the exception for later processing. * @param base the DN to use as the base of the search. * @param filter the search filter - must result in a unique result. * @param password the password to use for authentication. * @param errorCallback the callback that will be called if an exception is caught. - * @return true if the authentication was successful, - * false otherwise. - * @see #authenticate(Name, String, String, AuthenticatedLdapEntryContextCallback, AuthenticationErrorCallback) + * @return true if the authentication was successful, false + * otherwise. + * @see #authenticate(Name, String, String, AuthenticatedLdapEntryContextCallback, + * AuthenticationErrorCallback) * @since 1.3.1 - * @deprecated use {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} - * or {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} + * @deprecated use + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} or + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} */ - boolean authenticate(Name base, String filter, String password, - AuthenticationErrorCallback errorCallback); + boolean authenticate(Name base, String filter, String password, AuthenticationErrorCallback errorCallback); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. If an exception is caught, the same exception is passed on to the given - * {@link AuthenticationErrorCallback}. This enables the caller to provide a - * callback that, for example, collects the exception for later processing. - * + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. If + * an exception is caught, the same exception is passed on to the given + * {@link AuthenticationErrorCallback}. This enables the caller to provide a callback + * that, for example, collects the exception for later processing. * @param base the DN to use as the base of the search. * @param filter the search filter - must result in a unique result. * @param password the password to use for authentication. * @param errorCallback the callback that will be called if an exception is caught. - * @return true if the authentication was successful, - * false otherwise. + * @return true if the authentication was successful, false + * otherwise. * @throws IncorrectResultSizeDataAccessException if more than one users were found * @since 1.3.1 - * @deprecated use {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} - * or {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} + * @deprecated use + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String)} or + * {@link #authenticate(org.springframework.ldap.query.LdapQuery, String, AuthenticatedLdapEntryContextMapper)} */ - boolean authenticate(String base, String filter, String password, - AuthenticationErrorCallback errorCallback); - + boolean authenticate(String base, String filter, String password, AuthenticationErrorCallback errorCallback); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied LdapQuery; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied LdapQuery; use the DN of the found entry + * together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. *

    - * Note: This method differs from the older authenticate methods in that encountered - * exceptions are thrown rather than supplied to a callback for handling. + * Note: This method differs from the older authenticate methods in that + * encountered exceptions are thrown rather than supplied to a callback for handling. *

    - * * @param query the LdapQuery specifying the details of the search. * @param password the password to use for authentication. - * @param mapper the callback that will be called to perform operations - * on the DirContext authenticated with the found user. - * false otherwise. + * @param mapper the callback that will be called to perform operations on the + * DirContext authenticated with the found user. false otherwise. * @return the result from the callback. * @throws IncorrectResultSizeDataAccessException if more than one users were found - * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was found + * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was + * found * @throws NamingException if something went wrong in authentication. * * @since 2.0 @@ -1535,23 +1376,23 @@ public interface LdapOperations { T authenticate(LdapQuery query, String password, AuthenticatedLdapEntryContextMapper mapper); /** - * Utility method to perform a simple LDAP 'bind' authentication. Search for - * the LDAP entry to authenticate using the supplied base DN and filter; use - * the DN of the found entry together with the password as input to - * {@link ContextSource#getContext(String, String)}, thus authenticating the - * entry. If an exception is caught, the same exception is passed on to the given - * {@link AuthenticationErrorCallback}. This enables the caller to provide a - * callback that, for example, collects the exception for later processing. + * Utility method to perform a simple LDAP 'bind' authentication. Search for the LDAP + * entry to authenticate using the supplied base DN and filter; use the DN of the + * found entry together with the password as input to + * {@link ContextSource#getContext(String, String)}, thus authenticating the entry. If + * an exception is caught, the same exception is passed on to the given + * {@link AuthenticationErrorCallback}. This enables the caller to provide a callback + * that, for example, collects the exception for later processing. *

    - * Note: This method differs from the older authenticate methods in that encountered - * exceptions are thrown rather than supplied to a callback for handling. + * Note: This method differs from the older authenticate methods in that + * encountered exceptions are thrown rather than supplied to a callback for handling. *

    - * * @param query the LdapQuery specifying the details of the search. - * @param password the password to use for authentication. - * false otherwise. + * @param password the password to use for authentication. false + * otherwise. * @throws IncorrectResultSizeDataAccessException if more than one users were found - * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was found + * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was + * found * @throws NamingException if something went wrong in authentication. * * @since 2.0 @@ -1559,76 +1400,70 @@ public interface LdapOperations { */ void authenticate(LdapQuery query, String password); - /** - * Perform a search for a unique entry matching the specified search - * criteria and return the found object. If no entry is found or if there - * are more than one matching entry, an - * {@link IncorrectResultSizeDataAccessException} is thrown. + * Perform a search for a unique entry matching the specified search criteria and + * return the found object. If no entry is found or if there are more than one + * matching entry, an {@link IncorrectResultSizeDataAccessException} is thrown. * @param base the DN to use as the base of the search. * @param filter the search filter. * @param mapper the mapper to use for the search. - * @return the single object returned by the mapper that matches the search - * criteria. - * @throws IncorrectResultSizeDataAccessException if the result is not one unique entry + * @return the single object returned by the mapper that matches the search criteria. + * @throws IncorrectResultSizeDataAccessException if the result is not one unique + * entry * @since 1.3 */ T searchForObject(Name base, String filter, ContextMapper mapper); /** - * Perform a search for a unique entry matching the specified search - * criteria and return the found object. If no entry is found or if there - * are more than one matching entry, an - * {@link IncorrectResultSizeDataAccessException} is thrown. + * Perform a search for a unique entry matching the specified search criteria and + * return the found object. If no entry is found or if there are more than one + * matching entry, an {@link IncorrectResultSizeDataAccessException} is thrown. * @param base the DN to use as the base of the search. * @param filter the search filter. * @param searchControls the searchControls to use for the search. * @param mapper the mapper to use for the search. - * @return the single object returned by the mapper that matches the search - * criteria. - * @throws IncorrectResultSizeDataAccessException if the result is not one unique entry + * @return the single object returned by the mapper that matches the search criteria. + * @throws IncorrectResultSizeDataAccessException if the result is not one unique + * entry * @since 2.0 */ T searchForObject(Name base, String filter, SearchControls searchControls, ContextMapper mapper); /** - * Perform a search for a unique entry matching the specified search - * criteria and return the found object. If no entry is found or if there - * are more than one matching entry, an - * {@link IncorrectResultSizeDataAccessException} is thrown. + * Perform a search for a unique entry matching the specified search criteria and + * return the found object. If no entry is found or if there are more than one + * matching entry, an {@link IncorrectResultSizeDataAccessException} is thrown. * @param base the DN to use as the base of the search. * @param filter the search filter. * @param searchControls the searchControls to use for the search. * @param mapper the mapper to use for the search. - * @return the single object returned by the mapper that matches the search - * criteria. - * @throws IncorrectResultSizeDataAccessException if the result is not one unique entry + * @return the single object returned by the mapper that matches the search criteria. + * @throws IncorrectResultSizeDataAccessException if the result is not one unique + * entry * @since 2.0 */ T searchForObject(String base, String filter, SearchControls searchControls, ContextMapper mapper); /** - * Perform a search for a unique entry matching the specified search - * criteria and return the found object. If no entry is found or if there - * are more than one matching entry, an - * {@link IncorrectResultSizeDataAccessException} is thrown. + * Perform a search for a unique entry matching the specified search criteria and + * return the found object. If no entry is found or if there are more than one + * matching entry, an {@link IncorrectResultSizeDataAccessException} is thrown. * @param base the DN to use as the base of the search. * @param filter the search filter. * @param mapper the mapper to use for the search. - * @return the single object returned by the mapper that matches the search - * criteria. - * @throws IncorrectResultSizeDataAccessException if the result is not one unique entry + * @return the single object returned by the mapper that matches the search criteria. + * @throws IncorrectResultSizeDataAccessException if the result is not one unique + * entry * @since 1.3 */ T searchForObject(String base, String filter, ContextMapper mapper); /** - * Perform a search with parameters from the specified LdapQuery. All found objects will be supplied to the - * NameClassPairCallbackHandler for processing. - * + * Perform a search with parameters from the specified LdapQuery. All found objects + * will be supplied to the NameClassPairCallbackHandler for processing. * @param query the LDAP query specification. - * @param callbackHandler the NameClassPairCallbackHandler to supply all found entries to. - * + * @param callbackHandler the NameClassPairCallbackHandler to supply all + * found entries to. * @throws NamingException if any error occurs. * @since 2.0 * @see org.springframework.ldap.query.LdapQueryBuilder @@ -1637,14 +1472,13 @@ public interface LdapOperations { void search(LdapQuery query, NameClassPairCallbackHandler callbackHandler); /** - * Perform a search with parameters from the specified LdapQuery. All found objects will be supplied to the - * ContextMapper for processing, and all returned objects will be collected in a list to be returned. - * + * Perform a search with parameters from the specified LdapQuery. All found objects + * will be supplied to the ContextMapper for processing, and all returned + * objects will be collected in a list to be returned. * @param query the LDAP query specification. * @param mapper the ContextMapper to supply all found entries to. * @return a List containing all entries received from the * ContextMapper. - * * @throws NamingException if any error occurs. * @since 2.0 * @see org.springframework.ldap.query.LdapQueryBuilder @@ -1652,15 +1486,13 @@ public interface LdapOperations { List search(LdapQuery query, ContextMapper mapper); /** - * Perform a search with parameters from the specified LdapQuery. The Attributes of the found entries will be - * supplied to the AttributesMapper for processing, and all - * returned objects will be collected in a list to be returned. - * + * Perform a search with parameters from the specified LdapQuery. The Attributes of + * the found entries will be supplied to the AttributesMapper for + * processing, and all returned objects will be collected in a list to be returned. * @param query the LDAP query specification. * @param mapper the Attributes to supply all found Attributes to. * @return a List containing all entries received from the * Attributes. - * * @throws NamingException if any error occurs. * @since 2.0 * @see org.springframework.ldap.query.LdapQueryBuilder @@ -1668,42 +1500,40 @@ public interface LdapOperations { List search(LdapQuery query, AttributesMapper mapper); /** - * Perform a search for a unique entry matching the specified LDAP - * query and return the found entry as a DirContextOperation instance. If no entry is found or if there - * are more than one matching entry, an - * {@link IncorrectResultSizeDataAccessException} is thrown. + * Perform a search for a unique entry matching the specified LDAP query and return + * the found entry as a DirContextOperation instance. If no entry is found or if there + * are more than one matching entry, an {@link IncorrectResultSizeDataAccessException} + * is thrown. * @param query the LDAP query specification. * @return the single entry matching the query as a DirContextOperations instance. - * @throws IncorrectResultSizeDataAccessException if the result is not one unique entry + * @throws IncorrectResultSizeDataAccessException if the result is not one unique + * entry * @since 2.0 * @see org.springframework.ldap.query.LdapQueryBuilder */ DirContextOperations searchForContext(LdapQuery query); /** - * Perform a search for a unique entry matching the specified LDAP - * query and return the found object. If no entry is found or if there - * are more than one matching entry, an - * {@link IncorrectResultSizeDataAccessException} is thrown. + * Perform a search for a unique entry matching the specified LDAP query and return + * the found object. If no entry is found or if there are more than one matching + * entry, an {@link IncorrectResultSizeDataAccessException} is thrown. * @param query the LDAP query specification. - * @return the single object returned by the mapper that matches the search - * criteria. - * @throws IncorrectResultSizeDataAccessException if the result is not one unique entry + * @return the single object returned by the mapper that matches the search criteria. + * @throws IncorrectResultSizeDataAccessException if the result is not one unique + * entry * @since 2.0 * @see org.springframework.ldap.query.LdapQueryBuilder */ T searchForObject(LdapQuery query, ContextMapper mapper); /** - * Perform a search with parameters from the specified LdapQuery. The Attributes of the found entries will be - * supplied to the AttributesMapper for processing, and all - * returned objects will be collected in a list to be returned. - * + * Perform a search with parameters from the specified LdapQuery. The Attributes of + * the found entries will be supplied to the AttributesMapper for + * processing, and all returned objects will be collected in a list to be returned. * @param query the LDAP query specification. * @param mapper the Attributes to supply all found Attributes to. * @return a Stream of all entries received from the * Attributes. - * * @throws NamingException if any error occurs. * @since 3.0 * @see org.springframework.ldap.query.LdapQueryBuilder @@ -1711,14 +1541,13 @@ public interface LdapOperations { Stream searchForStream(LdapQuery query, AttributesMapper mapper); /** - * Perform a search with parameters from the specified LdapQuery. All found objects will be supplied to the - * ContextMapper for processing, and all returned objects will be collected in a list to be returned. - * + * Perform a search with parameters from the specified LdapQuery. All found objects + * will be supplied to the ContextMapper for processing, and all returned + * objects will be collected in a list to be returned. * @param query the LDAP query specification. * @param mapper the ContextMapper to supply all found entries to. * @return a Stream of all entries received from the * ContextMapper. - * * @throws NamingException if any error occurs. * @since 3.0 * @see org.springframework.ldap.query.LdapQueryBuilder @@ -1726,135 +1555,135 @@ public interface LdapOperations { Stream searchForStream(LdapQuery query, ContextMapper mapper); /** - * Read a named entry from the LDAP directory. The referenced class must have object-directory mapping metadata - * specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. - * + * Read a named entry from the LDAP directory. The referenced class must have + * object-directory mapping metadata specified using + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. * @param The Java type to return * @param dn The distinguished name of the entry to read from the LDAP directory. * @param clazz The Java type to return * @return The entry as read from the directory - * * @throws org.springframework.ldap.NamingException on error. * @since 2.0 */ T findByDn(Name dn, Class clazz); /** - * Create the given entry in the LDAP directory. The referenced class must have object-directory mapping metadata - * specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. - * If the field annotated with {@link org.springframework.ldap.odm.annotations.Id} - * is set in the object, this will be used as the distinguished name of the new entry. If no explicit DN is specified, - * an attempt will be made to calculate the name from fields annotated with {@link org.springframework.ldap.odm.annotations.DnAttribute}. + * Create the given entry in the LDAP directory. The referenced class must have + * object-directory mapping metadata specified using + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. + * If the field annotated with {@link org.springframework.ldap.odm.annotations.Id} is + * set in the object, this will be used as the distinguished name of the new entry. If + * no explicit DN is specified, an attempt will be made to calculate the name from + * fields annotated with {@link org.springframework.ldap.odm.annotations.DnAttribute}. * If an id can be calculated, this will be populated in the supplied object. - * - * @param entry The entry to be create, it must not be null or already exist in the directory. - * + * @param entry The entry to be create, it must not be null or already exist + * in the directory. * @throws org.springframework.ldap.NamingException on error. - * @throws IllegalArgumentException if the entry is null or on failure to determine the distinguished name. + * @throws IllegalArgumentException if the entry is null or on failure to determine + * the distinguished name. * @since 2.0 */ void create(Object entry); /** - * Update the given entry in the LDAP directory. The referenced class must have object-directory mapping metadata - * specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. - * If the distinguished name is not explicitly specified (i.e. if the - * field annotated with {@link org.springframework.ldap.odm.annotations.Id} is null), - * an attempt will be made to calculate the name from fields annotated with - * {@link org.springframework.ldap.odm.annotations.DnAttribute}. If the {@link org.springframework.ldap.odm.annotations.Id} - * field and the calculated DN is different, the entry will be moved (i.e., an {@link #unbind(javax.naming.Name)} - * followed by a {@link #bind(DirContextOperations)}. Otherwise - * the current data of the entry will be read from the directory and a {@link #modifyAttributes(DirContextOperations)} - * operation will be performed using the ModificationItems resulting from the changes of the - * entry compared to its current state in the directory. - * If the id of the entry has changed, i.e. if it wasn't specified from the beginning, or if it is calculated to - * have changed, the new value will be populated in the supplied object. - * + * Update the given entry in the LDAP directory. The referenced class must have + * object-directory mapping metadata specified using + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. + * If the distinguished name is not explicitly specified (i.e. if the field annotated + * with {@link org.springframework.ldap.odm.annotations.Id} is null), an + * attempt will be made to calculate the name from fields annotated with + * {@link org.springframework.ldap.odm.annotations.DnAttribute}. If the + * {@link org.springframework.ldap.odm.annotations.Id} field and the calculated DN is + * different, the entry will be moved (i.e., an + * {@link #unbind(javax.naming.Name)} followed by a + * {@link #bind(DirContextOperations)}. Otherwise the current data of the entry will + * be read from the directory and a {@link #modifyAttributes(DirContextOperations)} + * operation will be performed using the ModificationItems resulting from + * the changes of the entry compared to its current state in the directory. If the id + * of the entry has changed, i.e. if it wasn't specified from the beginning, or if it + * is calculated to have changed, the new value will be populated in the supplied + * object. * @param entry The entry to update, it must already exist in the directory. - * * @throws org.springframework.ldap.NamingException on error. - * @throws IllegalArgumentException if the entry is null or on failure to determine the distinguished name. + * @throws IllegalArgumentException if the entry is null or on failure to determine + * the distinguished name. * @since 2.0 */ void update(Object entry); /** - * Delete an entry from the LDAP directory. The referenced class must have object-directory mapping metadata - * specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. - * If the field annotated with {@link org.springframework.ldap.odm.annotations.Id} - * is set in the object, this will be used as the distinguished name of the new entry. If no explicit DN is specified, - * an attempt will be made to calculate the name from fields annotated with {@link org.springframework.ldap.odm.annotations.DnAttribute}. - * + * Delete an entry from the LDAP directory. The referenced class must have + * object-directory mapping metadata specified using + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. + * If the field annotated with {@link org.springframework.ldap.odm.annotations.Id} is + * set in the object, this will be used as the distinguished name of the new entry. If + * no explicit DN is specified, an attempt will be made to calculate the name from + * fields annotated with {@link org.springframework.ldap.odm.annotations.DnAttribute}. * @param entry The entry to delete, it must already exist in the directory. - * * @throws org.springframework.ldap.NamingException on error. - * @throws IllegalArgumentException if the entry is null or on failure to determine the distinguished name. + * @throws IllegalArgumentException if the entry is null or on failure to determine + * the distinguished name. * @since 2.0 */ void delete(Object entry); /** - * Find all entries in the LDAP directory of a given type. The referenced class must have object-directory mapping metadata - * specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. - * + * Find all entries in the LDAP directory of a given type. The referenced class must + * have object-directory mapping metadata specified using + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. * @param The Java type to return * @param clazz The Java type to return - * @return All entries that are of the type represented by the given - * Java class - * + * @return All entries that are of the type represented by the given Java class * @throws org.springframework.ldap.NamingException on error. * @since 2.0 */ List findAll(Class clazz); /** - * Find all entries in the LDAP directory of a given type. The referenced class must have object-directory mapping metadata - * specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. - * + * Find all entries in the LDAP directory of a given type. The referenced class must + * have object-directory mapping metadata specified using + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. * @param The Java type to return * @param base The root of the sub-tree at which to begin the search. - * @param searchControls The search controls of the search. Note that the 'returned attributes' parameter should - * typically not be tampered with, since that may affect the attributes populated in returned entries. + * @param searchControls The search controls of the search. Note that the 'returned + * attributes' parameter should typically not be tampered with, since that may affect + * the attributes populated in returned entries. * @param clazz The Java type to return - * @return All entries that are of the type represented by the given - * Java class - * + * @return All entries that are of the type represented by the given Java class * @throws org.springframework.ldap.NamingException on error. * @since 2.0 */ List findAll(Name base, SearchControls searchControls, Class clazz); /** - * Find all entries in the LDAP directory of a given type that matches the specified filter. - * The referenced class must have object-directory mapping metadata specified using - * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. - * + * Find all entries in the LDAP directory of a given type that matches the specified + * filter. The referenced class must have object-directory mapping metadata specified + * using {@link org.springframework.ldap.odm.annotations.Entry} and associated + * annotations. * @param The Java type to return * @param base The root of the sub-tree at which to begin the search. * @param filter The search filter. - * @param searchControls The search controls of the search. Note that the 'returned attributes' parameter should - * typically not be tampered with, since that may affect the attributes populated in returned entries. + * @param searchControls The search controls of the search. Note that the 'returned + * attributes' parameter should typically not be tampered with, since that may affect + * the attributes populated in returned entries. * @param clazz The Java type to return - * @return All entries that are of the type represented by the given - * Java class - * + * @return All entries that are of the type represented by the given Java class * @throws org.springframework.ldap.NamingException on error. * @since 2.0 */ List find(Name base, Filter filter, SearchControls searchControls, Class clazz); /** - * Search for entries in the LDAP directory. The referenced class must have object-directory - * mapping metadata specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. + * Search for entries in the LDAP directory. The referenced class must have + * object-directory mapping metadata specified using + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. *

    - * Only those entries that both match the query search filter and - * are represented by the given Java class are returned. - * + * Only those entries that both match the query search filter and are represented by + * the given Java class are returned. * @param The Java type to return * @param query the LDAP query specification * @param clazz The Java type to return * @return All matching entries. - * * @throws org.springframework.ldap.NamingException on error. * @see org.springframework.ldap.query.LdapQueryBuilder * @since 2.0 @@ -1862,8 +1691,9 @@ public interface LdapOperations { List find(LdapQuery query, Class clazz); /** - * Search for objects in the directory tree matching the specified LdapQuery, expecting to find exactly one match. - * The referenced class must have object-directory mapping metadata specified using + * Search for objects in the directory tree matching the specified LdapQuery, + * expecting to find exactly one match. The referenced class must have + * object-directory mapping metadata specified using * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. * @param query the LDAP query specification * @param clazz The Java type to return @@ -1871,23 +1701,24 @@ public interface LdapOperations { * @return The single entry matching the search specification. * @since 2.0 * @throws org.springframework.ldap.NamingException on LDAP error. - * @throws org.springframework.dao.EmptyResultDataAccessException if no matching entry can be found - * @throws IncorrectResultSizeDataAccessException if more than one matching entry is found + * @throws org.springframework.dao.EmptyResultDataAccessException if no matching entry + * can be found + * @throws IncorrectResultSizeDataAccessException if more than one matching entry is + * found */ T findOne(LdapQuery query, Class clazz); /** - * Search for entries in the LDAP directory. The referenced class must have object-directory - * mapping metadata specified using {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. + * Search for entries in the LDAP directory. The referenced class must have + * object-directory mapping metadata specified using + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. *

    - * Only those entries that both match the query search filter and - * are represented by the given Java class are returned. - * + * Only those entries that both match the query search filter and are represented by + * the given Java class are returned. * @param The Java type to return * @param query the LDAP query specification * @param clazz The Java type to return * @return All matching entries. - * * @throws org.springframework.ldap.NamingException on error. * @see org.springframework.ldap.query.LdapQueryBuilder * @since 3.0 @@ -1896,9 +1727,9 @@ public interface LdapOperations { /** * Get the configured ObjectDirectoryMapper. For internal use. - * * @return the configured ObjectDirectoryMapper. * @since 2.0 */ ObjectDirectoryMapper getObjectDirectoryMapper(); + } diff --git a/core/src/main/java/org/springframework/ldap/core/LdapRdn.java b/core/src/main/java/org/springframework/ldap/core/LdapRdn.java index b248b05c..4991e3d2 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapRdn.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapRdn.java @@ -31,15 +31,17 @@ import java.util.Set; /** * Datatype for a LDAP name, a part of a path. - * + * * The name: uid=adam.skogman Key: uid Value: adam.skogman - * + * * @author Adam Skogman * @author Mattias Hellborg Arthursson * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. */ public class LdapRdn implements Serializable, Comparable { + private static final long serialVersionUID = 5681397547245228750L; + private static final int DEFAULT_BUFFER_SIZE = 100; private Map components = new LinkedHashMap(); @@ -52,7 +54,6 @@ public class LdapRdn implements Serializable, Comparable { /** * Parse the supplied string and construct this instance accordingly. - * * @param string the string to parse. */ public LdapRdn(String string) { @@ -72,7 +73,6 @@ public class LdapRdn implements Serializable, Comparable { /** * Construct an LdapRdn using the supplied key and value. - * * @param key the attribute name. * @param value the attribute value. */ @@ -82,7 +82,6 @@ public class LdapRdn implements Serializable, Comparable { /** * Add an LdapRdnComponent to this LdapRdn. - * * @param rdnComponent the LdapRdnComponent to add.s */ public void addComponent(LdapRdnComponent rdnComponent) { @@ -91,7 +90,6 @@ public class LdapRdn implements Serializable, Comparable { /** * Gets all components in this LdapRdn. - * * @return the List of all LdapRdnComponents composing this LdapRdn. */ public List getComponents() { @@ -100,12 +98,11 @@ public class LdapRdn implements Serializable, Comparable { /** * Gets the first LdapRdnComponent of this LdapRdn. - * * @return The first LdapRdnComponent of this LdapRdn. * @throws IndexOutOfBoundsException if there are no components in this Rdn. */ public LdapRdnComponent getComponent() { - if(components.size() == 0) { + if (components.size() == 0) { throw new IndexOutOfBoundsException("No components"); } @@ -114,13 +111,12 @@ public class LdapRdn implements Serializable, Comparable { /** * Get the LdapRdnComponent at index idx. - * * @param idx the 0-based index of the component to get. * @return the LdapRdnComponent at index idx. * @throws IndexOutOfBoundsException if there are no components in this Rdn. */ public LdapRdnComponent getComponent(int idx) { - if(idx >= components.size()) { + if (idx >= components.size()) { throw new IndexOutOfBoundsException(); } @@ -129,7 +125,6 @@ public class LdapRdn implements Serializable, Comparable { /** * Get a properly rfc2253-encoded String representation of this LdapRdn. - * * @return an escaped String corresponding to this LdapRdn. * @throws IndexOutOfBoundsException if there are no components in this Rdn. */ @@ -151,7 +146,6 @@ public class LdapRdn implements Serializable, Comparable { /** * Get a String representation of this LdapRdn for use in urls. - * * @return a String representation of this LdapRdn for use in urls. */ public String encodeUrl() { @@ -169,27 +163,25 @@ public class LdapRdn implements Serializable, Comparable { /** * Compare this LdapRdn to another object. - * * @param obj the object to compare to. - * @throws ClassCastException if the supplied object is not an LdapRdn - * instance. + * @throws ClassCastException if the supplied object is not an LdapRdn instance. */ public int compareTo(Object obj) { LdapRdn that = (LdapRdn) obj; - if(this.components.size() != that.components.size()) { + if (this.components.size() != that.components.size()) { return this.components.size() - that.components.size(); } - Set> theseEntries = this.components.entrySet(); + Set> theseEntries = this.components.entrySet(); for (Map.Entry oneEntry : theseEntries) { LdapRdnComponent thatEntry = that.components.get(oneEntry.getKey()); - if(thatEntry == null) { + if (thatEntry == null) { return -1; } int compared = oneEntry.getValue().compareTo(thatEntry); - if(compared != 0) { + if (compared != 0) { return compared; } } @@ -199,7 +191,7 @@ public class LdapRdn implements Serializable, Comparable { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { @@ -209,13 +201,13 @@ public class LdapRdn implements Serializable, Comparable { LdapRdn that = (LdapRdn) obj; - if(this.components.size() != that.components.size()) { + if (this.components.size() != that.components.size()) { return false; } - Set> theseEntries = this.components.entrySet(); + Set> theseEntries = this.components.entrySet(); for (Map.Entry oneEntry : theseEntries) { - if(!oneEntry.getValue().equals(that.components.get(oneEntry.getKey()))) { + if (!oneEntry.getValue().equals(that.components.get(oneEntry.getKey()))) { return false; } } @@ -225,7 +217,7 @@ public class LdapRdn implements Serializable, Comparable { /* * (non-Javadoc) - * + * * @see java.lang.Object#hashCode() */ public int hashCode() { @@ -234,7 +226,7 @@ public class LdapRdn implements Serializable, Comparable { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ public String toString() { @@ -242,11 +234,9 @@ public class LdapRdn implements Serializable, Comparable { } /** - * Get the value of this LdapRdn. Note that if this Rdn is multi-value the - * first value will be returned. E.g. for the Rdn - * cn=john doe+sn=doe, the return value would be - * john doe. - * + * Get the value of this LdapRdn. Note that if this Rdn is multi-value the first value + * will be returned. E.g. for the Rdn cn=john doe+sn=doe, the return + * value would be john doe. * @return the (first) value of this LdapRdn. * @throws IndexOutOfBoundsException if there are no components in this Rdn. */ @@ -255,11 +245,9 @@ public class LdapRdn implements Serializable, Comparable { } /** - * Get the key of this LdapRdn. Note that if this Rdn is multi-value the - * first key will be returned. E.g. for the Rdn - * cn=john doe+sn=doe, the return value would be - * cn. - * + * Get the key of this LdapRdn. Note that if this Rdn is multi-value the first key + * will be returned. E.g. for the Rdn cn=john doe+sn=doe, the return + * value would be cn. * @return the (first) key of this LdapRdn. * @throws IndexOutOfBoundsException if there are no components in this Rdn. */ @@ -268,13 +256,10 @@ public class LdapRdn implements Serializable, Comparable { } /** - * Get the value of the LdapComponent with the specified key (Attribute - * name). - * + * Get the value of the LdapComponent with the specified key (Attribute name). * @param key the key * @return the value. - * @throws IllegalArgumentException if there is no component with the - * specified key. + * @throws IllegalArgumentException if there is no component with the specified key. */ public String getValue(String key) { for (Iterator iter = components.values().iterator(); iter.hasNext();) { @@ -288,21 +273,23 @@ public class LdapRdn implements Serializable, Comparable { } /** - * Create an immutable copy of this instance. It will not be possible to add - * or remove components or modify the keys and values of these components. - * + * Create an immutable copy of this instance. It will not be possible to add or remove + * components or modify the keys and values of these components. * @return an immutable copy of this instance. * @since 1.3 */ public LdapRdn immutableLdapRdn() { - Map mapWithImmutableRdns = new LinkedHashMap(components.size()); + Map mapWithImmutableRdns = new LinkedHashMap( + components.size()); for (Iterator iterator = components.values().iterator(); iterator.hasNext();) { LdapRdnComponent rdnComponent = (LdapRdnComponent) iterator.next(); mapWithImmutableRdns.put(rdnComponent.getKey(), rdnComponent.immutableLdapRdnComponent()); } - Map unmodifiableMapOfImmutableRdns = Collections.unmodifiableMap(mapWithImmutableRdns); + Map unmodifiableMapOfImmutableRdns = Collections + .unmodifiableMap(mapWithImmutableRdns); LdapRdn immutableRdn = new LdapRdn(); immutableRdn.components = unmodifiableMapOfImmutableRdns; return immutableRdn; } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/core/LdapRdnComponent.java b/core/src/main/java/org/springframework/ldap/core/LdapRdnComponent.java index 30677341..c649fc18 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapRdnComponent.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapRdnComponent.java @@ -26,14 +26,15 @@ import java.net.URI; import java.net.URISyntaxException; /** - * Represents part of an LdapRdn. As specified in RFC2253 an LdapRdn may be - * composed of several attributes, separated by "+". An - * LdapRdnComponent represents one of these attributes. - * + * Represents part of an LdapRdn. As specified in RFC2253 an LdapRdn may be composed of + * several attributes, separated by "+". An LdapRdnComponent represents one of + * these attributes. + * * @author Mattias Hellborg Arthursson * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. */ public class LdapRdnComponent implements Comparable, Serializable { + private static final long serialVersionUID = -3296747972616243038L; private static final Logger LOG = LoggerFactory.getLogger(LdapRdnComponent.class); @@ -46,7 +47,6 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Constructs an LdapRdnComponent without decoding the value. - * * @param key the Attribute name. * @param value the Attribute value. */ @@ -57,15 +57,13 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Constructs an LdapRdnComponent, optionally decoding the value. *

    - * Depending on the value of the "key case fold" System property, the keys - * will be lowercased, uppercased, or preserve their original case. Default - * is to convert them to lowercase. - * + * Depending on the value of the "key case fold" System property, the keys will be + * lowercased, uppercased, or preserve their original case. Default is to convert them + * to lowercase. * @param key the Attribute name. * @param value the Attribute value. - * @param decodeValue if true the value is decoded (typically - * used when a DN is parsed from a String), otherwise the value is used as - * specified. + * @param decodeValue if true the value is decoded (typically used when a + * DN is parsed from a String), otherwise the value is used as specified. * @see DistinguishedName#KEY_CASE_FOLD_PROPERTY */ public LdapRdnComponent(String key, String value, boolean decodeValue) { @@ -75,16 +73,18 @@ public class LdapRdnComponent implements Comparable, Serializable { String caseFold = System.getProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); if (!StringUtils.hasText(caseFold) || caseFold.equals(DistinguishedName.KEY_CASE_FOLD_LOWER)) { this.key = key.toLowerCase(); - } else if (caseFold.equals(DistinguishedName.KEY_CASE_FOLD_UPPER)) { + } + else if (caseFold.equals(DistinguishedName.KEY_CASE_FOLD_UPPER)) { this.key = key.toUpperCase(); - } else if (caseFold.equals(DistinguishedName.KEY_CASE_FOLD_NONE)) { + } + else if (caseFold.equals(DistinguishedName.KEY_CASE_FOLD_NONE)) { this.key = key; - } else { - LOG - .warn("\"" + caseFold + "\" invalid property value for " + DistinguishedName.KEY_CASE_FOLD_PROPERTY - + "; expected \"" + DistinguishedName.KEY_CASE_FOLD_LOWER + "\", \"" - + DistinguishedName.KEY_CASE_FOLD_UPPER + "\", or \"" - + DistinguishedName.KEY_CASE_FOLD_NONE + "\""); + } + else { + LOG.warn("\"" + caseFold + "\" invalid property value for " + DistinguishedName.KEY_CASE_FOLD_PROPERTY + + "; expected \"" + DistinguishedName.KEY_CASE_FOLD_LOWER + "\", \"" + + DistinguishedName.KEY_CASE_FOLD_UPPER + "\", or \"" + DistinguishedName.KEY_CASE_FOLD_NONE + + "\""); this.key = key.toLowerCase(); } if (decodeValue) { @@ -97,7 +97,6 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Get the key (Attribute name) of this component. - * * @return the key. */ public String getKey() { @@ -106,7 +105,6 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Set the key (Attribute name) of this component. - * * @param key the key. * @deprecated Using this method changes the internal state of surrounding * DistinguishedName instance. This should be avoided. @@ -118,7 +116,6 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Get the (Attribute) value of this component. - * * @return the value. */ public String getValue() { @@ -127,7 +124,6 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Set the (Attribute) value of this component. - * * @param value the value. * @deprecated Using this method changes the internal state of surrounding * DistinguishedName instance. This should be avoided. @@ -139,7 +135,6 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Encode key and value to ldap. - * * @return Properly ldap escaped rdn. */ protected String encodeLdap() { @@ -154,7 +149,7 @@ public class LdapRdnComponent implements Comparable, Serializable { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ public String toString() { @@ -170,7 +165,6 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Get a String representation of this instance for use in URLs. - * * @return a properly URL encoded representation of this instancs. */ public String encodeUrl() { @@ -187,7 +181,7 @@ public class LdapRdnComponent implements Comparable, Serializable { /* * (non-Javadoc) - * + * * @see java.lang.Object#hashCode() */ public int hashCode() { @@ -196,7 +190,7 @@ public class LdapRdnComponent implements Comparable, Serializable { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object obj) { @@ -206,8 +200,7 @@ public class LdapRdnComponent implements Comparable, Serializable { LdapRdnComponent that = (LdapRdnComponent) obj; // It's safe to compare directly against key and value, // because they are validated not to be null on instance creation. - return this.key.equalsIgnoreCase(that.key) - && this.value.equalsIgnoreCase(that.value); + return this.key.equalsIgnoreCase(that.key) && this.value.equalsIgnoreCase(that.value); } else { @@ -217,7 +210,6 @@ public class LdapRdnComponent implements Comparable, Serializable { /** * Compare this instance to the supplied object. - * * @param obj the object to compare to. * @throws ClassCastException if the object is not possible to cast to an * LdapRdnComponent. @@ -228,17 +220,17 @@ public class LdapRdnComponent implements Comparable, Serializable { // It's safe to compare directly against key and value, // because they are validated not to be null on instance creation. int keyCompare = this.key.toLowerCase().compareTo(that.key.toLowerCase()); - if(keyCompare == 0) { + if (keyCompare == 0) { return this.value.toLowerCase().compareTo(that.value.toLowerCase()); - } else { + } + else { return keyCompare; } } /** - * Create an immutable copy of this instance. It will not be possible to - * modify the key or the value of the returned instance. - * + * Create an immutable copy of this instance. It will not be possible to modify the + * key or the value of the returned instance. * @return an immutable copy of this instance. * @since 1.3 */ @@ -247,6 +239,7 @@ public class LdapRdnComponent implements Comparable, Serializable { } private static class ImmutableLdapRdnComponent extends LdapRdnComponent { + private static final long serialVersionUID = -7099970046426346567L; public ImmutableLdapRdnComponent(String key, String value) { @@ -260,5 +253,7 @@ public class LdapRdnComponent implements Comparable, Serializable { public void setValue(String value) { throw new UnsupportedOperationException("SetKey not supported for this immutable LdapRdnComponent"); } + } + } diff --git a/core/src/main/java/org/springframework/ldap/core/LdapTemplate.java b/core/src/main/java/org/springframework/ldap/core/LdapTemplate.java index 8410c130..e79303f8 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapTemplate.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapTemplate.java @@ -56,23 +56,21 @@ import java.util.stream.Stream; import java.util.stream.StreamSupport; /** - * Executes core LDAP functionality and helps to avoid common errors, relieving - * the user of the burden of looking up contexts, looping through - * NamingEnumerations and closing contexts. + * Executes core LDAP functionality and helps to avoid common errors, relieving the user + * of the burden of looking up contexts, looping through NamingEnumerations and closing + * contexts. *

    - * Note for Active Directory (AD) users: AD servers are apparently unable - * to handle referrals automatically, which causes a - * PartialResultException to be thrown whenever a referral is - * encountered in a search. To avoid this, set the - * ignorePartialResultException property to true. - * There is currently no way of manually handling these referrals in the form of - * ReferralException, i.e. either you get the exception (and your - * results are lost) or all referrals are ignored (if the server is unable to - * handle them properly. Neither is there any simple way to get notified that a + * Note for Active Directory (AD) users: AD servers are apparently unable to handle + * referrals automatically, which causes a PartialResultException to be + * thrown whenever a referral is encountered in a search. To avoid this, set the + * ignorePartialResultException property to true. There is + * currently no way of manually handling these referrals in the form of + * ReferralException, i.e. either you get the exception (and your results are + * lost) or all referrals are ignored (if the server is unable to handle them properly. + * Neither is there any simple way to get notified that a * PartialResultException has been ignored (other than in the log). - * + * * @see org.springframework.ldap.core.ContextSource - * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ @@ -110,7 +108,6 @@ public class LdapTemplate implements LdapOperations, InitializingBean { /** * Constructor to setup instance directly. - * * @param contextSource the ContextSource to use. */ public LdapTemplate(ContextSource contextSource) { @@ -118,9 +115,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Set the ContextSource. Call this method when the default constructor has - * been used. - * + * Set the ContextSource. Call this method when the default constructor has been used. * @param contextSource the ContextSource. */ public void setContextSource(ContextSource contextSource) { @@ -137,7 +132,6 @@ public class LdapTemplate implements LdapOperations, InitializingBean { /** * Set the ObjectDirectoryMapper instance to use. - * * @param odm the ObejctDirectoryMapper to use. * @since 2.0 */ @@ -147,7 +141,6 @@ public class LdapTemplate implements LdapOperations, InitializingBean { /** * Get the ContextSource. - * * @return the ContextSource. */ public ContextSource getContextSource() { @@ -155,18 +148,15 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Specify whether NameNotFoundException should be ignored in - * searches. In previous version, NameNotFoundException caused - * by the search base not being found was silently ignored. The default - * behavior is now to treat this as an error (as it should), and to convert - * and re-throw the exception. The ability to revert to the previous - * behavior still exists. The only difference is that the incident is in - * that case no longer silently ignored, but logged as a warning. - * - * @param ignore true if NameNotFoundException - * should be ignored in searches, false otherwise. Default is - * false. - * + * Specify whether NameNotFoundException should be ignored in searches. + * In previous version, NameNotFoundException caused by the search base + * not being found was silently ignored. The default behavior is now to treat this as + * an error (as it should), and to convert and re-throw the exception. The ability to + * revert to the previous behavior still exists. The only difference is that the + * incident is in that case no longer silently ignored, but logged as a warning. + * @param ignore true if NameNotFoundException should be + * ignored in searches, false otherwise. Default is false. + * * @since 1.3 */ public void setIgnoreNameNotFoundException(boolean ignore) { @@ -174,32 +164,27 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Specify whether PartialResultException should be ignored in - * searches. AD servers typically have a problem with referrals. Normally a - * referral should be followed automatically, but this does not seem to work - * with AD servers. The problem manifests itself with a - * PartialResultException being thrown when a referral is - * encountered by the server. Setting this property to true + * Specify whether PartialResultException should be ignored in searches. + * AD servers typically have a problem with referrals. Normally a referral should be + * followed automatically, but this does not seem to work with AD servers. The problem + * manifests itself with a PartialResultException being thrown when a + * referral is encountered by the server. Setting this property to true * presents a workaround to this problem by causing - * PartialResultException to be ignored, so that the search - * method returns normally. Default value of this parameter is - * false. - * - * @param ignore true if PartialResultException - * should be ignored in searches, false otherwise. Default is - * false. + * PartialResultException to be ignored, so that the search method + * returns normally. Default value of this parameter is false. + * @param ignore true if PartialResultException should be + * ignored in searches, false otherwise. Default is false. */ public void setIgnorePartialResultException(boolean ignore) { this.ignorePartialResultException = ignore; } /** - * Specify whether SizeLimitExceededException should be ignored in searches. - * This is typically what you want if you specify count limit in your search controls. - * - * @param ignore true if SizeLimitExceededException - * should be ignored in searches, false otherwise. Default is - * true. + * Specify whether SizeLimitExceededException should be ignored in + * searches. This is typically what you want if you specify count limit in your search + * controls. + * @param ignore true if SizeLimitExceededException should + * be ignored in searches, false otherwise. Default is true. * @since 2.0 */ public void setIgnoreSizeLimitExceededException(boolean ignore) { @@ -207,13 +192,11 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Set the default scope to be used in searches if not explicitly specified. - * Default is {@link javax.naming.directory.SearchControls#SUBTREE_SCOPE}. - * - * @param defaultSearchScope the default search scope to use in searches. - * One of {@link SearchControls#OBJECT_SCOPE}, - * {@link SearchControls#ONELEVEL_SCOPE}, - * or {@link SearchControls#SUBTREE_SCOPE} + * Set the default scope to be used in searches if not explicitly specified. Default + * is {@link javax.naming.directory.SearchControls#SUBTREE_SCOPE}. + * @param defaultSearchScope the default search scope to use in searches. One of + * {@link SearchControls#OBJECT_SCOPE}, {@link SearchControls#ONELEVEL_SCOPE}, or + * {@link SearchControls#SUBTREE_SCOPE} * @since 2.0 */ public void setDefaultSearchScope(int defaultSearchScope) { @@ -221,9 +204,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Set the default time limit be used in searches if not explicitly specified. - * Default is 0, indicating no time limit. - * + * Set the default time limit be used in searches if not explicitly specified. Default + * is 0, indicating no time limit. * @param defaultTimeLimit the default time limit to use in searches. * @since 2.0 */ @@ -234,7 +216,6 @@ public class LdapTemplate implements LdapOperations, InitializingBean { /** * Set the default count limit be used in searches if not explicitly specified. * Default is 0, indicating no count limit. - * * @param defaultCountLimit the default count limit to use in searches. * @since 2.0 */ @@ -339,28 +320,25 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Perform a search operation, such as a search(), list() or listBindings(). - * This method handles all the plumbing; getting a readonly context; looping - * through the NamingEnumeration and closing the context and enumeration. It - * also calls the supplied DirContextProcessor before and after the search, - * respectively. This enables custom pre-processing and post-processing, - * like for example when handling paged results or other search controls. + * Perform a search operation, such as a search(), list() or listBindings(). This + * method handles all the plumbing; getting a readonly context; looping through the + * NamingEnumeration and closing the context and enumeration. It also calls the + * supplied DirContextProcessor before and after the search, respectively. This + * enables custom pre-processing and post-processing, like for example when handling + * paged results or other search controls. *

    * The actual list is delegated to the {@link SearchExecutor} and each - * {@link NameClassPair} (this might be a NameClassPair or a subclass - * thereof) is passed to the CallbackHandler. Any encountered - * NamingException will be translated using the NamingExceptionTranslator. - * + * {@link NameClassPair} (this might be a NameClassPair or a subclass thereof) is + * passed to the CallbackHandler. Any encountered NamingException will be translated + * using the NamingExceptionTranslator. * @param se the SearchExecutor to use for performing the actual list. - * @param handler the NameClassPairCallbackHandler to which each found entry - * will be passed. - * @param processor DirContextProcessor for custom pre- and post-processing. - * Must not be null. If no custom processing should take place, - * please use e.g. + * @param handler the NameClassPairCallbackHandler to which each found entry will be + * passed. + * @param processor DirContextProcessor for custom pre- and post-processing. Must not + * be null. If no custom processing should take place, please use e.g. * {@link #search(SearchExecutor, NameClassPairCallbackHandler)}. - * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is interpreted that - * no entries were found. + * @throws NamingException if any error occurs. Note that a NameNotFoundException will + * be ignored. Instead this is interpreted that no entries were found. */ @Override public void search(SearchExecutor se, NameClassPairCallbackHandler handler, DirContextProcessor processor) { @@ -395,8 +373,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { ex = LdapUtils.convertLdapException(e); } } - catch(SizeLimitExceededException e) { - if(ignoreSizeLimitExceededException) { + catch (SizeLimitExceededException e) { + if (ignoreSizeLimitExceededException) { LOG.debug("SizeLimitExceededException encountered and ignored", e); } else { @@ -429,21 +407,19 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Perform a search operation, such as a search(), list() or listBindings(). - * This method handles all the plumbing; getting a readonly context; looping - * through the NamingEnumeration and closing the context and enumeration. + * Perform a search operation, such as a search(), list() or listBindings(). This + * method handles all the plumbing; getting a readonly context; looping through the + * NamingEnumeration and closing the context and enumeration. *

    * The actual list is delegated to the {@link SearchExecutor} and each - * {@link NameClassPair} (this might be a NameClassPair or a subclass - * thereof) is passed to the CallbackHandler. Any encountered - * NamingException will be translated using the NamingExceptionTranslator. - * + * {@link NameClassPair} (this might be a NameClassPair or a subclass thereof) is + * passed to the CallbackHandler. Any encountered NamingException will be translated + * using the NamingExceptionTranslator. * @param se the SearchExecutor to use for performing the actual list. - * @param handler the NameClassPairCallbackHandler to which each found entry - * will be passed. - * @throws NamingException if any error occurs. Note that a - * NameNotFoundException will be ignored. Instead this is interpreted that - * no entries were found. + * @param handler the NameClassPairCallbackHandler to which each found entry will be + * passed. + * @throws NamingException if any error occurs. Note that a NameNotFoundException will + * be ignored. Instead this is interpreted that no entries were found. */ @Override public void search(SearchExecutor se, NameClassPairCallbackHandler handler) { @@ -687,7 +663,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { */ @Override public List list(String base, NameClassPairMapper mapper) { - CollectingNameClassPairCallbackHandler handler = new MappingCollectingNameClassPairCallbackHandler(mapper); + CollectingNameClassPairCallbackHandler handler = new MappingCollectingNameClassPairCallbackHandler( + mapper); list(base, handler); return handler.getList(); } @@ -697,7 +674,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { */ @Override public List list(Name base, NameClassPairMapper mapper) { - CollectingNameClassPairCallbackHandler handler = new MappingCollectingNameClassPairCallbackHandler(mapper); + CollectingNameClassPairCallbackHandler handler = new MappingCollectingNameClassPairCallbackHandler( + mapper); list(base, handler); return handler.getList(); } @@ -751,7 +729,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { */ @Override public List listBindings(String base, NameClassPairMapper mapper) { - CollectingNameClassPairCallbackHandler handler = new MappingCollectingNameClassPairCallbackHandler(mapper); + CollectingNameClassPairCallbackHandler handler = new MappingCollectingNameClassPairCallbackHandler( + mapper); listBindings(base, handler); return handler.getList(); } @@ -761,7 +740,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { */ @Override public List listBindings(Name base, NameClassPairMapper mapper) { - CollectingNameClassPairCallbackHandler handler = new MappingCollectingNameClassPairCallbackHandler(mapper); + CollectingNameClassPairCallbackHandler handler = new MappingCollectingNameClassPairCallbackHandler( + mapper); listBindings(base, handler); return handler.getList(); } @@ -1098,7 +1078,6 @@ public class LdapTemplate implements LdapOperations, InitializingBean { /** * Delete all subcontexts including the current one recursively. - * * @param ctx The context to use for deleting. * @param name The starting point to delete recursively. * @throws NamingException if any error occurs @@ -1199,9 +1178,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Close the supplied DirContext if it is not null. Swallow any exceptions, - * as this is only for cleanup. - * + * Close the supplied DirContext if it is not null. Swallow any exceptions, as this is + * only for cleanup. * @param ctx the context to close. */ private void closeContext(DirContext ctx) { @@ -1216,9 +1194,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Close the supplied NamingEnumeration if it is not null. Swallow any - * exceptions, as this is only for cleanup. - * + * Close the supplied NamingEnumeration if it is not null. Swallow any exceptions, as + * this is only for cleanup. * @param results the NamingEnumeration to close. */ private void closeNamingEnumeration(NamingEnumeration results) { @@ -1243,9 +1220,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } /** - * Make sure the returnObjFlag is set in the supplied SearchControls. Set it - * and log if it's not set. - * + * Make sure the returnObjFlag is set in the supplied SearchControls. Set it and log + * if it's not set. * @param controls the SearchControls to check. */ private void assureReturnObjFlagSet(SearchControls controls) { @@ -1264,6 +1240,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { * @since 2.0 */ public static final class NullDirContextProcessor implements DirContextProcessor { + public void postProcess(DirContext ctx) { // Do nothing } @@ -1271,16 +1248,17 @@ public class LdapTemplate implements LdapOperations, InitializingBean { public void preProcess(DirContext ctx) { // Do nothing } + } /** - * A {@link NameClassPairCallbackHandler} that passes the NameClassPairs - * found to a NameClassPairMapper and collects the results in a list. - * + * A {@link NameClassPairCallbackHandler} that passes the NameClassPairs found to a + * NameClassPairMapper and collects the results in a list. + * * @author Mattias Hellborg Arthursson */ - public final static class MappingCollectingNameClassPairCallbackHandler extends - CollectingNameClassPairCallbackHandler { + public final static class MappingCollectingNameClassPairCallbackHandler + extends CollectingNameClassPairCallbackHandler { private NameClassPairMapper mapper; @@ -1299,6 +1277,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { throw LdapUtils.convertLdapException(e); } } + } /** @@ -1345,7 +1324,6 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } } - /** * {@inheritDoc} */ @@ -1356,8 +1334,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { rebind(dn, ctx, null); } else { - throw new IllegalStateException( - "The DirContextOperations instance needs to be properly initialized."); + throw new IllegalStateException("The DirContextOperations instance needs to be properly initialized."); } } @@ -1366,8 +1343,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { */ @Override public boolean authenticate(Name base, String filter, String password) { - return authenticate(base, filter, password, - new NullAuthenticatedLdapEntryContextCallback(), + return authenticate(base, filter, password, new NullAuthenticatedLdapEntryContextCallback(), new NullAuthenticationErrorCallback()); } @@ -1377,8 +1353,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { @Override public boolean authenticate(String base, String filter, String password) { return authenticate(LdapUtils.newLdapName(base), filter, password, - new NullAuthenticatedLdapEntryContextCallback(), - new NullAuthenticationErrorCallback()); + new NullAuthenticatedLdapEntryContextCallback(), new NullAuthenticationErrorCallback()); } /** @@ -1387,7 +1362,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { @Override public boolean authenticate(String base, String filter, String password, AuthenticatedLdapEntryContextCallback callback) { - return authenticate(LdapUtils.newLdapName(base), filter, password, callback, new NullAuthenticationErrorCallback()); + return authenticate(LdapUtils.newLdapName(base), filter, password, callback, + new NullAuthenticationErrorCallback()); } /** @@ -1405,7 +1381,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { @Override public boolean authenticate(String base, String filter, String password, AuthenticationErrorCallback errorCallback) { - return authenticate(LdapUtils.newLdapName(base), filter, password, new NullAuthenticatedLdapEntryContextCallback(), errorCallback); + return authenticate(LdapUtils.newLdapName(base), filter, password, + new NullAuthenticatedLdapEntryContextCallback(), errorCallback); } /** @@ -1433,27 +1410,21 @@ public class LdapTemplate implements LdapOperations, InitializingBean { public boolean authenticate(Name base, String filter, String password, final AuthenticatedLdapEntryContextCallback callback, final AuthenticationErrorCallback errorCallback) { - return authenticate(base, - filter, - password, - getDefaultSearchControls(defaultSearchScope, RETURN_OBJ_FLAG, null), - callback, - errorCallback).isSuccess(); + return authenticate(base, filter, password, getDefaultSearchControls(defaultSearchScope, RETURN_OBJ_FLAG, null), + callback, errorCallback).isSuccess(); } - private AuthenticationStatus authenticate(Name base, - String filter, - String password, - SearchControls searchControls, - final AuthenticatedLdapEntryContextCallback callback, - final AuthenticationErrorCallback errorCallback) { + private AuthenticationStatus authenticate(Name base, String filter, String password, SearchControls searchControls, + final AuthenticatedLdapEntryContextCallback callback, final AuthenticationErrorCallback errorCallback) { - List result = search(base, filter, searchControls, new LdapEntryIdentificationContextMapper()); + List result = search(base, filter, searchControls, + new LdapEntryIdentificationContextMapper()); if (result.size() == 0) { String msg = "No results found for search, base: '" + base + "'; filter: '" + filter + "'."; LOG.info(msg); return AuthenticationStatus.EMPTYRESULT; - } else if (result.size() > 1) { + } + else if (result.size() > 1) { String msg = "base: '" + base + "'; filter: '" + filter + "'."; throw new IncorrectResultSizeDataAccessException(msg, 1, result.size()); } @@ -1483,29 +1454,27 @@ public class LdapTemplate implements LdapOperations, InitializingBean { @Override public T authenticate(LdapQuery query, String password, AuthenticatedLdapEntryContextMapper mapper) { SearchControls searchControls = searchControlsForQuery(query, RETURN_OBJ_FLAG); - ReturningAuthenticatedLdapEntryContext mapperCallback = - new ReturningAuthenticatedLdapEntryContext(mapper); - CollectingAuthenticationErrorCallback errorCallback = - new CollectingAuthenticationErrorCallback(); + ReturningAuthenticatedLdapEntryContext mapperCallback = new ReturningAuthenticatedLdapEntryContext( + mapper); + CollectingAuthenticationErrorCallback errorCallback = new CollectingAuthenticationErrorCallback(); - AuthenticationStatus authenticationStatus = authenticate(query.base(), - query.filter().encode(), - password, - searchControls, - mapperCallback, - errorCallback); + AuthenticationStatus authenticationStatus = authenticate(query.base(), query.filter().encode(), password, + searchControls, mapperCallback, errorCallback); - if(errorCallback.hasError()) { + if (errorCallback.hasError()) { Exception error = errorCallback.getError(); if (error instanceof NamingException) { throw (NamingException) error; - } else { + } + else { throw new UncategorizedLdapException(error); } - } else if(AuthenticationStatus.EMPTYRESULT == authenticationStatus) { + } + else if (AuthenticationStatus.EMPTYRESULT == authenticationStatus) { throw new EmptyResultDataAccessException(1); - } else if(!authenticationStatus.isSuccess()) { + } + else if (!authenticationStatus.isSuccess()) { throw new AuthenticationException(); } @@ -1517,9 +1486,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { */ @Override public void authenticate(LdapQuery query, String password) { - authenticate(query, - password, - new NullAuthenticatedLdapEntryContextCallback()); + authenticate(query, password, new NullAuthenticatedLdapEntryContextCallback()); } /** @@ -1527,10 +1494,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { */ @Override public T searchForObject(Name base, String filter, ContextMapper mapper) { - return searchForObject(base, - filter, - getDefaultSearchControls(defaultSearchScope, RETURN_OBJ_FLAG, ALL_ATTRIBUTES), - mapper); + return searchForObject(base, filter, + getDefaultSearchControls(defaultSearchScope, RETURN_OBJ_FLAG, ALL_ATTRIBUTES), mapper); } /** @@ -1545,7 +1510,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { * {@inheritDoc} */ @Override - public T searchForObject (Name base, String filter, SearchControls searchControls, ContextMapper mapper) { + public T searchForObject(Name base, String filter, SearchControls searchControls, ContextMapper mapper) { List result = search(base, filter, searchControls, mapper); if (result.size() == 0) { @@ -1567,9 +1532,9 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } private static final class NullAuthenticatedLdapEntryContextCallback - implements AuthenticatedLdapEntryContextCallback, AuthenticatedLdapEntryContextMapper{ - public void executeWithContext(DirContext ctx, - LdapEntryIdentification ldapEntryIdentification) { + implements AuthenticatedLdapEntryContextCallback, AuthenticatedLdapEntryContextMapper { + + public void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { // Do nothing } @@ -1577,17 +1542,20 @@ public class LdapTemplate implements LdapOperations, InitializingBean { public Object mapWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { return null; } + } - private static final class NullAuthenticationErrorCallback - implements AuthenticationErrorCallback { + private static final class NullAuthenticationErrorCallback implements AuthenticationErrorCallback { + public void execute(Exception e) { // Do nothing } + } private static final class ReturningAuthenticatedLdapEntryContext implements AuthenticatedLdapEntryContextCallback { + private final AuthenticatedLdapEntryContextMapper mapper; private T collectedObject; @@ -1603,6 +1571,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { public void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { collectedObject = mapper.mapWithContext(ctx, ldapEntryIdentification); } + } /** @@ -1611,10 +1580,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { @Override public void search(LdapQuery query, NameClassPairCallbackHandler callbackHandler) { SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG); - search(query.base(), - query.filter().encode(), - searchControls, - callbackHandler); + search(query.base(), query.filter().encode(), searchControls, callbackHandler); } /** @@ -1624,28 +1590,22 @@ public class LdapTemplate implements LdapOperations, InitializingBean { public List search(LdapQuery query, ContextMapper mapper) { SearchControls searchControls = searchControlsForQuery(query, RETURN_OBJ_FLAG); - return search(query.base(), - query.filter().encode(), - searchControls, - mapper); + return search(query.base(), query.filter().encode(), searchControls, mapper); } private SearchControls searchControlsForQuery(LdapQuery query, boolean returnObjFlag) { - SearchControls searchControls = getDefaultSearchControls( - defaultSearchScope, - returnObjFlag, - query.attributes()); + SearchControls searchControls = getDefaultSearchControls(defaultSearchScope, returnObjFlag, query.attributes()); - if(query.searchScope() != null) { + if (query.searchScope() != null) { searchControls.setSearchScope(query.searchScope().getId()); } - if(query.countLimit() != null) { + if (query.countLimit() != null) { searchControls.setCountLimit(query.countLimit()); } - if(query.timeLimit() != null) { + if (query.timeLimit() != null) { searchControls.setTimeLimit(query.timeLimit()); } return searchControls; @@ -1658,10 +1618,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { public List search(LdapQuery query, AttributesMapper mapper) { SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG); - return search(query.base(), - query.filter().encode(), - searchControls, - mapper); + return search(query.base(), query.filter().encode(), searchControls, mapper); } /** @@ -1684,10 +1641,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { public T searchForObject(LdapQuery query, ContextMapper mapper) { SearchControls searchControls = searchControlsForQuery(query, DONT_RETURN_OBJ_FLAG); - return searchForObject(query.base(), - query.filter().encode(), - searchControls, - mapper); + return searchForObject(query.base(), query.filter().encode(), searchControls, mapper); } /** @@ -1723,7 +1677,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { String encodedFilter = filter.encode(); if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Searching - base=%1$s, finalFilter=%2$s, scope=%3$s", base, filter, searchControls)); + LOG.debug( + String.format("Searching - base=%1$s, finalFilter=%2$s, scope=%3$s", base, filter, searchControls)); } assureReturnObjFlagSet(searchControls); @@ -1732,9 +1687,11 @@ public class LdapTemplate implements LdapOperations, InitializingBean { if (results == null) { return Stream.empty(); } - return StreamSupport.stream(Spliterators.spliteratorUnknownSize(CollectionUtils.toIterator(results), Spliterator.ORDERED), false) - .map((nameClassPair) -> unchecked(() -> mapper.apply(nameClassPair))) - .filter(Objects::nonNull).onClose(() -> closeContextAndNamingEnumeration(ctx, results)); + return StreamSupport + .stream(Spliterators.spliteratorUnknownSize(CollectionUtils.toIterator(results), Spliterator.ORDERED), + false) + .map((nameClassPair) -> unchecked(() -> mapper.apply(nameClassPair))).filter(Objects::nonNull) + .onClose(() -> closeContextAndNamingEnumeration(ctx, results)); } /** @@ -1778,7 +1735,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } Name id = odm.getId(entry); - if(id == null) { + if (id == null) { id = odm.getCalculatedId(entry); odm.setId(entry, id); } @@ -1804,11 +1761,12 @@ public class LdapTemplate implements LdapOperations, InitializingBean { Name originalId = odm.getId(entry); Name calculatedId = odm.getCalculatedId(entry); - if(originalId != null && calculatedId != null && !originalId.equals(calculatedId)) { + if (originalId != null && calculatedId != null && !originalId.equals(calculatedId)) { // The DN has changed - remove the original entry and bind the new one // (because other data may have changed as well if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Calculated DN of %s; of entry %s differs from explicitly specified one; %s - moving", + LOG.debug(String.format( + "Calculated DN of %s; of entry %s differs from explicitly specified one; %s - moving", calculatedId, entry, originalId)); } @@ -1819,11 +1777,12 @@ public class LdapTemplate implements LdapOperations, InitializingBean { bind(context); odm.setId(entry, calculatedId); - } else { + } + else { // DN is the same, just modify the attributes Name id = originalId; - if(id == null) { + if (id == null) { id = calculatedId; odm.setId(entry, calculatedId); } @@ -1847,7 +1806,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } Name id = odm.getId(entry); - if(id == null) { + if (id == null) { id = odm.getCalculatedId(entry); } @@ -1869,8 +1828,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { @Override public List findAll(Class clazz) { return findAll(LdapUtils.emptyLdapName(), - getDefaultSearchControls(defaultSearchScope, RETURN_OBJ_FLAG, ALL_ATTRIBUTES), - clazz); + getDefaultSearchControls(defaultSearchScope, RETURN_OBJ_FLAG, ALL_ATTRIBUTES), clazz); } /** @@ -1893,7 +1851,8 @@ public class LdapTemplate implements LdapOperations, InitializingBean { } if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Searching - base=%1$s, finalFilter=%2$s, scope=%3$s", base, finalFilter, searchControls)); + LOG.debug(String.format("Searching - base=%1$s, finalFilter=%2$s, scope=%3$s", base, finalFilter, + searchControls)); } List result = search(localBase, finalFilter.encode(), searchControls, new ContextMapper() { @@ -1955,31 +1914,37 @@ public class LdapTemplate implements LdapOperations, InitializingBean { private T unchecked(CheckedSupplier supplier) { try { return supplier.get(); - } catch (NameNotFoundException e) { + } + catch (NameNotFoundException e) { // It is possible to ignore errors caused by base not found if (!ignoreNameNotFoundException) { throw LdapUtils.convertLdapException(e); } LOG.warn("Base context not found, ignoring: " + e.getMessage()); - } catch (PartialResultException e) { + } + catch (PartialResultException e) { // Workaround for AD servers not handling referrals correctly. if (!ignorePartialResultException) { throw LdapUtils.convertLdapException(e); } LOG.debug("PartialResultException encountered and ignored", e); - } catch(SizeLimitExceededException e) { - if(!ignoreSizeLimitExceededException) { + } + catch (SizeLimitExceededException e) { + if (!ignoreSizeLimitExceededException) { throw LdapUtils.convertLdapException(e); } LOG.debug("SizeLimitExceededException encountered and ignored", e); - } catch (javax.naming.NamingException e) { + } + catch (javax.naming.NamingException e) { throw LdapUtils.convertLdapException(e); } return null; } private interface CheckedSupplier { + T get() throws javax.naming.NamingException; + } /** @@ -1988,6 +1953,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { * @author Rob Winch */ private enum AuthenticationStatus { + /** * Authentication was successful */ @@ -2014,5 +1980,7 @@ public class LdapTemplate implements LdapOperations, InitializingBean { public boolean isSuccess() { return success; } + } + } diff --git a/core/src/main/java/org/springframework/ldap/core/NameAwareAttribute.java b/core/src/main/java/org/springframework/ldap/core/NameAwareAttribute.java index bb0003c1..a6eb829c 100644 --- a/core/src/main/java/org/springframework/ldap/core/NameAwareAttribute.java +++ b/core/src/main/java/org/springframework/ldap/core/NameAwareAttribute.java @@ -43,8 +43,11 @@ import java.util.Set; public final class NameAwareAttribute implements Attribute, Iterable { private final String id; + private final boolean orderMatters; + private final Set values = new LinkedHashSet(); + private Map valuesAsNames = new HashMap(); /** @@ -59,17 +62,17 @@ public final class NameAwareAttribute implements Attribute, Iterable { /** * Construct a new instance from the supplied Attribute. - * * @param attribute the Attribute to copy. */ public NameAwareAttribute(Attribute attribute) { this(attribute.getID(), attribute.isOrdered()); try { NamingEnumeration incomingValues = attribute.getAll(); - while(incomingValues.hasMore()) { + while (incomingValues.hasMore()) { this.add(incomingValues.next()); } - } catch (NamingException e) { + } + catch (NamingException e) { throw LdapUtils.convertLdapException(e); } @@ -88,7 +91,8 @@ public final class NameAwareAttribute implements Attribute, Iterable { } /** - * Construct a new instance with the specified id, no values and order significance as specified. + * Construct a new instance with the specified id, no values and order significance as + * specified. * @param id the attribute id * @param orderMatters whether order has significance in this attribute. */ @@ -104,7 +108,7 @@ public final class NameAwareAttribute implements Attribute, Iterable { @Override public Object get() { - if(values.isEmpty()) { + if (values.isEmpty()) { return null; } @@ -134,12 +138,13 @@ public final class NameAwareAttribute implements Attribute, Iterable { Name name = LdapUtils.newLdapName((Name) attrVal); String currentValue = valuesAsNames.get(name); String nameAsString = name.toString(); - if(currentValue == null) { + if (currentValue == null) { valuesAsNames.put(name, name.toString()); values.add(nameAsString); return true; - } else { - if(!currentValue.equals(nameAsString)) { + } + else { + if (!currentValue.equals(nameAsString)) { values.remove(currentValue); values.add(nameAsString); } @@ -152,7 +157,7 @@ public final class NameAwareAttribute implements Attribute, Iterable { } public void initValuesAsNames() { - if(hasValuesAsNames()) { + if (hasValuesAsNames()) { return; } @@ -162,15 +167,20 @@ public final class NameAwareAttribute implements Attribute, Iterable { String s = (String) value; try { newValuesAsNames.put(LdapUtils.newLdapName(s), s); - } catch (InvalidNameException e) { - throw new IllegalArgumentException("This instance has values that are not valid distinguished names; " + - "cannot handle Name values", e); } - } else if (value instanceof LdapName) { + catch (InvalidNameException e) { + throw new IllegalArgumentException( + "This instance has values that are not valid distinguished names; " + + "cannot handle Name values", + e); + } + } + else if (value instanceof LdapName) { newValuesAsNames.put((LdapName) value, value.toString()); - } else { - throw new IllegalArgumentException("This instance has non-string attribute values; " + - "cannot handle Name values"); + } + else { + throw new IllegalArgumentException( + "This instance has non-string attribute values; " + "cannot handle Name values"); } } @@ -188,7 +198,7 @@ public final class NameAwareAttribute implements Attribute, Iterable { Name name = LdapUtils.newLdapName((Name) attrval); String removedValue = valuesAsNames.remove(name); - if(removedValue != null) { + if (removedValue != null) { values.remove(removedValue); return true; @@ -221,8 +231,8 @@ public final class NameAwareAttribute implements Attribute, Iterable { /** *

    - * Due to performance reasons it is not advised to iterate over the attribute's values using this method. - * Please use the {@link #iterator()} instead. + * Due to performance reasons it is not advised to iterate over the attribute's values + * using this method. Please use the {@link #iterator()} instead. *

    * {@inheritDoc} */ @@ -232,12 +242,13 @@ public final class NameAwareAttribute implements Attribute, Iterable { try { Object value = iterator.next(); - for(int i = 0; i < ix; i++) { + for (int i = 0; i < ix; i++) { value = iterator.next(); } return value; - } catch (NoSuchElementException e) { + } + catch (NoSuchElementException e) { throw new IndexOutOfBoundsException("No value at index i"); } } @@ -248,18 +259,20 @@ public final class NameAwareAttribute implements Attribute, Iterable { try { Object value = iterator.next(); - for(int i = 0; i < ix; i++) { + for (int i = 0; i < ix; i++) { value = iterator.next(); } iterator.remove(); if (value instanceof String) { try { valuesAsNames.remove(new LdapName((String) value)); - } catch (javax.naming.InvalidNameException ignored) { + } + catch (javax.naming.InvalidNameException ignored) { } } return value; - } catch (NoSuchElementException e) { + } + catch (NoSuchElementException e) { throw new IndexOutOfBoundsException("No value at index i"); } } @@ -288,27 +301,30 @@ public final class NameAwareAttribute implements Attribute, Iterable { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; NameAwareAttribute that = (NameAwareAttribute) o; - if (id != null ? !id.equals(that.id) : that.id != null) return false; - if(this.values.size() != that.values.size()) { + if (id != null ? !id.equals(that.id) : that.id != null) + return false; + if (this.values.size() != that.values.size()) { return false; } - if(this.orderMatters != that.orderMatters || this.size() != that.size()) { + if (this.orderMatters != that.orderMatters || this.size() != that.size()) { return false; } - if(this.hasValuesAsNames() != that.hasValuesAsNames()) { + if (this.hasValuesAsNames() != that.hasValuesAsNames()) { return false; } Set myValues = this.values; Set theirValues = that.values; - if(this.hasValuesAsNames()) { + if (this.hasValuesAsNames()) { // We have Name values - compare these to get // syntactically correct comparison of the values @@ -316,19 +332,20 @@ public final class NameAwareAttribute implements Attribute, Iterable { theirValues = that.valuesAsNames.keySet(); } - if(orderMatters) { + if (orderMatters) { Iterator thisIterator = myValues.iterator(); Iterator thatIterator = theirValues.iterator(); - while(thisIterator.hasNext()) { - if(!ObjectUtils.nullSafeEquals(thisIterator.next(), thatIterator.next())) { + while (thisIterator.hasNext()) { + if (!ObjectUtils.nullSafeEquals(thisIterator.next(), thatIterator.next())) { return false; } } return true; - } else { + } + else { for (Object value : myValues) { - if(!CollectionUtils.contains(theirValues.iterator(), value)) { + if (!CollectionUtils.contains(theirValues.iterator(), value)) { return false; } } @@ -343,7 +360,7 @@ public final class NameAwareAttribute implements Attribute, Iterable { int valuesHash = 7; Set myValues = this.values; - if(hasValuesAsNames()) { + if (hasValuesAsNames()) { myValues = valuesAsNames.keySet(); } @@ -357,8 +374,8 @@ public final class NameAwareAttribute implements Attribute, Iterable { @Override public String toString() { - return String.format("NameAwareAttribute; id: %s; hasValuesAsNames: %s; orderMatters: %s; values: %s", - id, hasValuesAsNames(), orderMatters, values); + return String.format("NameAwareAttribute; id: %s; hasValuesAsNames: %s; orderMatters: %s; values: %s", id, + hasValuesAsNames(), orderMatters, values); } @Override diff --git a/core/src/main/java/org/springframework/ldap/core/NameAwareAttributes.java b/core/src/main/java/org/springframework/ldap/core/NameAwareAttributes.java index 0bbddf94..5152248b 100644 --- a/core/src/main/java/org/springframework/ldap/core/NameAwareAttributes.java +++ b/core/src/main/java/org/springframework/ldap/core/NameAwareAttributes.java @@ -31,6 +31,7 @@ import java.util.Map; * @since 2.0 */ public final class NameAwareAttributes implements Attributes { + private Map attributes = new HashMap(); /** @@ -46,7 +47,7 @@ public final class NameAwareAttributes implements Attributes { */ public NameAwareAttributes(Attributes attributes) { NamingEnumeration allAttributes = attributes.getAll(); - while(allAttributes.hasMoreElements()) { + while (allAttributes.hasMoreElements()) { Attribute attribute = allAttributes.nextElement(); put(new NameAwareAttribute(attribute)); } @@ -109,12 +110,15 @@ public final class NameAwareAttributes implements Attributes { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; NameAwareAttributes that = (NameAwareAttributes) o; - if (attributes != null ? !attributes.equals(that.attributes) : that.attributes != null) return false; + if (attributes != null ? !attributes.equals(that.attributes) : that.attributes != null) + return false; return true; } @@ -128,4 +132,5 @@ public final class NameAwareAttributes implements Attributes { public String toString() { return String.format("NameAwareAttribute; attributes: %s", attributes.toString()); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/NameClassPairCallbackHandler.java b/core/src/main/java/org/springframework/ldap/core/NameClassPairCallbackHandler.java index f9a2055d..43bcb252 100644 --- a/core/src/main/java/org/springframework/ldap/core/NameClassPairCallbackHandler.java +++ b/core/src/main/java/org/springframework/ldap/core/NameClassPairCallbackHandler.java @@ -20,24 +20,23 @@ import javax.naming.NameClassPair; import javax.naming.NamingException; /** - * Callback interface used by {@link LdapTemplate} search, list and listBindings - * methods. Implementations of this interface perform the actual work of - * extracting results from a single NameClassPair (a - * NameClassPair, Binding or - * SearchResult depending on the search operation) returned by an - * LDAP seach operation, such as search(), list(), and listBindings(). - * + * Callback interface used by {@link LdapTemplate} search, list and listBindings methods. + * Implementations of this interface perform the actual work of extracting results from a + * single NameClassPair (a NameClassPair, Binding + * or SearchResult depending on the search operation) returned by an LDAP + * seach operation, such as search(), list(), and listBindings(). + * * @author Mattias Hellborg Arthursson */ public interface NameClassPairCallbackHandler { + /** - * Handle one entry. This method will be called once for each entry returned - * by a search or list. - * - * @param nameClassPair - * the NameClassPair returned from the - * NamingEnumeration. + * Handle one entry. This method will be called once for each entry returned by a + * search or list. + * @param nameClassPair the NameClassPair returned from the + * NamingEnumeration. * @throws NamingException if an error occurs. */ void handleNameClassPair(NameClassPair nameClassPair) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/NameClassPairMapper.java b/core/src/main/java/org/springframework/ldap/core/NameClassPairMapper.java index d29312a3..77a19928 100644 --- a/core/src/main/java/org/springframework/ldap/core/NameClassPairMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/NameClassPairMapper.java @@ -21,24 +21,21 @@ import javax.naming.NamingException; /** * Responsible for mapping NameClassPair objects to beans. - * + * * @author Mattias Hellborg Arthursson */ public interface NameClassPairMapper { + /** * Map NameClassPair to an Object. The supplied - * NameClassPair is one of the results from a search - * operation (search, list or listBindings). Depending on which search - * operation is being performed, the NameClassPair might be a - * SearchResult, Binding or - * NameClassPair. - * - * @param nameClassPair - * NameClassPair from a search operation. + * NameClassPair is one of the results from a search operation (search, + * list or listBindings). Depending on which search operation is being performed, the + * NameClassPair might be a SearchResult, + * Binding or NameClassPair. + * @param nameClassPair NameClassPair from a search operation. * @return and Object built from the NameClassPair. - * @throws NamingException - * if one is encountered in the operation. + * @throws NamingException if one is encountered in the operation. */ - T mapFromNameClassPair(NameClassPair nameClassPair) - throws NamingException; + T mapFromNameClassPair(NameClassPair nameClassPair) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/ObjectRetrievalException.java b/core/src/main/java/org/springframework/ldap/core/ObjectRetrievalException.java index dbeeef84..63cfc45b 100644 --- a/core/src/main/java/org/springframework/ldap/core/ObjectRetrievalException.java +++ b/core/src/main/java/org/springframework/ldap/core/ObjectRetrievalException.java @@ -19,9 +19,9 @@ package org.springframework.ldap.core; import org.springframework.ldap.NamingException; /** - * Thrown by a {@link ContextMapperCallbackHandler} when it cannot retrieve an - * object from the given Binding. - * + * Thrown by a {@link ContextMapperCallbackHandler} when it cannot retrieve an object from + * the given Binding. + * * @author Ulrik Sandberg * @since 1.2 */ @@ -29,10 +29,8 @@ public class ObjectRetrievalException extends NamingException { /** * Create a new ObjectRetrievalException. - * - * @param msg - * the detail message - * + * @param msg the detail message + * */ public ObjectRetrievalException(String msg) { super(msg); @@ -40,11 +38,8 @@ public class ObjectRetrievalException extends NamingException { /** * Create a new ObjectRetrievalException. - * - * @param msg - * the detail message - * @param cause - * the root cause (if any) + * @param msg the detail message + * @param cause the root cause (if any) */ public ObjectRetrievalException(String msg, Throwable cause) { super(msg, cause); diff --git a/core/src/main/java/org/springframework/ldap/core/SearchExecutor.java b/core/src/main/java/org/springframework/ldap/core/SearchExecutor.java index f72d7221..72877a74 100644 --- a/core/src/main/java/org/springframework/ldap/core/SearchExecutor.java +++ b/core/src/main/java/org/springframework/ldap/core/SearchExecutor.java @@ -20,9 +20,9 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; /** - * Interface for delegating an actual search operation. The typical - * implementation of executeSearch would be something like: - * + * Interface for delegating an actual search operation. The typical implementation of + * executeSearch would be something like: + * *
      * SearchExecutor executor = new SearchExecutor(){
      *   public NamingEnumeration executeSearch(DirContext ctx) throws NamingException{
    @@ -30,23 +30,19 @@ import javax.naming.directory.DirContext;
      *   }
      * }
      * 
    - * + * * @see org.springframework.ldap.core.LdapTemplate#search(SearchExecutor, - * NameClassPairCallbackHandler) - * + * NameClassPairCallbackHandler) * @author Mattias Hellborg Arthursson */ public interface SearchExecutor { + /** * Execute the actual search. - * - * @param ctx - * the DirContext on which to work. - * @return the NamingEnumeration resulting from the search - * operation. - * @throws NamingException - * if the search results in one. + * @param ctx the DirContext on which to work. + * @return the NamingEnumeration resulting from the search operation. + * @throws NamingException if the search results in one. */ - NamingEnumeration executeSearch(DirContext ctx) - throws NamingException; + NamingEnumeration executeSearch(DirContext ctx) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/AbstractContextMapper.java b/core/src/main/java/org/springframework/ldap/core/support/AbstractContextMapper.java index e40cf158..996b759b 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/AbstractContextMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/support/AbstractContextMapper.java @@ -19,38 +19,32 @@ import org.springframework.ldap.core.ContextMapper; import org.springframework.ldap.core.DirContextOperations; /** - * Abstract superclass that may be used instead of implementing - * {@link ContextMapper} directly. Subclassing from this superclass, the - * supplied context will be automatically cast to - * DirContextOperations. Note that if you use your own + * Abstract superclass that may be used instead of implementing {@link ContextMapper} + * directly. Subclassing from this superclass, the supplied context will be automatically + * cast to DirContextOperations. Note that if you use your own * DirObjectFactory, this implementation will fail with a * ClassCastException. - * + * * @author Mattias Hellborg Arthursson - * + * */ public abstract class AbstractContextMapper implements ContextMapper { /** * {@inheritDoc} - * - * @throws ClassCastException - * if a custom DirObjectFactory implementation is - * used, causing the objects passed in be anything else than - * {@link DirContextOperations} instances. + * @throws ClassCastException if a custom DirObjectFactory implementation + * is used, causing the objects passed in be anything else than + * {@link DirContextOperations} instances. */ public final T mapFromContext(Object ctx) { return doMapFromContext((DirContextOperations) ctx); } /** - * Map a single DirContextOperation to an object. The - * supplied instance is the object supplied to - * {@link #mapFromContext(Object)} cast to a + * Map a single DirContextOperation to an object. The supplied instance + * is the object supplied to {@link #mapFromContext(Object)} cast to a * DirContextOperations. - * - * @param ctx - * the context to map to an object. + * @param ctx the context to map to an object. * @return an object built from the data in the context. */ protected abstract T doMapFromContext(DirContextOperations ctx); diff --git a/core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java b/core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java index 5c28b841..d37a0338 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java +++ b/core/src/main/java/org/springframework/ldap/core/support/AbstractContextSource.java @@ -45,30 +45,26 @@ import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** - * Abstract implementation of the {@link ContextSource} interface. By default, - * returns an authenticated - * DirContext implementation for both read-only and - * read-write operations. To have an anonymous environment created for read-only - * operations, set the anonymousReadOnly property to - * true. + * Abstract implementation of the {@link ContextSource} interface. By default, returns an + * authenticated DirContext implementation for both read-only and read-write + * operations. To have an anonymous environment created for read-only operations, set the + * anonymousReadOnly property to true. *

    - * Implementing classes need to implement - * {@link #getDirContextInstance(Hashtable)} to create a DirContext - * instance of the desired type. + * Implementing classes need to implement {@link #getDirContextInstance(Hashtable)} to + * create a DirContext instance of the desired type. *

    - * If an {@link AuthenticationSource} is set, this will be used for getting user - * principal and password for each new connection, otherwise a default one will - * be created using the specified userDn and password. + * If an {@link AuthenticationSource} is set, this will be used for getting user principal + * and password for each new connection, otherwise a default one will be created using the + * specified userDn and password. *

    - * Note: When using implementations of this class outside of a Spring - * Context it is necessary to call {@link #afterPropertiesSet()} when all - * properties are set, in order to finish up initialization. + * Note: When using implementations of this class outside of a Spring Context it is + * necessary to call {@link #afterPropertiesSet()} when all properties are set, in order + * to finish up initialization. * * @see org.springframework.ldap.core.LdapTemplate * @see org.springframework.ldap.core.support.DefaultDirObjectFactory * @see org.springframework.ldap.core.support.LdapContextSource * @see org.springframework.ldap.core.support.DirContextSource - * * @author Mattias Hellborg Arthursson * @author Adam Skogman * @author Ulrik Sandberg @@ -78,8 +74,11 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource private static final String DEFAULT_CONTEXT_FACTORY = "com.sun.jndi.ldap.LdapCtxFactory"; private static final Class DEFAULT_DIR_OBJECT_FACTORY = DefaultDirObjectFactory.class; + private static final boolean DONT_DISABLE_POOLING = false; + private static final boolean EXPLICITLY_DISABLE_POOLING = true; + private static final int DEFAULT_BUFFER_SIZE = 1024; private Class dirObjectFactory = DEFAULT_DIR_OBJECT_FACTORY; @@ -127,27 +126,30 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource public AbstractContextSource() { try { contextFactory = Class.forName(DEFAULT_CONTEXT_FACTORY); - } catch (ClassNotFoundException e) { + } + catch (ClassNotFoundException e) { LOG.trace("The default for contextFactory cannot be resolved", e); } } public DirContext getContext(String principal, String credentials) { - // This method is typically called for authentication purposes, which means that we + // This method is typically called for authentication purposes, which means that + // we // should explicitly disable pooling in case passwords are changed (LDAP-183). return doGetContext(principal, credentials, EXPLICITLY_DISABLE_POOLING); } private DirContext doGetContext(String principal, String credentials, boolean explicitlyDisablePooling) { Hashtable env = getAuthenticatedEnv(principal, credentials); - if(explicitlyDisablePooling) { + if (explicitlyDisablePooling) { env.remove(SUN_LDAP_POOLING_FLAG); } DirContext ctx = createContext(env); try { - DirContext processedDirContext = authenticationStrategy.processContextAfterCreation(ctx, principal, credentials); + DirContext processedDirContext = authenticationStrategy.processContextAfterCreation(ctx, principal, + credentials); return processedDirContext; } catch (NamingException e) { @@ -163,9 +165,7 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource */ public DirContext getReadOnlyContext() { if (!anonymousReadOnly) { - return doGetContext( - authenticationSource.getPrincipal(), - authenticationSource.getCredentials(), + return doGetContext(authenticationSource.getPrincipal(), authenticationSource.getCredentials(), DONT_DISABLE_POOLING); } else { @@ -179,18 +179,15 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource * @see org.springframework.ldap.core.ContextSource#getReadWriteContext() */ public DirContext getReadWriteContext() { - return doGetContext( - authenticationSource.getPrincipal(), - authenticationSource.getCredentials(), + return doGetContext(authenticationSource.getPrincipal(), authenticationSource.getCredentials(), DONT_DISABLE_POOLING); } /** - * Default implementation of setting the environment up to be authenticated. - * This method should typically NOT be overridden; any customization to the - * authentication mechanism should be managed by setting a different + * Default implementation of setting the environment up to be authenticated. This + * method should typically NOT be overridden; any customization to the authentication + * mechanism should be managed by setting a different * {@link DirContextAuthenticationStrategy} on this instance. - * * @param env the environment to modify. * @param principal the principal to authenticate with. * @param credentials the credentials to authenticate with. @@ -208,7 +205,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Close the context and swallow any exceptions. - * * @param ctx the DirContext to close. */ private void closeContext(DirContext ctx) { @@ -225,7 +221,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Assemble a valid url String from all registered urls to add as * PROVIDER_URL to the environment. - * * @param ldapUrls all individual url Strings. * @return the full url String */ @@ -252,41 +247,45 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource Attributes attributes = component.toAttributes(); - // Loop through all attribute of the rdn (usually just one, but more are supported by RFC) + // Loop through all attribute of the rdn (usually just one, but more are + // supported by RFC) NamingEnumeration allAttributes = attributes.getAll(); - while(allAttributes.hasMoreElements()) { + while (allAttributes.hasMoreElements()) { Attribute oneAttribute = allAttributes.nextElement(); String encodedAttributeName = nameEncodeForUrl(oneAttribute.getID()); - // Loop through all values of the attribute (usually just one, but more are supported by RFC) - NamingEnumeration allValues; + // Loop through all values of the attribute (usually just one, but more + // are supported by RFC) + NamingEnumeration allValues; try { allValues = oneAttribute.getAll(); - } catch (NamingException e) { + } + catch (NamingException e) { throw new UncategorizedLdapException("Unexpected error occurred formatting base URL", e); } - while(allValues.hasMoreElements()) { + while (allValues.hasMoreElements()) { sb.append(encodedAttributeName).append('='); Object oneValue = allValues.nextElement(); if (oneValue instanceof String) { String oneString = (String) oneValue; sb.append(nameEncodeForUrl(oneString)); - } else { + } + else { throw new IllegalArgumentException("Binary attributes not supported for base URL"); } - if(allValues.hasMoreElements()) { + if (allValues.hasMoreElements()) { sb.append('+'); } } - if(allAttributes.hasMoreElements()) { + if (allAttributes.hasMoreElements()) { sb.append('+'); } } - if(it.hasPrevious()) { + if (it.hasPrevious()) { sb.append(','); } } @@ -298,28 +297,30 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource String ldapEncoded = LdapEncoder.nameEncode(value); URI valueUri = new URI(null, null, ldapEncoded, null); return valueUri.toString(); - } catch (URISyntaxException e) { + } + catch (URISyntaxException e) { throw new UncategorizedLdapException("This really shouldn't happen - report this", e); } } /** - * Set the base suffix from which all operations should origin. If a base - * suffix is set, you will not have to (and, indeed, must not) specify the - * full distinguished names in any operations performed. - * + * Set the base suffix from which all operations should origin. If a base suffix is + * set, you will not have to (and, indeed, must not) specify the full distinguished + * names in any operations performed. * @param base the base suffix. */ public void setBase(String base) { if (base != null) { this.base = LdapUtils.newLdapName(base); - } else { + } + else { this.base = LdapUtils.emptyLdapName(); } } /** - * @deprecated {@link DistinguishedName} and associated classes and methods are deprecated as of 2.0. + * @deprecated {@link DistinguishedName} and associated classes and methods are + * deprecated as of 2.0. */ @Override public DistinguishedName getBaseLdapPath() { @@ -338,11 +339,9 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Create a DirContext using the supplied environment. - * * @param environment the LDAP environment to use when creating the * DirContext. - * @return a new DirContext implementation initialized with the supplied - * environment. + * @return a new DirContext implementation initialized with the supplied environment. */ protected DirContext createContext(Hashtable environment) { DirContext ctx = null; @@ -366,7 +365,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Set the context factory. Default is com.sun.jndi.ldap.LdapCtxFactory. - * * @param contextFactory the context factory used when creating Contexts. */ public void setContextFactory(Class contextFactory) { @@ -375,7 +373,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Get the context factory. - * * @return the context factory used when creating Contexts. */ public Class getContextFactory() { @@ -383,14 +380,12 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * Set the DirObjectFactory to use. Default is - * {@link DefaultDirObjectFactory}. The specified class needs to be an - * implementation of javax.naming.spi.DirObjectFactory. Note: Setting - * this value to null may have cause connection leaks when using + * Set the DirObjectFactory to use. Default is {@link DefaultDirObjectFactory}. The + * specified class needs to be an implementation of javax.naming.spi.DirObjectFactory. + * Note: Setting this value to null may have cause connection leaks when using * ContextMapper methods in LdapTemplate. - * - * @param dirObjectFactory the DirObjectFactory to be used. Null means that - * no DirObjectFactory will be used. + * @param dirObjectFactory the DirObjectFactory to be used. Null means that no + * DirObjectFactory will be used. */ public void setDirObjectFactory(Class dirObjectFactory) { this.dirObjectFactory = dirObjectFactory; @@ -398,7 +393,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Get the DirObjectFactory to use. - * * @return the DirObjectFactory to be used. null means that no * DirObjectFactory will be used. */ @@ -407,10 +401,10 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * Checks that all necessary data is set and that there is no compatibility - * issues, after which the instance is initialized. Note that you need to - * call this method explicitly after setting all desired properties if using - * the class outside of a Spring Context. + * Checks that all necessary data is set and that there is no compatibility issues, + * after which the instance is initialized. Note that you need to call this method + * explicitly after setting all desired properties if using the class outside of a + * Spring Context. */ public void afterPropertiesSet() { if (ObjectUtils.isEmpty(urls)) { @@ -427,7 +421,8 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } if (!anonymousReadOnly) { if (password == null) { - throw new IllegalArgumentException("Property 'password' cannot be null. To use a blank password, please ensure it is set to \"\""); + throw new IllegalArgumentException( + "Property 'password' cannot be null. To use a blank password, please ensure it is set to \"\""); } if (!StringUtils.hasText(password)) { LOG.info("Property 'password' not set - " + "blank password will be used"); @@ -477,7 +472,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Set the password (credentials) to use for getting authenticated contexts. - * * @param password the password. */ public void setPassword(String password) { @@ -493,9 +487,8 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * Set the user distinguished name (principal) to use for getting - * authenticated contexts. - * + * Set the user distinguished name (principal) to use for getting authenticated + * contexts. * @param userDn the user distinguished name. */ public void setUserDn(String userDn) { @@ -503,9 +496,8 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * Gets the user distinguished name (principal) to use for getting - * authenticated contexts. - * + * Gets the user distinguished name (principal) to use for getting authenticated + * contexts. * @return the user distinguished name. */ public String getUserDn() { @@ -513,9 +505,7 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * Set the urls of the LDAP servers. Use this method if several servers are - * required. - * + * Set the urls of the LDAP servers. Use this method if several servers are required. * @param urls the urls of all servers. */ public void setUrls(String[] urls) { @@ -524,7 +514,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Get the urls of the LDAP servers. - * * @return the urls of all servers. */ public String[] getUrls() { @@ -532,9 +521,7 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * Set the url of the LDAP server. Utility method if only one server is - * used. - * + * Set the url of the LDAP server. Utility method if only one server is used. * @param url the url of the LDAP server. */ public void setUrl(String url) { @@ -542,21 +529,19 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * Set whether the pooling flag should be set, enabling the built-in LDAP - * connection pooling. Default is false. The built-in LDAP - * connection pooling suffers from a number of deficiencies, e.g. no - * connection validation. Also, enabling this flag when using TLS - * connections will explicitly not work. Consider using the Spring LDAP - * PoolingContextSource as an alternative instead of enabling - * this flag. + * Set whether the pooling flag should be set, enabling the built-in LDAP connection + * pooling. Default is false. The built-in LDAP connection pooling + * suffers from a number of deficiencies, e.g. no connection validation. Also, + * enabling this flag when using TLS connections will explicitly not work. Consider + * using the Spring LDAP PoolingContextSource as an alternative instead + * of enabling this flag. *

    - * Note that since LDAP pooling is system wide, full configuration of this - * needs be done using system parameters as specified in the LDAP/JNDI - * documentation. Also note, that pooling is done on user dn basis, i.e. - * each individually authenticated connection will be pooled separately. - * This means that LDAP pooling will be most efficient using anonymous - * connections or connections authenticated using one single system user. - * + * Note that since LDAP pooling is system wide, full configuration of this needs be + * done using system parameters as specified in the LDAP/JNDI documentation. Also + * note, that pooling is done on user dn basis, i.e. each individually authenticated + * connection will be pooled separately. This means that LDAP pooling will be most + * efficient using anonymous connections or connections authenticated using one single + * system user. * @param pooled whether Contexts should be pooled. */ public void setPooled(boolean pooled) { @@ -565,7 +550,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Get whether the pooling flag should be set. - * * @return whether Contexts should be pooled. */ public boolean isPooled() { @@ -573,11 +557,10 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * If any custom environment properties are needed, these can be set using - * this method. - * - * @param baseEnvironmentProperties the base environment properties that should always be used when - * creating new Context instances. + * If any custom environment properties are needed, these can be set using this + * method. + * @param baseEnvironmentProperties the base environment properties that should always + * be used when creating new Context instances. */ public void setBaseEnvironmentProperties(Map baseEnvironmentProperties) { this.baseEnv = new Hashtable(baseEnvironmentProperties); @@ -602,9 +585,8 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Set the authentication source to use when retrieving user principal and * credentials. - * - * @param authenticationSource the {@link AuthenticationSource} that will - * provide user info. + * @param authenticationSource the {@link AuthenticationSource} that will provide user + * info. */ public void setAuthenticationSource(AuthenticationSource authenticationSource) { this.authenticationSource = authenticationSource; @@ -612,7 +594,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Get the authentication source. - * * @return the {@link AuthenticationSource} that will provide user info. */ public AuthenticationSource getAuthenticationSource() { @@ -620,37 +601,33 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource } /** - * Set whether environment properties should be cached between requsts for - * anonymous environment. Default is true; setting this - * property to false causes the environment Hashmap to be - * rebuilt from the current property settings of this instance between each - * request for an anonymous environment. - * - * @param cacheEnvironmentProperties true causes that the - * anonymous environment properties should be cached, false - * causes the Hashmap to be rebuilt for each request. + * Set whether environment properties should be cached between requsts for anonymous + * environment. Default is true; setting this property to + * false causes the environment Hashmap to be rebuilt from the current + * property settings of this instance between each request for an anonymous + * environment. + * @param cacheEnvironmentProperties true causes that the anonymous + * environment properties should be cached, false causes the Hashmap to + * be rebuilt for each request. */ public void setCacheEnvironmentProperties(boolean cacheEnvironmentProperties) { this.cacheEnvironmentProperties = cacheEnvironmentProperties; } /** - * Set whether an anonymous environment should be used for read-only - * operations. Default is false. - * - * @param anonymousReadOnly true if an anonymous environment - * should be used for read-only operations, false otherwise. + * Set whether an anonymous environment should be used for read-only operations. + * Default is false. + * @param anonymousReadOnly true if an anonymous environment should be + * used for read-only operations, false otherwise. */ public void setAnonymousReadOnly(boolean anonymousReadOnly) { this.anonymousReadOnly = anonymousReadOnly; } /** - * Get whether an anonymous environment should be used for read-only - * operations. - * - * @return true if an anonymous environment should be used for - * read-only operations, false otherwise. + * Get whether an anonymous environment should be used for read-only operations. + * @return true if an anonymous environment should be used for read-only + * operations, false otherwise. */ public boolean isAnonymousReadOnly() { return anonymousReadOnly; @@ -659,24 +636,20 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Set the {@link DirContextAuthenticationStrategy} to use for preparing the * environment and processing the created DirContext instances. - * - * @param authenticationStrategy the - * {@link DirContextAuthenticationStrategy} to use; default is - * {@link SimpleDirContextAuthenticationStrategy}. + * @param authenticationStrategy the {@link DirContextAuthenticationStrategy} to use; + * default is {@link SimpleDirContextAuthenticationStrategy}. */ public void setAuthenticationStrategy(DirContextAuthenticationStrategy authenticationStrategy) { this.authenticationStrategy = authenticationStrategy; } /** - * Set the method to handle referrals. Default is 'ignore'; setting this - * flag to 'follow' will enable referrals to be automatically followed. Note - * that this might require particular name server setup in order to work - * (the referred URLs will need to be automatically found using standard DNS - * resolution). - * @param referral the value to set the system property - * Context.REFERRAL to, customizing the way that referrals are - * handled. + * Set the method to handle referrals. Default is 'ignore'; setting this flag to + * 'follow' will enable referrals to be automatically followed. Note that this might + * require particular name server setup in order to work (the referred URLs will need + * to be automatically found using standard DNS resolution). + * @param referral the value to set the system property Context.REFERRAL + * to, customizing the way that referrals are handled. */ public void setReferral(String referral) { this.referral = referral; @@ -685,7 +658,6 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource /** * Implement in subclass to create a DirContext of the desired type (e.g. * InitialDirContext or InitialLdapContext). - * * @param environment the environment to use when creating the instance. * @return a new DirContext instance. * @throws NamingException if one is encountered when creating the instance. @@ -701,5 +673,7 @@ public abstract class AbstractContextSource implements BaseLdapPathContextSource public String getCredentials() { return password; } + } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/AbstractTlsDirContextAuthenticationStrategy.java b/core/src/main/java/org/springframework/ldap/core/support/AbstractTlsDirContextAuthenticationStrategy.java index 3cd2ac65..47b80322 100755 --- a/core/src/main/java/org/springframework/ldap/core/support/AbstractTlsDirContextAuthenticationStrategy.java +++ b/core/src/main/java/org/springframework/ldap/core/support/AbstractTlsDirContextAuthenticationStrategy.java @@ -33,39 +33,35 @@ import java.lang.reflect.Proxy; import java.util.Hashtable; /** - * Abstract superclass for {@link DirContextAuthenticationStrategy} - * implementations that apply TLS security to the connections. The supported TLS - * behavior differs between servers. E.g., some servers expect the TLS - * connection be shut down gracefully before the actual target context is - * closed, whereas other servers do not support that. The - * shutdownTlsGracefully property controls this behavior; the - * property defaults to false. + * Abstract superclass for {@link DirContextAuthenticationStrategy} implementations that + * apply TLS security to the connections. The supported TLS behavior differs between + * servers. E.g., some servers expect the TLS connection be shut down gracefully before + * the actual target context is closed, whereas other servers do not support that. The + * shutdownTlsGracefully property controls this behavior; the property + * defaults to false. *

    - * The SSLSocketFactory used for TLS negotiation can be customized - * using the sslSocketFactory property. This allows for example a - * socket factory that can load the keystore/truststore using the Spring - * Resource abstraction. This provides a much more Spring-like strategy for - * configuring PKI credentials for authentication, in addition to allowing - * application-specific keystores and truststores running in the same JVM. + * The SSLSocketFactory used for TLS negotiation can be customized using the + * sslSocketFactory property. This allows for example a socket factory that + * can load the keystore/truststore using the Spring Resource abstraction. This provides a + * much more Spring-like strategy for configuring PKI credentials for authentication, in + * addition to allowing application-specific keystores and truststores running in the same + * JVM. *

    - * In some rare occasions there is a need to supply a - * HostnameVerifier to the TLS processing instructions in order to - * have the returned certificate properly validated. If a - * HostnameVerifier is supplied to - * {@link #setHostnameVerifier(HostnameVerifier)}, that will be applied to the - * processing. + * In some rare occasions there is a need to supply a HostnameVerifier to the + * TLS processing instructions in order to have the returned certificate properly + * validated. If a HostnameVerifier is supplied to + * {@link #setHostnameVerifier(HostnameVerifier)}, that will be applied to the processing. *

    - * For further information regarding TLS, refer to this + * For further information regarding TLS, refer to + * this * page. *

    - * NB: TLS negotiation is an expensive process, which is why you will - * most likely want to use connection pooling, to make sure new connections are - * not created for each individual request. It is imperative however, that the - * built-in LDAP connection pooling is not used in combination with the TLS - * AuthenticationStrategy implementations - this will not work. You should use - * the Spring LDAP PoolingContextSource instead. - * + * NB: TLS negotiation is an expensive process, which is why you will most likely + * want to use connection pooling, to make sure new connections are not created for each + * individual request. It is imperative however, that the built-in LDAP connection pooling + * is not used in combination with the TLS AuthenticationStrategy implementations - this + * will not work. You should use the Spring LDAP PoolingContextSource instead. + * * @author Mattias Hellborg Arthursson */ public abstract class AbstractTlsDirContextAuthenticationStrategy implements DirContextAuthenticationStrategy { @@ -78,24 +74,21 @@ public abstract class AbstractTlsDirContextAuthenticationStrategy implements Dir /** SSL socket factory to use for startTLS negotiation */ private SSLSocketFactory sslSocketFactory; - + /** - * Specify whether the TLS should be shut down gracefully before the target - * context is closed. Defaults to false. - * - * @param shutdownTlsGracefully true to shut down the TLS - * connection explicitly, false closes the target context - * immediately. + * Specify whether the TLS should be shut down gracefully before the target context is + * closed. Defaults to false. + * @param shutdownTlsGracefully true to shut down the TLS connection + * explicitly, false closes the target context immediately. */ public void setShutdownTlsGracefully(boolean shutdownTlsGracefully) { this.shutdownTlsGracefully = shutdownTlsGracefully; } /** - * Set the optional - * HostnameVerifier to use for verifying incoming certificates. Defaults to null - * , meaning that the default hostname verification will take place. - * + * Set the optional HostnameVerifier to use for verifying incoming + * certificates. Defaults to null , meaning that the default hostname + * verification will take place. * @param hostnameVerifier The HostnameVerifier to use, if any. */ public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { @@ -103,25 +96,32 @@ public abstract class AbstractTlsDirContextAuthenticationStrategy implements Dir } /** - * Sets the optional SSL socket factory used for startTLS negotiation. - * Defaults to null to indicate that the default socket factory - * provided by the underlying JSSE provider should be used. + * Sets the optional SSL socket factory used for startTLS negotiation. Defaults to + * null to indicate that the default socket factory provided by the + * underlying JSSE provider should be used. * @param sslSocketFactory SSL socket factory to use, if any. */ public void setSslSocketFactory(final SSLSocketFactory sslSocketFactory) { this.sslSocketFactory = sslSocketFactory; } - - /* (non-Javadoc) - * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy#setupEnvironment(java.util.Hashtable, java.lang.String, java.lang.String) + + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy# + * setupEnvironment(java.util.Hashtable, java.lang.String, java.lang.String) */ public final void setupEnvironment(Hashtable env, String userDn, String password) { // Nothing to do in this implementation - authentication should take // place after TLS has been negotiated. } - /* (non-Javadoc) - * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy#processContextAfterCreation(javax.naming.directory.DirContext, java.lang.String, java.lang.String) + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy# + * processContextAfterCreation(javax.naming.directory.DirContext, java.lang.String, + * java.lang.String) */ public final DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) throws NamingException { @@ -133,16 +133,17 @@ public abstract class AbstractTlsDirContextAuthenticationStrategy implements Dir if (hostnameVerifier != null) { tlsResponse.setHostnameVerifier(hostnameVerifier); } - tlsResponse.negotiate(sslSocketFactory); // If null, the default SSL socket factory is used + tlsResponse.negotiate(sslSocketFactory); // If null, the default SSL + // socket factory is used applyAuthentication(ldapCtx, userDn, password); if (shutdownTlsGracefully) { // Wrap the target context in a proxy to intercept any calls // to 'close', so that we can shut down the TLS connection // gracefully first. - return (DirContext) Proxy.newProxyInstance(DirContextProxy.class.getClassLoader(), new Class[] { - LdapContext.class, DirContextProxy.class }, new TlsAwareDirContextProxy(ldapCtx, - tlsResponse)); + return (DirContext) Proxy.newProxyInstance(DirContextProxy.class.getClassLoader(), + new Class[] { LdapContext.class, DirContextProxy.class }, + new TlsAwareDirContextProxy(ldapCtx, tlsResponse)); } else { return ctx; @@ -161,9 +162,8 @@ public abstract class AbstractTlsDirContextAuthenticationStrategy implements Dir } /** - * Apply the actual authentication to the specified LdapContext - * . Typically, this will involve adding stuff to the environment. - * + * Apply the actual authentication to the specified LdapContext . + * Typically, this will involve adding stuff to the environment. * @param ctx the LdapContext instance. * @param userDn the user dn of the user to authenticate. * @param password the password of the user to authenticate. @@ -202,5 +202,7 @@ public abstract class AbstractTlsDirContextAuthenticationStrategy implements Dir return method.invoke(target, args); } } + } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/AggregateDirContextProcessor.java b/core/src/main/java/org/springframework/ldap/core/support/AggregateDirContextProcessor.java index c1cd32c3..6b218ca1 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/AggregateDirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/core/support/AggregateDirContextProcessor.java @@ -26,9 +26,9 @@ import java.util.List; /** * Manages a sequence of {@link DirContextProcessor} instances. Applies - * {@link #preProcess(DirContext)} and {@link #postProcess(DirContext)} - * respectively in sequence on the managed objects. - * + * {@link #preProcess(DirContext)} and {@link #postProcess(DirContext)} respectively in + * sequence on the managed objects. + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ @@ -38,9 +38,7 @@ public class AggregateDirContextProcessor implements DirContextProcessor { /** * Add the supplied DirContextProcessor to the list of managed objects. - * - * @param processor - * the DirContextpProcessor to add. + * @param processor the DirContextpProcessor to add. */ public void addDirContextProcessor(DirContextProcessor processor) { dirContextProcessors.add(processor); @@ -48,7 +46,6 @@ public class AggregateDirContextProcessor implements DirContextProcessor { /** * Get the list of managed {@link DirContextProcessor} instances. - * * @return the managed list of {@link DirContextProcessor} instances. */ public List getDirContextProcessors() { @@ -57,16 +54,17 @@ public class AggregateDirContextProcessor implements DirContextProcessor { /** * Set the list of managed {@link DirContextProcessor} instances. - * - * @param dirContextProcessors - * the list of {@link DirContextProcessor} instances to set. + * @param dirContextProcessors the list of {@link DirContextProcessor} instances to + * set. */ public void setDirContextProcessors(List dirContextProcessors) { this.dirContextProcessors = new ArrayList(dirContextProcessors); } /* - * @see org.springframework.ldap.core.DirContextProcessor#preProcess(javax.naming.directory.DirContext) + * @see + * org.springframework.ldap.core.DirContextProcessor#preProcess(javax.naming.directory + * .DirContext) */ public void preProcess(DirContext ctx) throws NamingException { for (DirContextProcessor processor : dirContextProcessors) { @@ -75,11 +73,13 @@ public class AggregateDirContextProcessor implements DirContextProcessor { } /* - * @see org.springframework.ldap.core.DirContextProcessor#postProcess(javax.naming.directory.DirContext) + * @see org.springframework.ldap.core.DirContextProcessor#postProcess(javax.naming. + * directory.DirContext) */ public void postProcess(DirContext ctx) throws NamingException { for (DirContextProcessor processor : dirContextProcessors) { processor.postProcess(ctx); } } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapNameAware.java b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapNameAware.java index f4383aac..275d7ea8 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapNameAware.java +++ b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapNameAware.java @@ -19,31 +19,29 @@ package org.springframework.ldap.core.support; import javax.naming.ldap.LdapName; /** - * Interface to be implemented by classes that want to have access to the base - * context used in the active ContextSource. There are several - * cases in which services may want to have access to the base context, e.g. - * when working with groups (groupOfNames objectclass), in which - * case the full DN of each group member needs to be specified in the attribute - * value. + * Interface to be implemented by classes that want to have access to the base context + * used in the active ContextSource. There are several cases in which + * services may want to have access to the base context, e.g. when working with groups + * (groupOfNames objectclass), in which case the full DN of each group member + * needs to be specified in the attribute value. *

    - * If a class implements this interface and a - * {@link BaseLdapPathBeanPostProcessor} is defined in the - * ApplicationContext, the default base path will automatically - * passed to the {@link #setBaseLdapPath(javax.naming.ldap.LdapName)} method on - * initialization. + * If a class implements this interface and a {@link BaseLdapPathBeanPostProcessor} is + * defined in the ApplicationContext, the default base path will + * automatically passed to the {@link #setBaseLdapPath(javax.naming.ldap.LdapName)} method + * on initialization. *

    * NB:The ContextSource needs to be a subclass of * {@link AbstractContextSource} for this mechanism to work. * - * * @author Mattias Hellborg Arthursson * @since 2.0 */ public interface BaseLdapNameAware { + /** - * Set the base LDAP path specified in the current - * ApplicationContext. + * Set the base LDAP path specified in the current ApplicationContext. * @param baseLdapPath the base path used in the ContextSource */ void setBaseLdapPath(LdapName baseLdapPath); + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathAware.java b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathAware.java index 73a3f299..a62d7148 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathAware.java +++ b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathAware.java @@ -18,34 +18,31 @@ package org.springframework.ldap.core.support; import org.springframework.ldap.core.DistinguishedName; /** - * Interface to be implemented by classes that want to have access to the base - * context used in the active ContextSource. There are several - * cases in which services may want to have access to the base context, e.g. - * when working with groups (groupOfNames objectclass), in which - * case the full DN of each group member needs to be specified in the attribute - * value. + * Interface to be implemented by classes that want to have access to the base context + * used in the active ContextSource. There are several cases in which + * services may want to have access to the base context, e.g. when working with groups + * (groupOfNames objectclass), in which case the full DN of each group member + * needs to be specified in the attribute value. *

    - * If a class implements this interface and a - * {@link BaseLdapPathBeanPostProcessor} is defined in the - * ApplicationContext, the default base path will automatically - * passed to the {@link #setBaseLdapPath(DistinguishedName)} method on + * If a class implements this interface and a {@link BaseLdapPathBeanPostProcessor} is + * defined in the ApplicationContext, the default base path will + * automatically passed to the {@link #setBaseLdapPath(DistinguishedName)} method on * initialization. *

    * NB:The ContextSource needs to be a subclass of * {@link AbstractContextSource} for this mechanism to work. - * - * + * * @author Mattias Hellborg Arthursson * @since 1.2 - * @deprecated {@link DistinguishedName} and associated classes and methods are deprecated as of 2.0. - * Use {@link BaseLdapNameAware} instead. + * @deprecated {@link DistinguishedName} and associated classes and methods are deprecated + * as of 2.0. Use {@link BaseLdapNameAware} instead. */ public interface BaseLdapPathAware { /** - * Set the base LDAP path specified in the current - * ApplicationContext. + * Set the base LDAP path specified in the current ApplicationContext. * @param baseLdapPath the base path used in the ContextSource */ void setBaseLdapPath(DistinguishedName baseLdapPath); + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessor.java b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessor.java index add8f357..62f2b242 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessor.java +++ b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessor.java @@ -30,25 +30,23 @@ import java.util.Collection; /** * This BeanPostProcessor checks each bean if it implements - * {@link BaseLdapNameAware} or {@link BaseLdapPathAware}. - * If it does, the default context base LDAP path will be determined, - * and that value will be injected to the {@link BaseLdapNameAware#setBaseLdapPath(javax.naming.ldap.LdapName)} - * or {@link BaseLdapPathAware#setBaseLdapPath(DistinguishedName)} method of the - * processed bean. + * {@link BaseLdapNameAware} or {@link BaseLdapPathAware}. If it does, the default context + * base LDAP path will be determined, and that value will be injected to the + * {@link BaseLdapNameAware#setBaseLdapPath(javax.naming.ldap.LdapName)} or + * {@link BaseLdapPathAware#setBaseLdapPath(DistinguishedName)} method of the processed + * bean. *

    - * If the baseLdapPath property of this - * BeanPostProcessor is set, that value will be used. Otherwise, in - * order to determine which base LDAP path to supply to the instance the - * ApplicationContext is searched for any beans that are - * implementations of {@link BaseLdapPathSource}. If one single occurrence is - * found, that instance is queried for its base path, and that is what will be - * injected. If more than one {@link BaseLdapPathSource} instance is configured - * in the ApplicationContext, the name of the one to use will need - * to be specified to the baseLdapPathSourceName property; - * otherwise the post processing will fail. If no {@link BaseLdapPathSource} - * implementing bean is found in the context and the basePath - * property is not set, post processing will also fail. - * + * If the baseLdapPath property of this BeanPostProcessor is + * set, that value will be used. Otherwise, in order to determine which base LDAP path to + * supply to the instance the ApplicationContext is searched for any beans + * that are implementations of {@link BaseLdapPathSource}. If one single occurrence is + * found, that instance is queried for its base path, and that is what will be injected. + * If more than one {@link BaseLdapPathSource} instance is configured in the + * ApplicationContext, the name of the one to use will need to be specified + * to the baseLdapPathSourceName property; otherwise the post processing will + * fail. If no {@link BaseLdapPathSource} implementing bean is found in the context and + * the basePath property is not set, post processing will also fail. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ @@ -64,7 +62,7 @@ public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, Applica @Override public Object postProcessBeforeInitialization(Object bean, String beanName) { - if(bean instanceof BaseLdapNameAware) { + if (bean instanceof BaseLdapNameAware) { BaseLdapNameAware baseLdapNameAware = (BaseLdapNameAware) bean; if (basePath != null) { @@ -74,7 +72,8 @@ public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, Applica BaseLdapPathSource ldapPathSource = getBaseLdapPathSourceFromApplicationContext(); baseLdapNameAware.setBaseLdapPath(LdapUtils.newLdapName(ldapPathSource.getBaseLdapName())); } - } else if (bean instanceof BaseLdapPathAware) { + } + else if (bean instanceof BaseLdapPathAware) { BaseLdapPathAware baseLdapPathAware = (BaseLdapPathAware) bean; if (basePath != null) { @@ -96,30 +95,32 @@ public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, Applica Collection beans = applicationContext.getBeansOfType(BaseLdapPathSource.class).values(); if (beans.isEmpty()) { throw new NoSuchBeanDefinitionException("No BaseLdapPathSource implementation definition found"); - } else if (beans.size() == 1) { + } + else if (beans.size() == 1) { return beans.iterator().next(); - } else { + } + else { BaseLdapPathSource found = null; // Try to find the correct one for (BaseLdapPathSource bean : beans) { - if(bean instanceof AbstractContextSource) { - if(found != null) { + if (bean instanceof AbstractContextSource) { + if (found != null) { // More than one found - nothing much to do. throw new NoSuchBeanDefinitionException( - "More than BaseLdapPathSource implementation definition found in current ApplicationContext; " + - "unable to determine the one to use. Please specify 'baseLdapPathSourceName'"); + "More than BaseLdapPathSource implementation definition found in current ApplicationContext; " + + "unable to determine the one to use. Please specify 'baseLdapPathSourceName'"); } found = bean; } } - if(found == null) { + if (found == null) { throw new NoSuchBeanDefinitionException( - "More than BaseLdapPathSource implementation definition found in current ApplicationContext; " + - "unable to determine the one to use (one of them should be an AbstractContextSource instance). " + - "Please specify 'baseLdapPathSourceName'"); + "More than BaseLdapPathSource implementation definition found in current ApplicationContext; " + + "unable to determine the one to use (one of them should be an AbstractContextSource instance). " + + "Please specify 'baseLdapPathSourceName'"); } return found; @@ -138,13 +139,13 @@ public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, Applica } /** - * Set the base path to be injected in all {@link BaseLdapPathAware} beans. - * If this property is not set, the default base path will be determined - * from any defined {@link BaseLdapPathSource} instances available in the + * Set the base path to be injected in all {@link BaseLdapPathAware} beans. If this + * property is not set, the default base path will be determined from any defined + * {@link BaseLdapPathSource} instances available in the * ApplicationContext. - * * @param basePath the base path. - * @deprecated {@link DistinguishedName} and associated classes and methods are deprecated as of 2.0. + * @deprecated {@link DistinguishedName} and associated classes and methods are + * deprecated as of 2.0. */ public void setBasePath(DistinguishedName basePath) { this.basePath = LdapUtils.newLdapName(basePath); @@ -155,12 +156,11 @@ public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, Applica } /** - * Set the name of the ContextSource bean to use for getting - * the base path. This method is typically useful if several ContextSource - * instances have been configured. - * - * @param contextSourceName the name of the ContextSource bean - * to use for determining the base path. + * Set the name of the ContextSource bean to use for getting the base + * path. This method is typically useful if several ContextSource instances have been + * configured. + * @param contextSourceName the name of the ContextSource bean to use for + * determining the base path. */ public void setBaseLdapPathSourceName(String contextSourceName) { this.baseLdapPathSourceName = contextSourceName; @@ -168,8 +168,8 @@ public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, Applica /** * Set the order value of this object for sorting purposes. - * - * @param order the order of this instance. Defaults to Ordered.LOWEST_PRECEDENCE. + * @param order the order of this instance. Defaults to + * Ordered.LOWEST_PRECEDENCE. * @see Ordered * @since 1.3.2 */ @@ -180,4 +180,5 @@ public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, Applica public int getOrder() { return order; } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathContextSource.java b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathContextSource.java index 1207e3c0..b80abdfa 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathContextSource.java +++ b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathContextSource.java @@ -18,9 +18,9 @@ package org.springframework.ldap.core.support; import org.springframework.ldap.core.ContextSource; /** - * Interface to be implemented by ContextSources that are capable - * of providing the base LDAP path. - * + * Interface to be implemented by ContextSources that are capable of + * providing the base LDAP path. + * * @author Mattias Hellborg Arthursson */ public interface BaseLdapPathContextSource extends ContextSource, BaseLdapPathSource { diff --git a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathSource.java b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathSource.java index f1086366..247bde6a 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathSource.java +++ b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathSource.java @@ -21,39 +21,37 @@ import org.springframework.ldap.core.DistinguishedName; import javax.naming.ldap.LdapName; /** - * Implementations of this interface are capable of providing a base LDAP path. - * The base LDAP path is the root path to which all LDAP operations performed on - * a particular context are relative. - * + * Implementations of this interface are capable of providing a base LDAP path. The base + * LDAP path is the root path to which all LDAP operations performed on a particular + * context are relative. + * * @see ContextSource - * * @author Mattias Hellborg Arthursson */ public interface BaseLdapPathSource { + /** * Get the base LDAP path as a {@link DistinguishedName}. - * - * @return the base LDAP path as a {@link DistinguishedName}. The path will - * be empty if no base path is specified. - * @deprecated {@link DistinguishedName} and associated classes and methods are deprecated as of 2.0. - * Use {@link #getBaseLdapName()} instead. + * @return the base LDAP path as a {@link DistinguishedName}. The path will be empty + * if no base path is specified. + * @deprecated {@link DistinguishedName} and associated classes and methods are + * deprecated as of 2.0. Use {@link #getBaseLdapName()} instead. */ DistinguishedName getBaseLdapPath(); /** * Get the base LDAP path as a {@link LdapName}. - * - * @return the base LDAP path as a {@link LdapName}. The path will - * be empty if no base path is specified. + * @return the base LDAP path as a {@link LdapName}. The path will be empty if no base + * path is specified. * @since 2.0 */ LdapName getBaseLdapName(); /** * Get the base LDAP path as a String. - * - * @return the base LDAP path as a An empty String will be returned if no - * base path is specified. + * @return the base LDAP path as a An empty String will be returned if no base path is + * specified. */ String getBaseLdapPathAsString(); + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/ContextMapperCallbackHandlerWithControls.java b/core/src/main/java/org/springframework/ldap/core/support/ContextMapperCallbackHandlerWithControls.java index 780160fd..51f8d8e9 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/ContextMapperCallbackHandlerWithControls.java +++ b/core/src/main/java/org/springframework/ldap/core/support/ContextMapperCallbackHandlerWithControls.java @@ -24,15 +24,14 @@ import javax.naming.NamingException; import javax.naming.ldap.HasControls; /** - * Currently only per request controls can be inspected via the post process - * method on a context processor. If a request control gives a different value - * for each search result, then this cannot be inspected using the existing - * support classes. An example control that requires this feature would be - * 1.3.6.1.4.1.42.2.27.9.5.8 Account usability control, that can be used with - * for example the Sun ONE or the OpenDS directory servers. - * + * Currently only per request controls can be inspected via the post process method on a + * context processor. If a request control gives a different value for each search result, + * then this cannot be inspected using the existing support classes. An example control + * that requires this feature would be 1.3.6.1.4.1.42.2.27.9.5.8 Account usability + * control, that can be used with for example the Sun ONE or the OpenDS directory servers. + * * The extended callback handler can pass hasControls to mapper. - * + * * @author Tim Terry * @author Ulrik Sandberg */ @@ -49,7 +48,7 @@ public class ContextMapperCallbackHandlerWithControls extends ContextMapperCa * @see org.springframework.ldap.core.ContextMapperCallbackHandler# * getObjectFromNameClassPair(javax.naming.NameClassPair) */ - public T getObjectFromNameClassPair(final NameClassPair nameClassPair) throws NamingException{ + public T getObjectFromNameClassPair(final NameClassPair nameClassPair) throws NamingException { if (!(nameClassPair instanceof Binding)) { throw new IllegalArgumentException("Parameter must be an instance of Binding"); } @@ -68,4 +67,5 @@ public class ContextMapperCallbackHandlerWithControls extends ContextMapperCa } return result; } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/ContextMapperWithControls.java b/core/src/main/java/org/springframework/ldap/core/support/ContextMapperWithControls.java index 089a774e..6246461c 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/ContextMapperWithControls.java +++ b/core/src/main/java/org/springframework/ldap/core/support/ContextMapperWithControls.java @@ -21,11 +21,11 @@ import javax.naming.NamingException; import javax.naming.ldap.HasControls; /** - * Extension of the {@link org.springframework.ldap.core.ContextMapper} interface that allows - * controls to be passed to the mapper implementation. Uses Java 5 covariant - * return types to override the return type of the - * {@link #mapFromContextWithControls(Object, javax.naming.ldap.HasControls)} method to be the - * type parameter T. + * Extension of the {@link org.springframework.ldap.core.ContextMapper} interface that + * allows controls to be passed to the mapper implementation. Uses Java 5 covariant return + * types to override the return type of the + * {@link #mapFromContextWithControls(Object, javax.naming.ldap.HasControls)} method to be + * the type parameter T. * * @author Tim Terry * @author Ulrik Sandberg @@ -33,5 +33,7 @@ import javax.naming.ldap.HasControls; * {@link #mapFromContextWithControls(Object, javax.naming.ldap.HasControls)} method */ public interface ContextMapperWithControls extends ContextMapper { + T mapFromContextWithControls(final Object ctx, final HasControls hasControls) throws NamingException; + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/CountNameClassPairCallbackHandler.java b/core/src/main/java/org/springframework/ldap/core/support/CountNameClassPairCallbackHandler.java index 48a3c51d..e1fce6a9 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/CountNameClassPairCallbackHandler.java +++ b/core/src/main/java/org/springframework/ldap/core/support/CountNameClassPairCallbackHandler.java @@ -21,18 +21,16 @@ import org.springframework.ldap.core.NameClassPairCallbackHandler; /** * A {@link NameClassPairCallbackHandler} for counting all returned entries. - * + * * @author Mattias Hellborg Arthursson - * + * */ -public class CountNameClassPairCallbackHandler implements - NameClassPairCallbackHandler { +public class CountNameClassPairCallbackHandler implements NameClassPairCallbackHandler { private int noOfRows = 0; /** * Get the number of rows that was returned by the search. - * * @return the number of entries that have been handled. */ public int getNoOfRows() { @@ -41,8 +39,9 @@ public class CountNameClassPairCallbackHandler implements /* * (non-Javadoc) - * - * @see org.springframework.ldap.SearchResultCallbackHandler#handleSearchResult(javax.naming.directory.SearchResult) + * + * @see org.springframework.ldap.SearchResultCallbackHandler#handleSearchResult(javax. + * naming.directory.SearchResult) */ public void handleNameClassPair(NameClassPair nameClassPair) { noOfRows++; diff --git a/core/src/main/java/org/springframework/ldap/core/support/DefaultDirObjectFactory.java b/core/src/main/java/org/springframework/ldap/core/support/DefaultDirObjectFactory.java index 1281789d..b6184966 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/DefaultDirObjectFactory.java +++ b/core/src/main/java/org/springframework/ldap/core/support/DefaultDirObjectFactory.java @@ -38,14 +38,14 @@ import java.util.Hashtable; * @author Mattias Hellborg Arthursson */ public class DefaultDirObjectFactory implements DirObjectFactory { + private static final Logger LOG = LoggerFactory.getLogger(DefaultDirObjectFactory.class); /** - * Key to use in the ContextSource implementation to store the value of the - * base path suffix, if any, in the Ldap Environment. - * - * @deprecated Use {@link BaseLdapNameAware} and - * {@link BaseLdapPathBeanPostProcessor} instead. + * Key to use in the ContextSource implementation to store the value of the base path + * suffix, if any, in the Ldap Environment. + * @deprecated Use {@link BaseLdapNameAware} and {@link BaseLdapPathBeanPostProcessor} + * instead. */ public static final String JNDI_ENV_BASE_PATH_KEY = "org.springframework.ldap.base.path"; @@ -54,11 +54,7 @@ public class DefaultDirObjectFactory implements DirObjectFactory { private static final String LDAPS_PROTOCOL_PREFIX = "ldaps://"; @Override - public final Object getObjectInstance( - Object obj, - Name name, - Context nameCtx, - Hashtable environment, + public final Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment, Attributes attrs) throws Exception { try { @@ -94,20 +90,18 @@ public class DefaultDirObjectFactory implements DirObjectFactory { } /** - * Construct a DirContextAdapter given the supplied paramters. The - * name is normally a JNDI CompositeName, which - * needs to be handled with particuclar care. Specifically the escaping of a - * CompositeName destroys proper escaping of Distinguished - * Names. Also, the name might contain referral information, in which case - * we need to separate the server information from the actual Distinguished - * Name so that we can create a representing DirContextAdapter. - * + * Construct a DirContextAdapter given the supplied paramters. The name + * is normally a JNDI CompositeName, which needs to be handled with + * particuclar care. Specifically the escaping of a CompositeName + * destroys proper escaping of Distinguished Names. Also, the name might contain + * referral information, in which case we need to separate the server information from + * the actual Distinguished Name so that we can create a representing + * DirContextAdapter. * @param attrs the attributes - * @param name the Name, typically a CompositeName, possibly - * including referral information. + * @param name the Name, typically a CompositeName, possibly including + * referral information. * @param nameInNamespace the Name in namespace. - * @return a {@link DirContextAdapter} representing the specified - * information. + * @return a {@link DirContextAdapter} representing the specified information. */ DirContextAdapter constructAdapterFromName(Attributes attrs, Name name, String nameInNamespace) { String nameString; @@ -118,14 +112,11 @@ public class DefaultDirObjectFactory implements DirObjectFactory { // problem. CompositeName.toString() completely screws up the // formatting // in some cases, particularly when backslashes are involved. - nameString = LdapUtils - .convertCompositeNameToString((CompositeName) name); + nameString = LdapUtils.convertCompositeNameToString((CompositeName) name); } else { - LOG - .warn("Expecting a CompositeName as input to getObjectInstance but received a '" - + name.getClass().toString() - + "' - using toString and proceeding with undefined results"); + LOG.warn("Expecting a CompositeName as input to getObjectInstance but received a '" + + name.getClass().toString() + "' - using toString and proceeding with undefined results"); nameString = name.toString(); } @@ -148,10 +139,8 @@ public class DefaultDirObjectFactory implements DirObjectFactory { nameString = pathString; } catch (URISyntaxException e) { - throw new IllegalArgumentException( - "Supplied name starts with protocol prefix indicating a referral," - + " but is not possible to parse to an URI", - e); + throw new IllegalArgumentException("Supplied name starts with protocol prefix indicating a referral," + + " but is not possible to parse to an URI", e); } if (LOG.isDebugEnabled()) { LOG.debug("Resulting name after removal of referral information: '" + nameString + "'"); @@ -165,7 +154,8 @@ public class DefaultDirObjectFactory implements DirObjectFactory { } @Override - public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception { + public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) + throws Exception { return null; } diff --git a/core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java b/core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java index 804397c6..d405adf4 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapper.java @@ -40,15 +40,14 @@ import java.util.Map; import java.util.Set; /** - * Utility class that helps with reading all attribute values from Active Directory using Incremental Retrieval of - * Multi-valued Properties. - *

    Example usage of this attribute mapper: - *

    + * Utility class that helps with reading all attribute values from Active Directory using
    + * Incremental Retrieval of Multi-valued Properties.
    + * 

    + * Example usage of this attribute mapper:

      *	 List values = DefaultIncrementalAttributeMapper.lookupAttributeValues(ldapTemplate, theDn, "oneAttribute");
      *	 Attributes attrs = DefaultIncrementalAttributeMapper.lookupAttributeValues(ldapTemplate, theDn, new Object[]{"oneAttribute", "anotherAttribute"});
    - * 
    - * For greater control, e.g. explicitly specifying the requested page size, create and use an instance yourself: - *
    + * 
    For greater control, e.g. explicitly specifying the requested page size, create + * and use an instance yourself:
      *
      *	  IncrementalAttributesMapper incrementalAttributeMapper = new DefaultIncrementalAttributeMapper(10, "someAttribute");
      *	  while (incrementalAttributeMapper.hasMore()) {
    @@ -58,27 +57,35 @@ import java.util.Set;
      *	  List values = incrementalAttributeMapper.getValues("someAttribute");
      * 
    *

    - * NOTE: Instances of this class are highly stateful and must not be reused or shared between threads in any way. + * NOTE: Instances of this class are highly stateful and must not be reused or + * shared between threads in any way. *

    - * NOTE: Instances of this class can only be used with lookups. No support is given for searches. + * NOTE: Instances of this class can only be used with lookups. No support + * is given for searches. *

    * * @author Marius Scurtescu * @author Mattias Hellborg Arthursson - * @see Incremental Retrieval of Multi-valued Properties - * @see #lookupAttributes(org.springframework.ldap.core.LdapOperations, javax.naming.Name, String[]) - * @see #lookupAttributeValues(org.springframework.ldap.core.LdapOperations, javax.naming.Name, String) + * @see Incremental + * Retrieval of Multi-valued Properties + * @see #lookupAttributes(org.springframework.ldap.core.LdapOperations, javax.naming.Name, + * String[]) + * @see #lookupAttributeValues(org.springframework.ldap.core.LdapOperations, + * javax.naming.Name, String) * @since 1.3.2 */ -public class DefaultIncrementalAttributesMapper implements IncrementalAttributesMapper { +public class DefaultIncrementalAttributesMapper + implements IncrementalAttributesMapper { + private final static Logger LOG = LoggerFactory.getLogger(DefaultIncrementalAttributesMapper.class); private Map stateMap = new LinkedHashMap(); + private Set rangedAttributesInNextIteration = new LinkedHashSet(); /** - * This guy will be used when an unmapped attribute is encountered. This really should never happen, - * but this saves us a number of null checks. + * This guy will be used when an unmapped attribute is encountered. This really should + * never happen, but this saves us a number of null checks. */ private static final IncrementalAttributeState NOT_FOUND_ATTRIBUTE_STATE = new IncrementalAttributeState() { @Override @@ -114,10 +121,8 @@ public class DefaultIncrementalAttributesMapper implements IncrementalAttributes /** * Create an instance for the requested attribute. - * - * @param attributeName the name of the attribute that this instance handles. - * This is the attribute name that will be requested, and whose - * values are managed. + * @param attributeName the name of the attribute that this instance handles. This is + * the attribute name that will be requested, and whose values are managed. */ public DefaultIncrementalAttributesMapper(String attributeName) { this(RangeOption.TERMINAL_END_OF_RANGE, attributeName); @@ -125,10 +130,8 @@ public class DefaultIncrementalAttributesMapper implements IncrementalAttributes /** * Create an instance for the requested attributes. - * - * @param attributeNames the name of the attributes that this instance handles. - * These are the attribute names that will be requested, and whose - * values are managed. + * @param attributeNames the name of the attributes that this instance handles. These + * are the attribute names that will be requested, and whose values are managed. */ public DefaultIncrementalAttributesMapper(String[] attributeNames) { this(RangeOption.TERMINAL_END_OF_RANGE, attributeNames); @@ -136,23 +139,21 @@ public class DefaultIncrementalAttributesMapper implements IncrementalAttributes /** * Create an instance for the requested attribute with a specific page size. - * - * @param pageSize the requested page size that will be included in range query attribute names. - * @param attributeName the name of the attribute that this instance handles. - * This is the attribute name that will be requested, and whose - * values are managed. + * @param pageSize the requested page size that will be included in range query + * attribute names. + * @param attributeName the name of the attribute that this instance handles. This is + * the attribute name that will be requested, and whose values are managed. */ public DefaultIncrementalAttributesMapper(int pageSize, String attributeName) { - this(pageSize, new String[]{attributeName}); + this(pageSize, new String[] { attributeName }); } /** * Create an instance for the requested attributes with a specific page size. - * - * @param pageSize the requested page size that will be included in range query attribute names. - * @param attributeNames the name of the attributes that this instance handles. - * These are the attribute names that will be requested, and whose - * values are managed. + * @param pageSize the requested page size that will be included in range query + * attribute names. + * @param attributeNames the name of the attributes that this instance handles. These + * are the attribute names that will be requested, and whose values are managed. */ public DefaultIncrementalAttributesMapper(int pageSize, String[] attributeNames) { for (String attributeName : attributeNames) { @@ -179,7 +180,8 @@ public class DefaultIncrementalAttributesMapper implements IncrementalAttributes if (attributeNameSplit.length == 1) { // No range specification for this attribute state.processValues(attributes, attributeName); - } else { + } + else { for (String option : attributeNameSplit) { RangeOption responseRange = RangeOption.parse(option); @@ -250,93 +252,95 @@ public class DefaultIncrementalAttributesMapper implements IncrementalAttributes } /** - * Lookup all values for the specified attribute, looping through the results incrementally if necessary. - * + * Lookup all values for the specified attribute, looping through the results + * incrementally if necessary. * @param ldapOperations The instance to use for performing the actual lookup. - * @param dn The distinguished name of the object to find. - * @param attribute name of the attribute to request. - * @return an Attributes instance, populated with all found values for the requested attribute. - * Never null, though the actual attribute may not be set if it was not - * set on the requested object. + * @param dn The distinguished name of the object to find. + * @param attribute name of the attribute to request. + * @return an Attributes instance, populated with all found values for the requested + * attribute. Never null, though the actual attribute may not be set if + * it was not set on the requested object. */ public static Attributes lookupAttributes(LdapOperations ldapOperations, String dn, String attribute) { return lookupAttributes(ldapOperations, LdapUtils.newLdapName(dn), attribute); } /** - * Lookup all values for the specified attributes, looping through the results incrementally if necessary. - * + * Lookup all values for the specified attributes, looping through the results + * incrementally if necessary. * @param ldapOperations The instance to use for performing the actual lookup. - * @param dn The distinguished name of the object to find. - * @param attributes names of the attributes to request. - * @return an Attributes instance, populated with all found values for the requested attributes. - * Never null, though the actual attributes may not be set if they was not - * set on the requested object. + * @param dn The distinguished name of the object to find. + * @param attributes names of the attributes to request. + * @return an Attributes instance, populated with all found values for the requested + * attributes. Never null, though the actual attributes may not be set if + * they was not set on the requested object. */ public static Attributes lookupAttributes(LdapOperations ldapOperations, String dn, String[] attributes) { return lookupAttributes(ldapOperations, LdapUtils.newLdapName(dn), attributes); } /** - * Lookup all values for the specified attribute, looping through the results incrementally if necessary. - * + * Lookup all values for the specified attribute, looping through the results + * incrementally if necessary. * @param ldapOperations The instance to use for performing the actual lookup. - * @param dn The distinguished name of the object to find. - * @param attribute name of the attribute to request. - * @return an Attributes instance, populated with all found values for the requested attribute. - * Never null, though the actual attribute may not be set if it was not - * set on the requested object. + * @param dn The distinguished name of the object to find. + * @param attribute name of the attribute to request. + * @return an Attributes instance, populated with all found values for the requested + * attribute. Never null, though the actual attribute may not be set if + * it was not set on the requested object. */ public static Attributes lookupAttributes(LdapOperations ldapOperations, Name dn, String attribute) { - return lookupAttributes(ldapOperations, dn, new String[]{attribute}); + return lookupAttributes(ldapOperations, dn, new String[] { attribute }); } /** - * Lookup all values for the specified attributes, looping through the results incrementally if necessary. - * + * Lookup all values for the specified attributes, looping through the results + * incrementally if necessary. * @param ldapOperations The instance to use for performing the actual lookup. - * @param dn The distinguished name of the object to find. - * @param attributes names of the attributes to request. - * @return an Attributes instance, populated with all found values for the requested attributes. - * Never null, though the actual attributes may not be set if they was not - * set on the requested object. + * @param dn The distinguished name of the object to find. + * @param attributes names of the attributes to request. + * @return an Attributes instance, populated with all found values for the requested + * attributes. Never null, though the actual attributes may not be set if + * they was not set on the requested object. */ public static Attributes lookupAttributes(LdapOperations ldapOperations, Name dn, String[] attributes) { return loopForAllAttributeValues(ldapOperations, dn, attributes).getCollectedAttributes(); } /** - * Lookup all values for the specified attribute, looping through the results incrementally if necessary. - * + * Lookup all values for the specified attribute, looping through the results + * incrementally if necessary. * @param ldapOperations The instance to use for performing the actual lookup. - * @param dn The distinguished name of the object to find. - * @param attribute name of the attribute to request. - * @return a list with all attribute values found for the requested attribute. - * Never null, an empty list indicates that the attribute was not set or empty. + * @param dn The distinguished name of the object to find. + * @param attribute name of the attribute to request. + * @return a list with all attribute values found for the requested attribute. Never + * null, an empty list indicates that the attribute was not set or empty. */ public static List lookupAttributeValues(LdapOperations ldapOperations, String dn, String attribute) { return lookupAttributeValues(ldapOperations, LdapUtils.newLdapName(dn), attribute); } /** - * Lookup all values for the specified attribute, looping through the results incrementally if necessary. - * + * Lookup all values for the specified attribute, looping through the results + * incrementally if necessary. * @param ldapOperations The instance to use for performing the actual lookup. - * @param dn The distinguished name of the object to find. - * @param attribute name of the attribute to request. - * @return a list with all attribute values found for the requested attribute. - * Never null, an empty list indicates that the attribute was not set or empty. + * @param dn The distinguished name of the object to find. + * @param attribute name of the attribute to request. + * @return a list with all attribute values found for the requested attribute. Never + * null, an empty list indicates that the attribute was not set or empty. */ public static List lookupAttributeValues(LdapOperations ldapOperations, Name dn, String attribute) { - List values = loopForAllAttributeValues(ldapOperations, dn, new String[]{attribute}).getValues(attribute); - if(values == null) { + List values = loopForAllAttributeValues(ldapOperations, dn, new String[] { attribute }) + .getValues(attribute); + if (values == null) { values = Collections.emptyList(); } return values; } - private static DefaultIncrementalAttributesMapper loopForAllAttributeValues(LdapOperations ldapOperations, Name dn, String[] attributes) { + private static DefaultIncrementalAttributesMapper loopForAllAttributeValues(LdapOperations ldapOperations, Name dn, + String[] attributes) { DefaultIncrementalAttributesMapper mapper = new DefaultIncrementalAttributesMapper(attributes); while (mapper.hasMore()) { ldapOperations.lookup(dn, mapper.getAttributesForLookup(), mapper); @@ -345,14 +349,18 @@ public class DefaultIncrementalAttributesMapper implements IncrementalAttributes } /** - * This class keeps track of the state of an individual attribute in the process of collecting - * multi-value attributes using ranges. Holds the values collected thus far, the next applicable range, - * and the actual (requested) attribute name. + * This class keeps track of the state of an individual attribute in the process of + * collecting multi-value attributes using ranges. Holds the values collected thus + * far, the next applicable range, and the actual (requested) attribute name. */ private static final class DefaultIncrementalAttributeState implements IncrementalAttributeState { + private final String actualAttributeName; + private List values = null; + private final int pageSize; + boolean more = true; private RangeOption requestRange; @@ -415,16 +423,19 @@ public class DefaultIncrementalAttributesMapper implements IncrementalAttributes public List getValues() { if (values != null) { return new ArrayList(values); - } else { + } + else { return null; } } + } /** * @author Mattias Hellborg Arthursson */ private interface IncrementalAttributeState { + boolean hasMore(); void calculateNextRange(RangeOption responseRange); @@ -436,5 +447,7 @@ public class DefaultIncrementalAttributesMapper implements IncrementalAttributes void processValues(Attributes attributes, String attributeName) throws NamingException; List getValues(); + } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java b/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java index 1c98c594..c6351231 100755 --- a/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java +++ b/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java @@ -22,14 +22,14 @@ import javax.naming.ldap.LdapContext; /** * Default implementation of TLS authentication. Applies SIMPLE * authentication on top of the negotiated TLS session. Refer to - * {@link AbstractTlsDirContextAuthenticationStrategy} for configuration - * options. - * + * {@link AbstractTlsDirContextAuthenticationStrategy} for configuration options. + * * @author Mattias Hellborg Arthursson * @see AbstractTlsDirContextAuthenticationStrategy * @see AbstractContextSource */ public class DefaultTlsDirContextAuthenticationStrategy extends AbstractTlsDirContextAuthenticationStrategy { + private static final String SIMPLE_AUTHENTICATION = "simple"; protected void applyAuthentication(LdapContext ctx, String userDn, String password) throws NamingException { diff --git a/core/src/main/java/org/springframework/ldap/core/support/DelegatingBaseLdapPathContextSourceSupport.java b/core/src/main/java/org/springframework/ldap/core/support/DelegatingBaseLdapPathContextSourceSupport.java index 14c30b7d..fae19755 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/DelegatingBaseLdapPathContextSourceSupport.java +++ b/core/src/main/java/org/springframework/ldap/core/support/DelegatingBaseLdapPathContextSourceSupport.java @@ -22,8 +22,8 @@ import org.springframework.ldap.core.DistinguishedName; import javax.naming.ldap.LdapName; /** - * Support class to provide {@link BaseLdapPathSource} functionality to ContextSource instances - * that act as proxies. + * Support class to provide {@link BaseLdapPathSource} functionality to ContextSource + * instances that act as proxies. * * @author Mattias Hellborg Arthursson * @since 2.0 @@ -39,9 +39,12 @@ public abstract class DelegatingBaseLdapPathContextSourceSupport implements Base private BaseLdapPathSource getTargetAsBaseLdapPathSource() { try { return (BaseLdapPathSource) getTarget(); - } catch (ClassCastException e) { - throw new UnsupportedOperationException("This operation is not supported on a target ContextSource that does not " + - " implement BaseLdapPathContextSource", e); + } + catch (ClassCastException e) { + throw new UnsupportedOperationException( + "This operation is not supported on a target ContextSource that does not " + + " implement BaseLdapPathContextSource", + e); } } @@ -59,4 +62,5 @@ public abstract class DelegatingBaseLdapPathContextSourceSupport implements Base public final String getBaseLdapPathAsString() { return getTargetAsBaseLdapPathSource().getBaseLdapPathAsString(); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/DigestMd5DirContextAuthenticationStrategy.java b/core/src/main/java/org/springframework/ldap/core/support/DigestMd5DirContextAuthenticationStrategy.java index c180a6c1..2340ebd6 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/DigestMd5DirContextAuthenticationStrategy.java +++ b/core/src/main/java/org/springframework/ldap/core/support/DigestMd5DirContextAuthenticationStrategy.java @@ -32,8 +32,10 @@ public class DigestMd5DirContextAuthenticationStrategy implements DirContextAuth /* * (non-Javadoc) - * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy#processContextAfterCreation(javax.naming.directory.DirContext, - * java.lang.String, java.lang.String) + * + * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy# + * processContextAfterCreation(javax.naming.directory.DirContext, java.lang.String, + * java.lang.String) */ public DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) { return ctx; @@ -41,8 +43,9 @@ public class DigestMd5DirContextAuthenticationStrategy implements DirContextAuth /* * (non-Javadoc) - * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy#setupEnvironment(java.util.Hashtable, - * java.lang.String, java.lang.String) + * + * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy# + * setupEnvironment(java.util.Hashtable, java.lang.String, java.lang.String) */ public void setupEnvironment(Hashtable env, String userDn, String password) { env.put(Context.SECURITY_AUTHENTICATION, DIGEST_MD5_AUTHENTICATION); @@ -50,4 +53,5 @@ public class DigestMd5DirContextAuthenticationStrategy implements DirContextAuth env.put(Context.SECURITY_PRINCIPAL, userDn); env.put(Context.SECURITY_CREDENTIALS, password); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/DirContextAuthenticationStrategy.java b/core/src/main/java/org/springframework/ldap/core/support/DirContextAuthenticationStrategy.java index f8b3df3f..219ee6bb 100755 --- a/core/src/main/java/org/springframework/ldap/core/support/DirContextAuthenticationStrategy.java +++ b/core/src/main/java/org/springframework/ldap/core/support/DirContextAuthenticationStrategy.java @@ -23,63 +23,56 @@ import javax.naming.directory.DirContext; import java.util.Hashtable; /** - * A strategy to use when authenticating LDAP connections on creation. When - * authenticating LDAP connections different strategies are needed depending on - * the authentication mechanism used. Furthermore, depending on the mechanism - * the work to be done needs to be applied at different stages of the - * DirContext creation process. A - * DirContextAuthenticationStrategy contains the logic to perform a particular - * type of authentication mechanism and will be called by its - * {@link ContextSource} at appropriate stages of the process. - * + * A strategy to use when authenticating LDAP connections on creation. When authenticating + * LDAP connections different strategies are needed depending on the authentication + * mechanism used. Furthermore, depending on the mechanism the work to be done needs to be + * applied at different stages of the DirContext creation process. A + * DirContextAuthenticationStrategy contains the logic to perform a particular type of + * authentication mechanism and will be called by its {@link ContextSource} at appropriate + * stages of the process. + * * @author Mattias Hellborg Arthursson */ public interface DirContextAuthenticationStrategy { /** - * This method is responsible for preparing the environment to be used when - * creating the DirContext instance. The base environment - * (including URL, ContextFactory etc. will already be set, - * and this method is called just before the actual Context is to be - * created. - * - * @param env The Hashtable to be sent to the - * DirContext instance on initialization. Pre-configured with - * the basic settings; the implementation of this method is responsible for - * manipulating the environment as appropriate for the particular - * authentication mechanism. + * This method is responsible for preparing the environment to be used when creating + * the DirContext instance. The base environment (including URL, + * ContextFactory etc. will already be set, and this method is called + * just before the actual Context is to be created. + * @param env The Hashtable to be sent to the DirContext + * instance on initialization. Pre-configured with the basic settings; the + * implementation of this method is responsible for manipulating the environment as + * appropriate for the particular authentication mechanism. * @param userDn the user DN to authenticate, as received from the * {@link AuthenticationSource} of the {@link ContextSource}. * @param password the password to authenticate with, as received from the * {@link AuthenticationSource} of the {@link ContextSource}. * @throws NamingException if anything goes wrong. This will cause the - * DirContext creation to be aborted and the exception to be - * translated and rethrown. + * DirContext creation to be aborted and the exception to be translated + * and rethrown. */ void setupEnvironment(Hashtable env, String userDn, String password) throws NamingException; /** - * This method is responsible for post-processing the - * DirContext instance after it has been created. It will be - * called immediately after the instance has been created. Some - * authentication mechanisms, e.g. TLS, require particular stuff to happen - * before the actual target Context is closed. This method provides the - * possibility to replace or wrap the actual DirContext with a proxy so that - * any calls on it may be intercepted. - * - * @param ctx the freshly created DirContext instance. The - * actual implementation class (e.g. InitialLdapContext) - * depends on the {@link ContextSource} implementation. + * This method is responsible for post-processing the DirContext instance + * after it has been created. It will be called immediately after the instance has + * been created. Some authentication mechanisms, e.g. TLS, require particular stuff to + * happen before the actual target Context is closed. This method provides the + * possibility to replace or wrap the actual DirContext with a proxy so that any calls + * on it may be intercepted. + * @param ctx the freshly created DirContext instance. The actual + * implementation class (e.g. InitialLdapContext) depends on the + * {@link ContextSource} implementation. * @param userDn the user DN to authenticate, as received from the * {@link AuthenticationSource} of the {@link ContextSource}. * @param password the password to authenticate with, as received from the * {@link AuthenticationSource} of the {@link ContextSource}. * @return the DirContext, possibly modified, replaced or wrapped. * @throws NamingException if anything goes wrong. This will cause the - * DirContext creation to be aborted and the exception to be - * translated and rethrown. + * DirContext creation to be aborted and the exception to be translated + * and rethrown. */ - DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) - throws NamingException; + DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) throws NamingException; } diff --git a/core/src/main/java/org/springframework/ldap/core/support/DirContextSource.java b/core/src/main/java/org/springframework/ldap/core/support/DirContextSource.java index 6236e23a..22f95575 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/DirContextSource.java +++ b/core/src/main/java/org/springframework/ldap/core/support/DirContextSource.java @@ -22,27 +22,24 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; - /** - * ContextSource implementation which creates InitialDirContext instances, for - * LDAPv2 compatibility. For configuration information, see - * {@link org.springframework.ldap.core.support.AbstractContextSource AbstractContextSource}. - * + * ContextSource implementation which creates InitialDirContext instances, for LDAPv2 + * compatibility. For configuration information, see + * {@link org.springframework.ldap.core.support.AbstractContextSource + * AbstractContextSource}. + * * @see org.springframework.ldap.core.support.AbstractContextSource - * * @author Mattias Hellborg Arthursson */ public class DirContextSource extends AbstractContextSource { /** * Create a new InitialDirContext instance. - * - * @param environment - * the environment to use when creating the context. + * @param environment the environment to use when creating the context. * @return a new InitialDirContext implementation. */ - protected DirContext getDirContextInstance(Hashtable environment) - throws NamingException { + protected DirContext getDirContextInstance(Hashtable environment) throws NamingException { return new InitialDirContext(environment); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/ExternalTlsDirContextAuthenticationStrategy.java b/core/src/main/java/org/springframework/ldap/core/support/ExternalTlsDirContextAuthenticationStrategy.java index 4f766318..63ea449d 100755 --- a/core/src/main/java/org/springframework/ldap/core/support/ExternalTlsDirContextAuthenticationStrategy.java +++ b/core/src/main/java/org/springframework/ldap/core/support/ExternalTlsDirContextAuthenticationStrategy.java @@ -22,12 +22,12 @@ import javax.naming.ldap.LdapContext; /** * {@link DirContextAuthenticationStrategy} for using TLS and external (SASL) - * authentication. This implementation requires a client certificate to be - * pointed out using system variables, as described here. Refer to {@link AbstractTlsDirContextAuthenticationStrategy} for - * other configuration options. - * + * authentication. This implementation requires a client certificate to be pointed out + * using system variables, as described + * here. + * Refer to {@link AbstractTlsDirContextAuthenticationStrategy} for other configuration + * options. + * * @author Mattias Hellborg Arthursson * @see AbstractTlsDirContextAuthenticationStrategy * @see AbstractContextSource diff --git a/core/src/main/java/org/springframework/ldap/core/support/LdapContextSource.java b/core/src/main/java/org/springframework/ldap/core/support/LdapContextSource.java index 40eab7be..746ba0d2 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/LdapContextSource.java +++ b/core/src/main/java/org/springframework/ldap/core/support/LdapContextSource.java @@ -22,12 +22,12 @@ import javax.naming.ldap.InitialLdapContext; import java.util.Hashtable; /** - * ContextSource implementation which creates an InitialLdapContext - * instance. For configuration information, see - * {@link org.springframework.ldap.core.support.AbstractContextSource AbstractContextSource}. - * + * ContextSource implementation which creates an InitialLdapContext instance. + * For configuration information, see + * {@link org.springframework.ldap.core.support.AbstractContextSource + * AbstractContextSource}. + * * @see org.springframework.ldap.core.support.AbstractContextSource - * * @author Mattias Hellborg Arthursson * @author Adam Skogman * @author Ulrik Sandberg @@ -35,10 +35,12 @@ import java.util.Hashtable; public class LdapContextSource extends AbstractContextSource { /* - * @see org.springframework.ldap.support.AbstractContextSource#getDirContextInstance(java.util.Hashtable) + * @see + * org.springframework.ldap.support.AbstractContextSource#getDirContextInstance(java. + * util.Hashtable) */ - protected DirContext getDirContextInstance(Hashtable environment) - throws NamingException { + protected DirContext getDirContextInstance(Hashtable environment) throws NamingException { return new InitialLdapContext(environment, null); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/LdapOperationsCallback.java b/core/src/main/java/org/springframework/ldap/core/support/LdapOperationsCallback.java index 8a52d95d..50721939 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/LdapOperationsCallback.java +++ b/core/src/main/java/org/springframework/ldap/core/support/LdapOperationsCallback.java @@ -23,17 +23,20 @@ import org.springframework.ldap.core.LdapOperations; * * @author Mattias Hellborg Arthursson * @since 2.0 - * @see SingleContextSource#doWithSingleContext(org.springframework.ldap.core.ContextSource, LdapOperationsCallback) - * @see SingleContextSource#doWithSingleContext(org.springframework.ldap.core.ContextSource, LdapOperationsCallback, boolean, boolean, boolean) + * @see SingleContextSource#doWithSingleContext(org.springframework.ldap.core.ContextSource, + * LdapOperationsCallback) + * @see SingleContextSource#doWithSingleContext(org.springframework.ldap.core.ContextSource, + * LdapOperationsCallback, boolean, boolean, boolean) */ public interface LdapOperationsCallback { + /** - * Perform a sequence of LDAP operations on the supplied LdapOperations instance. The underlying DirContext - * that the operations will work on is guaranteed to always be exact same instance during the lifetime of this - * method. - * + * Perform a sequence of LDAP operations on the supplied LdapOperations instance. The + * underlying DirContext that the operations will work on is guaranteed to always be + * exact same instance during the lifetime of this method. * @param operations the LdapOperations instance to perform operations on. * @return The aggregated result of all the performed operations. */ T doWithLdapOperations(LdapOperations operations); + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/LookupAttemptingCallback.java b/core/src/main/java/org/springframework/ldap/core/support/LookupAttemptingCallback.java index 5ec37897..10b60a49 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/LookupAttemptingCallback.java +++ b/core/src/main/java/org/springframework/ldap/core/support/LookupAttemptingCallback.java @@ -26,19 +26,21 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; /** - * Attempts to perform an LDAP operation in the authenticated context, because - * Active Directory might allow bind with incorrect password (specifically empty - * password), and later refuse operations. We want to fail fast when - * authenticating. {@link #mapWithContext(javax.naming.directory.DirContext, org.springframework.ldap.core.LdapEntryIdentification)} - * returns the {@link DirContextOperations} instance that results from the lookup operation. This instance - * can be used to obtain information regarding the authenticated user. - * + * Attempts to perform an LDAP operation in the authenticated context, because Active + * Directory might allow bind with incorrect password (specifically empty password), and + * later refuse operations. We want to fail fast when authenticating. + * {@link #mapWithContext(javax.naming.directory.DirContext, org.springframework.ldap.core.LdapEntryIdentification)} + * returns the {@link DirContextOperations} instance that results from the lookup + * operation. This instance can be used to obtain information regarding the authenticated + * user. + * * @author Hugo Josefson * @author Mattias Hellborg Arthursson * @since 1.3.1 */ -public class LookupAttemptingCallback implements - AuthenticatedLdapEntryContextCallback, AuthenticatedLdapEntryContextMapper { +public class LookupAttemptingCallback + implements AuthenticatedLdapEntryContextCallback, AuthenticatedLdapEntryContextMapper { + @Override public void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { mapWithContext(ctx, ldapEntryIdentification); @@ -54,4 +56,5 @@ public class LookupAttemptingCallback implements throw LdapUtils.convertLdapException(e); } } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/RangeOption.java b/core/src/main/java/org/springframework/ldap/core/support/RangeOption.java index d85d1a3a..6355a8c0 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/RangeOption.java +++ b/core/src/main/java/org/springframework/ldap/core/support/RangeOption.java @@ -20,22 +20,25 @@ import java.util.regex.Pattern; import java.util.regex.Matcher; /** - * Attribute name Range Option used for Incremental Retrieval of - * Multi-valued Properties. + * Attribute name Range Option used for Incremental Retrieval of Multi-valued + * Properties. * * @author Marius Scurtescu - * * @see DefaultIncrementalAttributesMapper * @since 1.3.2 */ class RangeOption implements Comparable { + public static final int TERMINAL_END_OF_RANGE = -1; + public static final int TERMINAL_MISSING = -2; private int initial = 0; + private int terminal = TERMINAL_END_OF_RANGE; - private static final Pattern RANGE_PATTERN = Pattern.compile("^Range=([0-9]+)(-([0-9]+|\\*))?$", Pattern.CASE_INSENSITIVE); + private static final Pattern RANGE_PATTERN = Pattern.compile("^Range=([0-9]+)(-([0-9]+|\\*))?$", + Pattern.CASE_INSENSITIVE); public RangeOption(int initial) { this(initial, TERMINAL_END_OF_RANGE); @@ -51,7 +54,8 @@ class RangeOption implements Comparable { } if (terminal >= 0 && terminal < initial) { - throw new IllegalArgumentException("range-terminal cannot be smaller than range-initial: " + initial + "-" + terminal); + throw new IllegalArgumentException( + "range-terminal cannot be smaller than range-initial: " + initial + "-" + terminal); } this.initial = initial; @@ -93,7 +97,8 @@ class RangeOption implements Comparable { if (isTerminalEndOfRange()) { rangeBuilder.append('*'); - } else { + } + else { rangeBuilder.append(terminal); } } @@ -118,7 +123,8 @@ class RangeOption implements Comparable { if ("*".equals(terminalStr)) { terminal = TERMINAL_END_OF_RANGE; - } else { + } + else { terminal = Integer.parseInt(terminalStr); } } @@ -128,7 +134,8 @@ class RangeOption implements Comparable { public int compareTo(RangeOption that) { if (this.getInitial() != that.getInitial()) - throw new IllegalStateException("Ranges cannot be compared, range-initial not the same: " + this.toString() + " vs " + that.toString()); + throw new IllegalStateException("Ranges cannot be compared, range-initial not the same: " + this.toString() + + " vs " + that.toString()); if (this.getTerminal() == that.getTerminal()) { return 0; @@ -155,13 +162,17 @@ class RangeOption implements Comparable { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; RangeOption that = (RangeOption) o; - if (initial != that.initial) return false; - if (terminal != that.terminal) return false; + if (initial != that.initial) + return false; + if (terminal != that.terminal) + return false; return true; } @@ -187,4 +198,5 @@ class RangeOption implements Comparable { return new RangeOption(initial, terminal); } + } diff --git a/core/src/main/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategy.java b/core/src/main/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategy.java index d3714a5b..56c86510 100755 --- a/core/src/main/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategy.java +++ b/core/src/main/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategy.java @@ -20,12 +20,11 @@ import javax.naming.directory.DirContext; import java.util.Hashtable; /** - * The default {@link DirContextAuthenticationStrategy} implementation, setting - * the DirContext environment up for 'SIMPLE' authentication, and - * specifying the user DN and password as SECURITY_PRINCIPAL and - * SECURITY_CREDENTIALS respectively in the authenticated environment before the - * context is created. - * + * The default {@link DirContextAuthenticationStrategy} implementation, setting the + * DirContext environment up for 'SIMPLE' authentication, and specifying the + * user DN and password as SECURITY_PRINCIPAL and SECURITY_CREDENTIALS respectively in the + * authenticated environment before the context is created. + * * @author Mattias Hellborg Arthursson */ public class SimpleDirContextAuthenticationStrategy implements DirContextAuthenticationStrategy { @@ -34,8 +33,9 @@ public class SimpleDirContextAuthenticationStrategy implements DirContextAuthent /* * (non-Javadoc) - * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy#setupEnvironment(java.util.Hashtable, - * java.lang.String, java.lang.String) + * + * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy# + * setupEnvironment(java.util.Hashtable, java.lang.String, java.lang.String) */ public void setupEnvironment(Hashtable env, String userDn, String password) { env.put(Context.SECURITY_AUTHENTICATION, SIMPLE_AUTHENTICATION); @@ -45,8 +45,10 @@ public class SimpleDirContextAuthenticationStrategy implements DirContextAuthent /* * (non-Javadoc) - * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy#processContextAfterCreation(javax.naming.directory.DirContext, - * java.lang.String, java.lang.String) + * + * @see org.springframework.ldap.core.support.DirContextAuthenticationStrategy# + * processContextAfterCreation(javax.naming.directory.DirContext, java.lang.String, + * java.lang.String) */ public DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) { return ctx; diff --git a/core/src/main/java/org/springframework/ldap/core/support/SingleContextSource.java b/core/src/main/java/org/springframework/ldap/core/support/SingleContextSource.java index ff85e423..cae43e62 100644 --- a/core/src/main/java/org/springframework/ldap/core/support/SingleContextSource.java +++ b/core/src/main/java/org/springframework/ldap/core/support/SingleContextSource.java @@ -30,8 +30,8 @@ import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** - * A {@link ContextSource} to be used as a decorator around a target ContextSource - * to make sure the target is never actually closed. Useful when working with e.g. paged results, + * A {@link ContextSource} to be used as a decorator around a target ContextSource to make + * sure the target is never actually closed. Useful when working with e.g. paged results, * as these require the same target to be used. * * @author Mattias Hellborg Arthursson @@ -39,15 +39,17 @@ import java.lang.reflect.Proxy; public class SingleContextSource implements ContextSource, DisposableBean { private static final Logger LOG = LoggerFactory.getLogger(SingleContextSource.class); + private static final boolean DONT_USE_READ_ONLY = false; + private static final boolean DONT_IGNORE_PARTIAL_RESULT = false; + private static final boolean DONT_IGNORE_NAME_NOT_FOUND = false; private final DirContext ctx; /** * Constructor. - * * @param ctx the target DirContext. */ public SingleContextSource(DirContext ctx) { @@ -55,37 +57,33 @@ public class SingleContextSource implements ContextSource, DisposableBean { } /* - * @see org.springframework.ldap.ContextSource#getReadOnlyContext() - */ + * @see org.springframework.ldap.ContextSource#getReadOnlyContext() + */ public DirContext getReadOnlyContext() { return getNonClosingDirContextProxy(ctx); } /* - * @see org.springframework.ldap.ContextSource#getReadWriteContext() - */ + * @see org.springframework.ldap.ContextSource#getReadWriteContext() + */ public DirContext getReadWriteContext() { return getNonClosingDirContextProxy(ctx); } private DirContext getNonClosingDirContextProxy(DirContext context) { - return (DirContext) Proxy.newProxyInstance(DirContextProxy.class - .getClassLoader(), new Class[]{ - LdapUtils.getActualTargetClass(context), - DirContextProxy.class}, - new SingleContextSource.NonClosingDirContextInvocationHandler( - context)); + return (DirContext) Proxy.newProxyInstance(DirContextProxy.class.getClassLoader(), + new Class[] { LdapUtils.getActualTargetClass(context), DirContextProxy.class }, + new SingleContextSource.NonClosingDirContextInvocationHandler(context)); } public DirContext getContext(String principal, String credentials) { - throw new UnsupportedOperationException( - "Not a valid operation for this type of ContextSource"); + throw new UnsupportedOperationException("Not a valid operation for this type of ContextSource"); } /** - * Destroy method that allows the target DirContext to be cleaned up when - * the SingleContextSource is not going to be used any more. + * Destroy method that allows the target DirContext to be cleaned up when the + * SingleContextSource is not going to be used any more. */ public void destroy() { try { @@ -97,51 +95,60 @@ public class SingleContextSource implements ContextSource, DisposableBean { } /** - * Construct a SingleContextSource and execute the LdapOperationsCallback using the created instance. - * This makes sure the same connection will be used for all operations inside the LdapOperationsCallback, - * which is particularly useful when working with e.g. Paged Results as these typically require the exact - * same connection to be used for all requests involving the same cookie. - * The SingleContextSource instance will be properly disposed of once the operation has been completed. - *

    By default, the {@link org.springframework.ldap.core.ContextSource#getReadWriteContext()} method - * will be used to create the DirContext instance to operate on.

    - * + * Construct a SingleContextSource and execute the LdapOperationsCallback using the + * created instance. This makes sure the same connection will be used for all + * operations inside the LdapOperationsCallback, which is particularly useful when + * working with e.g. Paged Results as these typically require the exact same + * connection to be used for all requests involving the same cookie. The + * SingleContextSource instance will be properly disposed of once the operation has + * been completed. + *

    + * By default, the + * {@link org.springframework.ldap.core.ContextSource#getReadWriteContext()} method + * will be used to create the DirContext instance to operate on. + *

    * @param contextSource The target ContextSource to retrieve a DirContext from. * @param callback the callback to perform the Ldap operations. * @return the result returned from the callback. - * @see #doWithSingleContext(org.springframework.ldap.core.ContextSource, LdapOperationsCallback, boolean, boolean, boolean) + * @see #doWithSingleContext(org.springframework.ldap.core.ContextSource, + * LdapOperationsCallback, boolean, boolean, boolean) * @since 2.0 */ public static T doWithSingleContext(ContextSource contextSource, LdapOperationsCallback callback) { - return doWithSingleContext(contextSource, callback, DONT_USE_READ_ONLY, DONT_IGNORE_PARTIAL_RESULT, DONT_IGNORE_NAME_NOT_FOUND); + return doWithSingleContext(contextSource, callback, DONT_USE_READ_ONLY, DONT_IGNORE_PARTIAL_RESULT, + DONT_IGNORE_NAME_NOT_FOUND); } /** - * Construct a SingleContextSource and execute the LdapOperationsCallback using the created instance. - * This makes sure the same connection will be used for all operations inside the LdapOperationsCallback, - * which is particularly useful when working with e.g. Paged Results as these typically require the exact - * same connection to be used for all requests involving the same cookie.. - * The SingleContextSource instance will be properly disposed of once the operation has been completed. - * + * Construct a SingleContextSource and execute the LdapOperationsCallback using the + * created instance. This makes sure the same connection will be used for all + * operations inside the LdapOperationsCallback, which is particularly useful when + * working with e.g. Paged Results as these typically require the exact same + * connection to be used for all requests involving the same cookie.. The + * SingleContextSource instance will be properly disposed of once the operation has + * been completed. * @param contextSource The target ContextSource to retrieve a DirContext from * @param callback the callback to perform the Ldap operations - * @param useReadOnly if true, use the {@link org.springframework.ldap.core.ContextSource#getReadOnlyContext()} - * method on the target ContextSource to get the actual DirContext instance, if false, - * use {@link org.springframework.ldap.core.ContextSource#getReadWriteContext()}. - * @param ignorePartialResultException Used for populating this property on the created LdapTemplate instance. - * @param ignoreNameNotFoundException Used for populating this property on the created LdapTemplate instance. + * @param useReadOnly if true, use the + * {@link org.springframework.ldap.core.ContextSource#getReadOnlyContext()} method on + * the target ContextSource to get the actual DirContext instance, if + * false, use + * {@link org.springframework.ldap.core.ContextSource#getReadWriteContext()}. + * @param ignorePartialResultException Used for populating this property on the + * created LdapTemplate instance. + * @param ignoreNameNotFoundException Used for populating this property on the created + * LdapTemplate instance. * @return the result returned from the callback. * @since 2.0 */ - public static T doWithSingleContext(ContextSource contextSource, - LdapOperationsCallback callback, - boolean useReadOnly, - boolean ignorePartialResultException, - boolean ignoreNameNotFoundException) { + public static T doWithSingleContext(ContextSource contextSource, LdapOperationsCallback callback, + boolean useReadOnly, boolean ignorePartialResultException, boolean ignoreNameNotFoundException) { SingleContextSource singleContextSource; if (useReadOnly) { singleContextSource = new SingleContextSource(contextSource.getReadOnlyContext()); - } else { + } + else { singleContextSource = new SingleContextSource(contextSource.getReadWriteContext()); } @@ -151,19 +158,19 @@ public class SingleContextSource implements ContextSource, DisposableBean { try { return callback.doWithLdapOperations(ldapTemplate); - } finally { + } + finally { singleContextSource.destroy(); } } /** - * A proxy for DirContext forwarding all operation to the target DirContext, - * but making sure that no close operations will be performed. + * A proxy for DirContext forwarding all operation to the target DirContext, but + * making sure that no close operations will be performed. * * @author Mattias Hellborg Arthursson */ - public static class NonClosingDirContextInvocationHandler implements - InvocationHandler { + public static class NonClosingDirContextInvocationHandler implements InvocationHandler { private DirContext target; @@ -175,19 +182,21 @@ public class SingleContextSource implements ContextSource, DisposableBean { * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, * java.lang.reflect.Method, java.lang.Object[]) */ - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if (methodName.equals("getTargetContext")) { return target; - } else if (methodName.equals("equals")) { + } + else if (methodName.equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); - } else if (methodName.equals("hashCode")) { + } + else if (methodName.equals("hashCode")) { // Use hashCode of Connection proxy. return proxy.hashCode(); - } else if (methodName.equals("close")) { + } + else if (methodName.equals("close")) { // Never close the target context, as this class will only be // used for operations concerning the compensating transactions. return null; @@ -200,5 +209,7 @@ public class SingleContextSource implements ContextSource, DisposableBean { throw e.getTargetException(); } } + } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/AbsoluteFalseFilter.java b/core/src/main/java/org/springframework/ldap/filter/AbsoluteFalseFilter.java index c941f47b..74ac7b70 100644 --- a/core/src/main/java/org/springframework/ldap/filter/AbsoluteFalseFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/AbsoluteFalseFilter.java @@ -24,7 +24,9 @@ package org.springframework.ldap.filter; * @since 1.3.2 */ public class AbsoluteFalseFilter extends AbstractFilter { + public StringBuffer encode(StringBuffer buff) { return buff.append("(|)"); } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/AbsoluteTrueFilter.java b/core/src/main/java/org/springframework/ldap/filter/AbsoluteTrueFilter.java index ce6b06ec..e68531ca 100644 --- a/core/src/main/java/org/springframework/ldap/filter/AbsoluteTrueFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/AbsoluteTrueFilter.java @@ -24,8 +24,10 @@ package org.springframework.ldap.filter; * @since 1.3.2 */ public class AbsoluteTrueFilter extends AbstractFilter { + public StringBuffer encode(StringBuffer buff) { buff.append("(&)"); return buff; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/AbstractFilter.java b/core/src/main/java/org/springframework/ldap/filter/AbstractFilter.java index b9e7a01f..ef006fbf 100644 --- a/core/src/main/java/org/springframework/ldap/filter/AbstractFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/AbstractFilter.java @@ -17,9 +17,8 @@ package org.springframework.ldap.filter; /** - * Convenience class that implements most of the methods in the Filter - * interface. - * + * Convenience class that implements most of the methods in the Filter interface. + * * @author Adam Skogman */ public abstract class AbstractFilter implements Filter { @@ -37,4 +36,5 @@ public abstract class AbstractFilter implements Filter { public String toString() { return encode(); } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/AndFilter.java b/core/src/main/java/org/springframework/ldap/filter/AndFilter.java index 896182e3..f7331d1c 100644 --- a/core/src/main/java/org/springframework/ldap/filter/AndFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/AndFilter.java @@ -18,16 +18,16 @@ package org.springframework.ldap.filter; /** * A filter for a logical AND. Example: - * + * *
      *	 AndFilter filter = new AndFilter();
      *	 filter.and(new EqualsFilter("objectclass", "person");
      *	 filter.and(new EqualsFilter("cn", "Some CN");
      *	 System.out.println(filter.encode());	
      * 
    - * + * * would result in: (&(objectclass=person)(cn=Some CN)) - * + * * @see org.springframework.ldap.filter.EqualsFilter * @author Adam Skogman * @author Mattias Hellborg Arthursson @@ -45,13 +45,12 @@ public class AndFilter extends BinaryLogicalFilter { /** * Add a query to the AND expression. - * - * @param query The expression to AND with the rest of the AND:ed - * expressions. + * @param query The expression to AND with the rest of the AND:ed expressions. * @return This LdapAndQuery */ public AndFilter and(Filter query) { append(query); return this; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/BinaryLogicalFilter.java b/core/src/main/java/org/springframework/ldap/filter/BinaryLogicalFilter.java index 31548627..775f62fd 100644 --- a/core/src/main/java/org/springframework/ldap/filter/BinaryLogicalFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/BinaryLogicalFilter.java @@ -20,9 +20,9 @@ import java.util.LinkedList; import java.util.List; /** - * Abstract superclass for binary logical operations, that is "AND" - * and "OR" operations. - * + * Abstract superclass for binary logical operations, that is "AND" and + * "OR" operations. + * * @author Mattias Hellborg Arthursson */ public abstract class BinaryLogicalFilter extends AbstractFilter { @@ -59,19 +59,21 @@ public abstract class BinaryLogicalFilter extends AbstractFilter { /** * Implement this in subclass to return the logical operator, for example * "&". - * * @return the logical operator. */ protected abstract String getLogicalOperator(); @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; BinaryLogicalFilter that = (BinaryLogicalFilter) o; - if (queryList != null ? !queryList.equals(that.queryList) : that.queryList != null) return false; + if (queryList != null ? !queryList.equals(that.queryList) : that.queryList != null) + return false; return true; } @@ -83,7 +85,6 @@ public abstract class BinaryLogicalFilter extends AbstractFilter { /** * Add a query to this logical operation. - * * @param query the query to add. * @return This instance. */ @@ -96,4 +97,5 @@ public abstract class BinaryLogicalFilter extends AbstractFilter { queryList.addAll(subQueries); return this; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/CompareFilter.java b/core/src/main/java/org/springframework/ldap/filter/CompareFilter.java index c631e1d3..e704258f 100644 --- a/core/src/main/java/org/springframework/ldap/filter/CompareFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/CompareFilter.java @@ -19,7 +19,7 @@ import org.springframework.ldap.support.LdapEncoder; /** * Abstract superclass for filters that compare values. - * + * * @author Mattias Hellborg Arthursson */ public abstract class CompareFilter extends AbstractFilter { @@ -38,7 +38,6 @@ public abstract class CompareFilter extends AbstractFilter { /** * For testing purposes. - * * @return the encoded value. */ String getEncodedValue() { @@ -47,7 +46,6 @@ public abstract class CompareFilter extends AbstractFilter { /** * Override to perform special encoding in subclass. - * * @param value the value to encode. * @return properly escaped value. */ @@ -57,7 +55,6 @@ public abstract class CompareFilter extends AbstractFilter { /** * Convenience constructor for int values. - * * @param attribute Name of attribute in filter. * @param value The value of the attribute in the filter. */ @@ -80,13 +77,17 @@ public abstract class CompareFilter extends AbstractFilter { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; CompareFilter that = (CompareFilter) o; - if (attribute != null ? !attribute.equals(that.attribute) : that.attribute != null) return false; - if (value != null ? !value.equals(that.value) : that.value != null) return false; + if (attribute != null ? !attribute.equals(that.attribute) : that.attribute != null) + return false; + if (value != null ? !value.equals(that.value) : that.value != null) + return false; return true; } @@ -99,12 +100,11 @@ public abstract class CompareFilter extends AbstractFilter { } /** - * Implement this method in subclass to return a String representing the - * operator. The {@link EqualsFilter#getCompareString()} would for example - * return an equals sign, "=". - * - * @return the String to use as operator in the comparison for the specific - * subclass. + * Implement this method in subclass to return a String representing the operator. The + * {@link EqualsFilter#getCompareString()} would for example return an equals sign, + * "=". + * @return the String to use as operator in the comparison for the specific subclass. */ protected abstract String getCompareString(); + } diff --git a/core/src/main/java/org/springframework/ldap/filter/EqualsFilter.java b/core/src/main/java/org/springframework/ldap/filter/EqualsFilter.java index c34ecb7f..3ad2065b 100644 --- a/core/src/main/java/org/springframework/ldap/filter/EqualsFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/EqualsFilter.java @@ -18,18 +18,18 @@ package org.springframework.ldap.filter; /** * A filter for 'equals'. The following code: - * + * *
      * EqualsFilter filter = new EqualsFilter("cn", "Some CN");
      * System.out.println(filter.encode());
      * 
    - * + * * would result in: - * + * *
      * (cn=Some CN)
      * 
    - * + * * @author Adam Skogman */ public class EqualsFilter extends CompareFilter { @@ -42,7 +42,6 @@ public class EqualsFilter extends CompareFilter { /** * Convenience constructor for int values. - * * @param attribute Name of attribute in filter. * @param value The value of the attribute in the filter. */ @@ -56,4 +55,5 @@ public class EqualsFilter extends CompareFilter { protected String getCompareString() { return EQUALS_SIGN; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/Filter.java b/core/src/main/java/org/springframework/ldap/filter/Filter.java index d5dab99b..86b44ddd 100644 --- a/core/src/main/java/org/springframework/ldap/filter/Filter.java +++ b/core/src/main/java/org/springframework/ldap/filter/Filter.java @@ -18,23 +18,21 @@ package org.springframework.ldap.filter; /** * Common interface for LDAP filters. - * + * * @author Adam Skogman - * @see RFC 1960: A String - * Representation of LDAP Search Filters + * @see RFC 1960: A String Representation + * of LDAP Search Filters */ public interface Filter { /** * Encodes the filter to a String. - * * @return The encoded filter in the standard String format */ String encode(); /** * Encodes the filter to a StringBuffer. - * * @param buf The StringBuffer to encode the filter to * @return The same StringBuffer as was given */ @@ -42,7 +40,6 @@ public interface Filter { /** * All filters must implement equals. - * * @param o * @return true if the objects are equal. */ @@ -50,9 +47,8 @@ public interface Filter { /** * All filters must implement hashCode. - * - * @return the hash code according to the contract in - * {@link Object#hashCode()} + * @return the hash code according to the contract in {@link Object#hashCode()} */ int hashCode(); + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/filter/FilterEditor.java b/core/src/main/java/org/springframework/ldap/filter/FilterEditor.java index 92a19af6..fac9a3a0 100644 --- a/core/src/main/java/org/springframework/ldap/filter/FilterEditor.java +++ b/core/src/main/java/org/springframework/ldap/filter/FilterEditor.java @@ -20,11 +20,13 @@ import java.beans.PropertyEditorSupport; /** * Property editor for {@link Filter} instances. Creates {@link HardcodedFilter} * instances. - * + * * @author Mathieu Larchet */ public class FilterEditor extends PropertyEditorSupport { + public void setAsText(String text) throws IllegalArgumentException { setValue(new HardcodedFilter(text)); } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilter.java b/core/src/main/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilter.java index ce20876e..6b6e96af 100644 --- a/core/src/main/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilter.java @@ -17,20 +17,19 @@ package org.springframework.ldap.filter; /** - * A filter to compare >=. LDAP RFC does not allow > comparison. The following - * code: - * + * A filter to compare >=. LDAP RFC does not allow > comparison. The following code: + * *
      * GreaterThanOrEqualsFilter filter = new GreaterThanOrEqualsFilter("cn", "Some CN");
      * System.out.println(filter.ecode());
      * 
    - * + * * would result in: - * + * *
      * (cn>=Some CN)
      * 
    - * + * * @author Mattias Hellborg Arthursson */ public class GreaterThanOrEqualsFilter extends CompareFilter { @@ -48,4 +47,5 @@ public class GreaterThanOrEqualsFilter extends CompareFilter { protected String getCompareString() { return GREATER_THAN_OR_EQUALS; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/HardcodedFilter.java b/core/src/main/java/org/springframework/ldap/filter/HardcodedFilter.java index ec0deafa..cec2d5c0 100644 --- a/core/src/main/java/org/springframework/ldap/filter/HardcodedFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/HardcodedFilter.java @@ -18,30 +18,29 @@ package org.springframework.ldap.filter; import org.springframework.util.StringUtils; /** - * Allows hard coded parts to be included in a search filter. Particularly useful - * if some filters are specified in configuration files and these should be - * combined with other ones. - * + * Allows hard coded parts to be included in a search filter. Particularly useful if some + * filters are specified in configuration files and these should be combined with other + * ones. + * *
      * Filter filter = new HardcodedFilter("(&(objectClass=user)(!(objectClass=computer)))");
      * System.out.println(filter.toString());
      * 
    - * - * would result in: - * (&(objectClass=user)(!(objectClass=computer))) + * + * would result in: (&(objectClass=user)(!(objectClass=computer))) *

    - * Note 1: If the definition is in XML you will need to properly encode any special characters so that they are valid in an XML file, - * e.g. "&" needs to be encoded as "&amp;", e.g. - *

    + * Note 1: If the definition is in XML you will need to properly encode any special
    + * characters so that they are valid in an XML file, e.g. "&" needs to be
    + * encoded as "&amp;", e.g. 
      * <bean class="MyClass">
      *   <property name="filter" value="(&amp;(objectClass=user)(!(objectClass=computer)))" />
      * </bean>
      * 
    *

    - * Note 2: There will be no validation to ensure that the supplied filter is - * valid. Using this implementation to build filters from user input is strongly - * discouraged. + * Note 2: There will be no validation to ensure that the supplied filter is valid. + * Using this implementation to build filters from user input is strongly discouraged. *

    + * * @author Justen Stepka * @author Mathieu Larchet */ @@ -68,12 +67,15 @@ public class HardcodedFilter extends AbstractFilter { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; HardcodedFilter that = (HardcodedFilter) o; - if (filter != null ? !filter.equals(that.filter) : that.filter != null) return false; + if (filter != null ? !filter.equals(that.filter) : that.filter != null) + return false; return true; } @@ -82,4 +84,5 @@ public class HardcodedFilter extends AbstractFilter { public int hashCode() { return filter != null ? filter.hashCode() : 0; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/LessThanOrEqualsFilter.java b/core/src/main/java/org/springframework/ldap/filter/LessThanOrEqualsFilter.java index edabd7cb..ccc28ba3 100644 --- a/core/src/main/java/org/springframework/ldap/filter/LessThanOrEqualsFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/LessThanOrEqualsFilter.java @@ -17,20 +17,19 @@ package org.springframework.ldap.filter; /** - * A filter to compare <=. LDAP RFC does not allow < comparison. The following - * code: - * + * A filter to compare <=. LDAP RFC does not allow < comparison. The following code: + * *

      * LessThanOrEqualsFilter filter = new LessThanOrEqualsFilter("cn", "Some CN");
      * System.out.println(filter.ecode());
      * 
    - * + * * would result in: - * + * *
      * (cn<=Some CN)
      * 
    - * + * * @author Mattias Hellborg Arthursson */ public class LessThanOrEqualsFilter extends CompareFilter { @@ -48,4 +47,5 @@ public class LessThanOrEqualsFilter extends CompareFilter { protected String getCompareString() { return LESS_THAN_OR_EQUALS; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/LikeFilter.java b/core/src/main/java/org/springframework/ldap/filter/LikeFilter.java index e19ca4d3..274a6e19 100644 --- a/core/src/main/java/org/springframework/ldap/filter/LikeFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/LikeFilter.java @@ -19,20 +19,20 @@ package org.springframework.ldap.filter; import org.springframework.ldap.support.LdapEncoder; /** - * This filter allows the user to specify wildcards (*) by not escaping them in - * the filter. The following code: - * + * This filter allows the user to specify wildcards (*) by not escaping them in the + * filter. The following code: + * *
      * LikeFilter filter = new LikeFilter("cn", "foo*");
      * System.out.println(filter.ecode());
      * 
    - * + * * would result in: - * + * *
      *  (cn=foo*)
      * 
    - * + * * @author Anders Henja * @author Mattias Hellborg Arthursson */ @@ -64,4 +64,5 @@ public class LikeFilter extends EqualsFilter { return buff.toString(); } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/NotFilter.java b/core/src/main/java/org/springframework/ldap/filter/NotFilter.java index 3fd35b35..ab95df67 100644 --- a/core/src/main/java/org/springframework/ldap/filter/NotFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/NotFilter.java @@ -20,18 +20,18 @@ import org.springframework.util.Assert; /** * A filter for 'not'. The following code: - * + * *
      * Filter filter = new NotFilter(new EqualsFilter("cn", "foo");
      * System.out.println(filter.encode());
      * 
    - * + * * would result in: - * + * *
      * (!(cn = foo))
      * 
    - * + * * @author Adam Skogman */ public class NotFilter extends AbstractFilter { @@ -40,7 +40,6 @@ public class NotFilter extends AbstractFilter { /** * Create a filter that negates the outcome of the given filter. - * * @param filter The filter that should be negated. */ public NotFilter(Filter filter) { @@ -59,12 +58,15 @@ public class NotFilter extends AbstractFilter { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; NotFilter notFilter = (NotFilter) o; - if (filter != null ? !filter.equals(notFilter.filter) : notFilter.filter != null) return false; + if (filter != null ? !filter.equals(notFilter.filter) : notFilter.filter != null) + return false; return true; } @@ -73,4 +75,5 @@ public class NotFilter extends AbstractFilter { public int hashCode() { return filter != null ? filter.hashCode() : 0; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/NotPresentFilter.java b/core/src/main/java/org/springframework/ldap/filter/NotPresentFilter.java index 75faa13c..8edb3964 100644 --- a/core/src/main/java/org/springframework/ldap/filter/NotPresentFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/NotPresentFilter.java @@ -16,33 +16,31 @@ package org.springframework.ldap.filter; /** - * A convenience class that combines {@code NOT} behavior with {@code present} - * behavior to allow the user to check for the non-existence of a attribute. For - * an attribute to be {@code NOT present} it must not have any values set. To - * filter on attributes at are {@code present} use the {@link PresentFilter}. - * + * A convenience class that combines {@code NOT} behavior with {@code present} behavior to + * allow the user to check for the non-existence of a attribute. For an attribute to be + * {@code NOT present} it must not have any values set. To filter on attributes at are + * {@code present} use the {@link PresentFilter}. + * *
      * NotPresentFilter filter = new NotPresentFilter("foo");
      * System.out.println(filter.encode());
      * 
    - * + * * would result in: - * + * *
      *  (!(foo=*))
      * 
    + * * @author Jordan Hein */ public class NotPresentFilter extends AbstractFilter { - + private String attribute; /** - * Creates a new instance of a not present filter for a particular - * attribute. - * - * @param attribute the attribute expected to be not-present (ie, unset, or - * null). + * Creates a new instance of a not present filter for a particular attribute. + * @param attribute the attribute expected to be not-present (ie, unset, or null). */ public NotPresentFilter(String attribute) { this.attribute = attribute; @@ -57,12 +55,15 @@ public class NotPresentFilter extends AbstractFilter { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; NotPresentFilter that = (NotPresentFilter) o; - if (attribute != null ? !attribute.equals(that.attribute) : that.attribute != null) return false; + if (attribute != null ? !attribute.equals(that.attribute) : that.attribute != null) + return false; return true; } @@ -71,4 +72,5 @@ public class NotPresentFilter extends AbstractFilter { public int hashCode() { return attribute != null ? attribute.hashCode() : 0; } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/filter/OrFilter.java b/core/src/main/java/org/springframework/ldap/filter/OrFilter.java index 21850df8..f3a705ac 100644 --- a/core/src/main/java/org/springframework/ldap/filter/OrFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/OrFilter.java @@ -18,17 +18,16 @@ package org.springframework.ldap.filter; /** * Filter for logical OR. - * + * *
      * OrFilter filter = new OrFilter();
      * filter.or(new EqualsFilter("objectclass", "person");
      * filter.or(new EqualsFilter("objectclass", "organizationalUnit");
      * System.out.println(filter.encode());	
      * 
    - * - * would result in: - * (|(objectclass=person)(objectclass=organizationalUnit)) - * + * + * would result in: (|(objectclass=person)(objectclass=organizationalUnit)) + * * @author Adam Skogman * @author Mattias Hellborg Arthursson */ @@ -38,7 +37,6 @@ public class OrFilter extends BinaryLogicalFilter { /** * Add a query to the OR expression - * * @param query The query to or with the rest of the or:ed queries. * @return This LdapOrQuery */ @@ -50,4 +48,5 @@ public class OrFilter extends BinaryLogicalFilter { protected String getLogicalOperator() { return PIPE_SIGN; } + } diff --git a/core/src/main/java/org/springframework/ldap/filter/PresentFilter.java b/core/src/main/java/org/springframework/ldap/filter/PresentFilter.java index b4da3402..f24a3c18 100644 --- a/core/src/main/java/org/springframework/ldap/filter/PresentFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/PresentFilter.java @@ -16,22 +16,23 @@ package org.springframework.ldap.filter; /** - * Filter that allows the user to check for the existence of a attribute. For an - * attribute to be {@code 'present'} it must contain a value. Attributes that do - * not contain a value are {@code 'NOT present'}. To filter on attributes that - * are {@code 'NOT present'} use the {@link NotPresentFilter} or use this filter - * in combination with a {@link NotFilter} . - * + * Filter that allows the user to check for the existence of a attribute. For an attribute + * to be {@code 'present'} it must contain a value. Attributes that do not contain a value + * are {@code 'NOT present'}. To filter on attributes that are {@code 'NOT present'} use + * the {@link NotPresentFilter} or use this filter in combination with a {@link NotFilter} + * . + * *
      * PresentFilter filter = new PresentFilter("foo");
      * System.out.println(filter.encode());
      * 
    - * + * * would result in: - * + * *
      *  (foo=*)
      * 
    + * * @author Jordan Hein */ public class PresentFilter extends AbstractFilter { @@ -40,9 +41,7 @@ public class PresentFilter extends AbstractFilter { /** * Creates a new instance of a present filter for a particular attribute. - * - * @param attribute the attribute expected to be present (ie, contains a - * value). + * @param attribute the attribute expected to be present (ie, contains a value). */ public PresentFilter(String attribute) { this.attribute = attribute; @@ -57,12 +56,15 @@ public class PresentFilter extends AbstractFilter { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; PresentFilter that = (PresentFilter) o; - if (attribute != null ? !attribute.equals(that.attribute) : that.attribute != null) return false; + if (attribute != null ? !attribute.equals(that.attribute) : that.attribute != null) + return false; return true; } @@ -71,4 +73,5 @@ public class PresentFilter extends AbstractFilter { public int hashCode() { return attribute != null ? attribute.hashCode() : 0; } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/filter/WhitespaceWildcardsFilter.java b/core/src/main/java/org/springframework/ldap/filter/WhitespaceWildcardsFilter.java index cfc23eb3..27acc7cb 100644 --- a/core/src/main/java/org/springframework/ldap/filter/WhitespaceWildcardsFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/WhitespaceWildcardsFilter.java @@ -22,20 +22,20 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * This filter automatically converts all whitespace to wildcards (*). The - * following code: - * + * This filter automatically converts all whitespace to wildcards (*). The following code: + * *
      * WhitespaceWildcardsFilter filter = new WhitespaceWildcardsFilter("cn", "Some CN");
      * System.out.println(filter.ecode());
      * 
    - * + * * would result in: (cn=*Some*CN*) - * + * * @author Adam Skogman * @author Mattias Hellborg Arthursson */ public class WhitespaceWildcardsFilter extends EqualsFilter { + private static Pattern starReplacePattern = Pattern.compile("\\s+"); public WhitespaceWildcardsFilter(String attribute, String value) { @@ -69,4 +69,5 @@ public class WhitespaceWildcardsFilter extends EqualsFilter { return buff.toString(); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/annotations/Attribute.java b/core/src/main/java/org/springframework/ldap/odm/annotations/Attribute.java index 116f96d8..48a92a79 100755 --- a/core/src/main/java/org/springframework/ldap/odm/annotations/Attribute.java +++ b/core/src/main/java/org/springframework/ldap/odm/annotations/Attribute.java @@ -5,60 +5,62 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** * This annotation describes the mapping of a Java field to an LDAP attribute. *

    * The containing class must be annotated with {@link Entry}. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> * @see Entry */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Attribute { + /** - * The Type attribute indicates whether a field is regarded as binary based - * or string based by the LDAP JNDI provider. + * The Type attribute indicates whether a field is regarded as binary based or string + * based by the LDAP JNDI provider. */ enum Type { + /** - * A string field - returned by the JNDI LDAP provider as a {@link java.lang.String}. + * A string field - returned by the JNDI LDAP provider as a + * {@link java.lang.String}. */ - STRING, /** + STRING, + /** * A binary field - returned by the JNDI LDAP provider as a byte[]. */ BINARY + } /** * The LDAP attribute name that this field represents. *

    - * Defaults to "" in which case the Java field name is used as the LDAP attribute name. - * + * Defaults to "" in which case the Java field name is used as the LDAP attribute + * name. * @return The LDAP attribute name. - * + * */ String name() default ""; /** * Indicates whether this field is returned by the LDAP JNDI provider as a - * String (Type.STRING) or as a - * byte[] (Type.BINARY). - * - * @return Either Type.STRING to indicate a string attribute - * or Type.BINARY to indicate a binary attribute. + * String (Type.STRING) or as a byte[] + * (Type.BINARY). + * @return Either Type.STRING to indicate a string attribute or + * Type.BINARY to indicate a binary attribute. */ Type type() default Type.STRING; /** * The LDAP syntax of the attribute that this field represents. *

    - * This optional value is typically used to affect the precision of conversion - * of values between LDAP and Java, - * see {@link org.springframework.ldap.odm.typeconversion.ConverterManager} - * and {@link org.springframework.ldap.odm.typeconversion.impl.ConverterManagerImpl}. - * + * This optional value is typically used to affect the precision of conversion of + * values between LDAP and Java, see + * {@link org.springframework.ldap.odm.typeconversion.ConverterManager} and + * {@link org.springframework.ldap.odm.typeconversion.impl.ConverterManagerImpl}. * @return The LDAP syntax of this attribute. */ String syntax() default ""; @@ -66,10 +68,9 @@ public @interface Attribute { /** * A boolean parameter to indicate if the attribute should be read only. *

    - * This value allows attributes to be read on read, but not persisted, there - * are many operational and read-only ldap attributes which will throw errors - * if they are persisted back to ldap. - * + * This value allows attributes to be read on read, but not persisted, there are many + * operational and read-only ldap attributes which will throw errors if they are + * persisted back to ldap. * @return {@code true} is the attribute should not be written to ldap. */ boolean readonly() default false; diff --git a/core/src/main/java/org/springframework/ldap/odm/annotations/DnAttribute.java b/core/src/main/java/org/springframework/ldap/odm/annotations/DnAttribute.java index 99b5f302..682b8ad8 100644 --- a/core/src/main/java/org/springframework/ldap/odm/annotations/DnAttribute.java +++ b/core/src/main/java/org/springframework/ldap/odm/annotations/DnAttribute.java @@ -23,13 +23,15 @@ import java.lang.annotation.Target; /** * Indicates that a field is to be automatically populated to/from the distinguished name - * of an entry. Fields annotated with this annotation will be automatically populated with values from - * the distinguished names of found entries. Annotated fields must be of type String. + * of an entry. Fields annotated with this annotation will be automatically populated with + * values from the distinguished names of found entries. Annotated fields must be of type + * String. *

    * For automatic calculation of the DN of an entry to work, the {@link #index()} value - * must be specified on all DnAttribute annotations in that class, and these attribute values, - * prepended with the {@link org.springframework.ldap.odm.annotations.Entry#base()} value will be used - * to figure out the distinguished name of entries to create and update. + * must be specified on all DnAttribute annotations in that class, and these attribute + * values, prepended with the + * {@link org.springframework.ldap.odm.annotations.Entry#base()} value will be used to + * figure out the distinguished name of entries to create and update. *

    * @author Mattias Hellborg Arthursson * @since 2.0 @@ -37,6 +39,7 @@ import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface DnAttribute { + /** * The name of the distinguished name attribute. * @return the attribute name. @@ -48,4 +51,5 @@ public @interface DnAttribute { * @return the 0-based index of this attribute. */ int index() default -1; + } diff --git a/core/src/main/java/org/springframework/ldap/odm/annotations/Entry.java b/core/src/main/java/org/springframework/ldap/odm/annotations/Entry.java index 23c4a1ce..cfe0fdff 100755 --- a/core/src/main/java/org/springframework/ldap/odm/annotations/Entry.java +++ b/core/src/main/java/org/springframework/ldap/odm/annotations/Entry.java @@ -8,18 +8,18 @@ import java.lang.annotation.Target; /** * This annotation marks a Java class to be persisted in an LDAP directory. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Entry { + /** * A list of LDAP object classes that the annotated Java class represents. *

    * All fields will be persisted to LDAP unless annotated {@link Transient}. - * * @return A list of LDAP classes which the annotated Java class represents. */ String[] objectClasses(); @@ -27,8 +27,8 @@ public @interface Entry { /** * The base DN of this entry. If specified, this will be prepended to all calculated * distinguished names for entries of the annotated class. - * * @return the base DN for entries of this class */ String base() default ""; + } diff --git a/core/src/main/java/org/springframework/ldap/odm/annotations/Id.java b/core/src/main/java/org/springframework/ldap/odm/annotations/Id.java index 0e21a7e0..ca13933b 100755 --- a/core/src/main/java/org/springframework/ldap/odm/annotations/Id.java +++ b/core/src/main/java/org/springframework/ldap/odm/annotations/Id.java @@ -5,19 +5,20 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; - /** - * This annotation marks a Java field as containing the Distinguished Name of an LDAP Entry. + * This annotation marks a Java field as containing the Distinguished Name of an LDAP + * Entry. *

    - * The marked field must be of type {@link javax.naming.Name} and must not - * be annotated {@link Attribute}. + * The marked field must be of type {@link javax.naming.Name} and must not be + * annotated {@link Attribute}. * * @author Paul Harvey <paul.at.pauls-place.me.uk> - * + * * @see Attribute * @see javax.naming.Name */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Id { + } diff --git a/core/src/main/java/org/springframework/ldap/odm/annotations/Transient.java b/core/src/main/java/org/springframework/ldap/odm/annotations/Transient.java index c970cfea..3a0ef0ec 100755 --- a/core/src/main/java/org/springframework/ldap/odm/annotations/Transient.java +++ b/core/src/main/java/org/springframework/ldap/odm/annotations/Transient.java @@ -6,14 +6,15 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * This annotation identifies a field in an {@link Entry} annotated class that - * should not be persisted to LDAP. - * + * This annotation identifies a field in an {@link Entry} annotated class that should + * not be persisted to LDAP. + * * @author Paul Harvey <paul@pauls-place.me.uk> - * + * * @see Entry */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Transient { + } diff --git a/core/src/main/java/org/springframework/ldap/odm/annotations/package-info.java b/core/src/main/java/org/springframework/ldap/odm/annotations/package-info.java index 43f56985..a40f609d 100755 --- a/core/src/main/java/org/springframework/ldap/odm/annotations/package-info.java +++ b/core/src/main/java/org/springframework/ldap/odm/annotations/package-info.java @@ -1,9 +1,10 @@ /** * Provides a set of annotations to describe the mapping of a Java class to an LDAP entry. *

    - * These annotations are for use with OdmManager. - * + * These annotations are for use with + * OdmManager. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ + */ package org.springframework.ldap.odm.annotations; \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/odm/core/ObjectDirectoryMapper.java b/core/src/main/java/org/springframework/ldap/odm/core/ObjectDirectoryMapper.java index 8bb44e7f..cea272e6 100644 --- a/core/src/main/java/org/springframework/ldap/odm/core/ObjectDirectoryMapper.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/ObjectDirectoryMapper.java @@ -22,9 +22,11 @@ import org.springframework.LdapDataEntry; import org.springframework.ldap.filter.Filter; /** - * The ObjectDirectoryMapper keeps track of managed class metadata and is used by {@link org.springframework.ldap.core.LdapTemplate} - * to map to/from entity objects annotated with the annotations specified in the {@link org.springframework.ldap.odm.annotations} - * package. Instances of this class are typically intended for internal use only. + * The ObjectDirectoryMapper keeps track of managed class metadata and is used by + * {@link org.springframework.ldap.core.LdapTemplate} to map to/from entity objects + * annotated with the annotations specified in the + * {@link org.springframework.ldap.odm.annotations} package. Instances of this class are + * typically intended for internal use only. * * @author Mattias Hellborg Arthursson * @since 2.0 @@ -32,9 +34,8 @@ import org.springframework.ldap.filter.Filter; public interface ObjectDirectoryMapper { /** - * Used to convert from Java representation of an Ldap Entry when writing to - * the Ldap directory - * + * Used to convert from Java representation of an Ldap Entry when writing to the Ldap + * directory * @param entry - The entry to convert. * @param context - The LDAP context to store the converted entry * @throws org.springframework.ldap.NamingException on error. @@ -42,14 +43,14 @@ public interface ObjectDirectoryMapper { void mapToLdapDataEntry(Object entry, LdapDataEntry context); /** - * Used to convert from the JNDI LDAP representation of an Entry to the Java representation when reading from LDAP. + * Used to convert from the JNDI LDAP representation of an Entry to the Java + * representation when reading from LDAP. * @throws org.springframework.ldap.NamingException on error. */ T mapFromLdapDataEntry(LdapDataEntry ctx, Class clazz); /** * Get the distinguished name for the specified object. - * * @param entry the entry to get distinguished name for. * @return the distinguished name of the entry. * @throws org.springframework.ldap.NamingException on error. @@ -58,7 +59,6 @@ public interface ObjectDirectoryMapper { /** * Set the distinguished name for the specified object. - * * @param entry the entry to set the name on * @param id the name to set * @throws org.springframework.ldap.NamingException on error. @@ -68,12 +68,13 @@ public interface ObjectDirectoryMapper { Name getCalculatedId(Object entry); /** - * Use the specified search filter and return a new one that only applies to entries of the specified class. - * In effect this means padding the original filter with an objectclass condition. - * + * Use the specified search filter and return a new one that only applies to entries + * of the specified class. In effect this means padding the original filter with an + * objectclass condition. * @param clazz the class. * @param baseFilter the filter we want to use. - * @return the original filter, modified so that it only applies to entries of the specified class. + * @return the original filter, modified so that it only applies to entries of the + * specified class. * @throws org.springframework.ldap.NamingException on error. */ Filter filterFor(Class clazz, Filter baseFilter); @@ -88,11 +89,14 @@ public interface ObjectDirectoryMapper { */ String attributeFor(Class clazz, String fieldName); - /** Check if the specified class is already managed by this instance; if not, check the metadata and add the class to the managed - * classes. - * + /** + * Check if the specified class is already managed by this instance; if not, check the + * metadata and add the class to the managed classes. * @param clazz the class to manage. - * @return all relevant attribute names used in the given class (either for reading from LDAP or for writing to LDAP or both) - * @throws org.springframework.ldap.NamingException on error. */ + * @return all relevant attribute names used in the given class (either for reading + * from LDAP or for writing to LDAP or both) + * @throws org.springframework.ldap.NamingException on error. + */ String[] manageClass(Class clazz); + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/OdmException.java b/core/src/main/java/org/springframework/ldap/odm/core/OdmException.java index b52b5eaf..35603976 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/OdmException.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/OdmException.java @@ -20,12 +20,13 @@ import org.springframework.ldap.NamingException; /** * The root of the Spring LDAP ODM exception hierarchy. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> * */ @SuppressWarnings("serial") public class OdmException extends NamingException { + public OdmException(String message) { super(message); } @@ -33,4 +34,5 @@ public class OdmException extends NamingException { public OdmException(String message, Throwable e) { super(message, e); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/impl/AttributeMetaData.java b/core/src/main/java/org/springframework/ldap/odm/core/impl/AttributeMetaData.java index 840a03ca..3f5f5deb 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/impl/AttributeMetaData.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/impl/AttributeMetaData.java @@ -39,15 +39,16 @@ import java.util.TreeSet; /* * Extract attribute meta-data from the @Attribute annotation, the @Id annotation * and via reflection. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ /* package */ final class AttributeMetaData { - private static final CaseIgnoreString OBJECT_CLASS_ATTRIBUTE_CI=new CaseIgnoreString("objectclass"); - + + private static final CaseIgnoreString OBJECT_CLASS_ATTRIBUTE_CI = new CaseIgnoreString("objectclass"); + // Name of the LDAP attribute from the @Attribute annotation private CaseIgnoreString name; - + // Syntax of the LDAP attribute from the @Attribute annotation private String syntax; @@ -58,7 +59,7 @@ import java.util.TreeSet; private final Field field; // The Java class of the field corresponding to this meta data - // This is the actual scalar type meaning that if the field is + // This is the actual scalar type meaning that if the field is // List then the valueClass will be String private Class valueClass; @@ -86,16 +87,16 @@ import java.util.TreeSet; private boolean processAttributeAnnotation(Field field) { // Default to no syntax specified syntax = ""; - + // Default to a String based attribute isBinary = false; - + // Default name of attribute to the name of the field name = new CaseIgnoreString(field.getName()); - + // We have not yet found the @Attribute annotation - boolean foundAnnotation=false; - + boolean foundAnnotation = false; + // Grab the @Attribute annotation Attribute attribute = field.getAnnotation(Attribute.class); @@ -103,11 +104,12 @@ import java.util.TreeSet; // Did we find the annotation? if (attribute != null) { // Pull attribute name, syntax and whether attribute is binary - // from the annotation - foundAnnotation=true; + // from the annotation + foundAnnotation = true; String localAttributeName = attribute.name(); - // Would be more efficient to use !isEmpty - but that then makes us Java 6 dependent - if (localAttributeName != null && localAttributeName.length()>0) { + // Would be more efficient to use !isEmpty - but that then makes us Java 6 + // dependent + if (localAttributeName != null && localAttributeName.length() > 0) { name = new CaseIgnoreString(localAttributeName); attrList.add(localAttributeName); } @@ -116,12 +118,12 @@ import java.util.TreeSet; isReadOnly = attribute.readonly(); } attributes = attrList.toArray(new String[attrList.size()]); - - isObjectClass=name.equals(OBJECT_CLASS_ATTRIBUTE_CI); - + + isObjectClass = name.equals(OBJECT_CLASS_ATTRIBUTE_CI); + return foundAnnotation; } - + // Extract reflection information from the field: // valueClass, isList private void determineFieldType(Field field) { @@ -130,58 +132,67 @@ import java.util.TreeSet; isCollection = Collection.class.isAssignableFrom(fieldType); - valueClass=null; + valueClass = null; if (!isCollection) { // It's not a list so assume its single valued - so just take the field type valueClass = fieldType; - } else { + } + else { determineCollectionClass(fieldType); // It's multi-valued - so we need to look at the signature in // the class file to find the generic type - this is supported for class file // format 49 and greater which corresponds to java 5 and later. ParameterizedType paramType; try { - paramType = (ParameterizedType)field.getGenericType(); - } catch (ClassCastException e) { - throw new MetaDataException(String.format("Can't determine destination type for field %1$s in Entry class %2$s", - field, field.getDeclaringClass()), e); + paramType = (ParameterizedType) field.getGenericType(); + } + catch (ClassCastException e) { + throw new MetaDataException( + String.format("Can't determine destination type for field %1$s in Entry class %2$s", field, + field.getDeclaringClass()), + e); } Type[] actualParamArguments = paramType.getActualTypeArguments(); if (actualParamArguments.length == 1) { if (actualParamArguments[0] instanceof Class) { - valueClass = (Class)actualParamArguments[0]; - } else { + valueClass = (Class) actualParamArguments[0]; + } + else { if (actualParamArguments[0] instanceof GenericArrayType) { // Deal with arrays - Type type=((GenericArrayType)actualParamArguments[0]).getGenericComponentType(); + Type type = ((GenericArrayType) actualParamArguments[0]).getGenericComponentType(); if (type instanceof Class) { - valueClass=Array.newInstance((Class)type, 0).getClass(); - } - } + valueClass = Array.newInstance((Class) type, 0).getClass(); + } + } } - } + } } // Check we have been able to determine the value class - if (valueClass==null) { - throw new MetaDataException(String.format("Can't determine destination type for field %1$s in class %2$s", + if (valueClass == null) { + throw new MetaDataException(String.format("Can't determine destination type for field %1$s in class %2$s", field, field.getDeclaringClass())); } } @SuppressWarnings("unchecked") private void determineCollectionClass(Class fieldType) { - if(fieldType.isInterface()) { - if(Collection.class.equals(fieldType) || List.class.equals(fieldType)) { + if (fieldType.isInterface()) { + if (Collection.class.equals(fieldType) || List.class.equals(fieldType)) { collectionClass = ArrayList.class; - } else if(SortedSet.class.equals(fieldType)) { + } + else if (SortedSet.class.equals(fieldType)) { collectionClass = TreeSet.class; - } else if(Set.class.isAssignableFrom(fieldType)) { + } + else if (Set.class.isAssignableFrom(fieldType)) { collectionClass = LinkedHashSet.class; - } else { + } + else { throw new MetaDataException(String.format("Collection class %s is not supported", fieldType)); } - } else { + } + else { collectionClass = (Class) fieldType; } } @@ -190,7 +201,8 @@ import java.util.TreeSet; public Collection newCollectionInstance() { try { return (Collection) collectionClass.newInstance(); - } catch (Exception e) { + } + catch (Exception e) { throw new UncategorizedLdapException("Failed to instantiate collection class", e); } } @@ -199,33 +211,33 @@ import java.util.TreeSet; // isId private boolean processIdAnnotation(Field field, Class fieldType) { // Are we dealing with the Id field? - isId=field.getAnnotation(Id.class)!=null; + isId = field.getAnnotation(Id.class) != null; - if (isId) { + if (isId) { // It must be of type Name or a subclass of that of if (!Name.class.isAssignableFrom(fieldType)) { - throw new MetaDataException( - String.format("The id field must be of type javax.naming.Name or a subclass that of in Entry class %1$s", - field.getDeclaringClass())); + throw new MetaDataException(String.format( + "The id field must be of type javax.naming.Name or a subclass that of in Entry class %1$s", + field.getDeclaringClass())); } } - + return isId; } - + // Extract meta-data from the given field public AttributeMetaData(Field field) { - this.field=field; + this.field = field; this.dnAttribute = field.getAnnotation(DnAttribute.class); - if(this.dnAttribute != null && !field.getType().equals(String.class)) { - throw new MetaDataException(String.format("%s is of type %s, but only String attributes can be declared as @DnAttributes", - field.toString(), - field.getType().toString())); + if (this.dnAttribute != null && !field.getType().equals(String.class)) { + throw new MetaDataException( + String.format("%s is of type %s, but only String attributes can be declared as @DnAttributes", + field.toString(), field.getType().toString())); } Transient transientAnnotation = field.getAnnotation(Transient.class); - if(transientAnnotation != null) { + if (transientAnnotation != null) { this.isTransient = true; return; } @@ -233,28 +245,27 @@ import java.util.TreeSet; // Reflection data determineFieldType(field); - // Data from the @Attribute annotation - boolean foundAttributeAnnotation=processAttributeAnnotation(field); + boolean foundAttributeAnnotation = processAttributeAnnotation(field); // Data from the @Id annotation - boolean foundIdAnnoation=processIdAnnotation(field, valueClass); + boolean foundIdAnnoation = processIdAnnotation(field, valueClass); // Check that the field has not been annotated with both @Attribute and with @Id if (foundAttributeAnnotation && foundIdAnnoation) { - throw new MetaDataException( - String.format("You may not specifiy an %1$s annoation and an %2$s annotation on the same field, error in field %3$s in Entry class %4$s", - Id.class, Attribute.class, field.getName(), field.getDeclaringClass())); + throw new MetaDataException(String.format( + "You may not specifiy an %1$s annoation and an %2$s annotation on the same field, error in field %3$s in Entry class %4$s", + Id.class, Attribute.class, field.getName(), field.getDeclaringClass())); } - + // If this is the objectclass attribute then it must be of type List - if (isObjectClass() && (!isCollection() || valueClass!=String.class)) { - throw new MetaDataException(String.format("The type of the objectclass attribute must be List in classs %1$s", - field.getDeclaringClass())); + if (isObjectClass() && (!isCollection() || valueClass != String.class)) { + throw new MetaDataException( + String.format("The type of the objectclass attribute must be List in classs %1$s", + field.getDeclaringClass())); } } - public String getSyntax() { return syntax; } @@ -270,7 +281,7 @@ import java.util.TreeSet; public CaseIgnoreString getName() { return name; } - + public boolean isCollection() { return isCollection; } @@ -308,23 +319,28 @@ import java.util.TreeSet; } public Class getJndiClass() { - if(isBinary()) { + if (isBinary()) { return byte[].class; - } else if(Name.class.isAssignableFrom(valueClass)) { + } + else if (Name.class.isAssignableFrom(valueClass)) { return Name.class; - } else { + } + else { return String.class; } } /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override public String toString() { - return String.format("name=%1$s | field=%2$s | valueClass=%3$s | syntax=%4$s| isBinary=%5$s | isId=%6$s | isReadOnly=%7$s | isList=%8$s | isObjectClass=%9$s", - getName(), getField(), getValueClass(), getSyntax(), isBinary(), isId(), isReadOnly(), isCollection(), isObjectClass()); + return String.format( + "name=%1$s | field=%2$s | valueClass=%3$s | syntax=%4$s| isBinary=%5$s | isId=%6$s | isReadOnly=%7$s | isList=%8$s | isObjectClass=%9$s", + getName(), getField(), getValueClass(), getSyntax(), isBinary(), isId(), isReadOnly(), isCollection(), + isObjectClass()); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/impl/CaseIgnoreString.java b/core/src/main/java/org/springframework/ldap/odm/core/impl/CaseIgnoreString.java index f274f56e..91f120b2 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/impl/CaseIgnoreString.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/impl/CaseIgnoreString.java @@ -20,9 +20,11 @@ import org.springframework.util.Assert; // A case independent String wrapper. /* package */ final class CaseIgnoreString implements Comparable { + private final String string; - private final int hashCode; - + + private final int hashCode; + public CaseIgnoreString(String string) { Assert.notNull(string, "string must not be null"); this.string = string; @@ -30,11 +32,10 @@ import org.springframework.util.Assert; } public boolean equals(Object other) { - return other instanceof CaseIgnoreString && - ((CaseIgnoreString)other).string.equalsIgnoreCase(string); + return other instanceof CaseIgnoreString && ((CaseIgnoreString) other).string.equalsIgnoreCase(string); } - - public int hashCode() { + + public int hashCode() { return hashCode; } @@ -46,4 +47,5 @@ import org.springframework.util.Assert; public String toString() { return string; } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/impl/DefaultObjectDirectoryMapper.java b/core/src/main/java/org/springframework/ldap/odm/core/impl/DefaultObjectDirectoryMapper.java index 9dc6560f..64c03b51 100644 --- a/core/src/main/java/org/springframework/ldap/odm/core/impl/DefaultObjectDirectoryMapper.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/impl/DefaultObjectDirectoryMapper.java @@ -52,22 +52,24 @@ import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; /** - * Default implementation of {@link ObjectDirectoryMapper}. Unless you need to explicitly configure - * converters there is typically no reason to explicitly consider yourself with this class. + * Default implementation of {@link ObjectDirectoryMapper}. Unless you need to explicitly + * configure converters there is typically no reason to explicitly consider yourself with + * this class. * * @author Paul Harvey <paul.at.pauls-place.me.uk> * @author Mattias Hellborg Arthursson * @since 2.0 */ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { + private static final Logger LOG = LoggerFactory.getLogger(DefaultObjectDirectoryMapper.class); // The converter manager to use to translate values between LDAP and Java private ConverterManager converterManager; - private static final String OBJECT_CLASS_ATTRIBUTE="objectclass"; - private static final CaseIgnoreString OBJECT_CLASS_ATTRIBUTE_CI=new CaseIgnoreString(OBJECT_CLASS_ATTRIBUTE); + private static final String OBJECT_CLASS_ATTRIBUTE = "objectclass"; + private static final CaseIgnoreString OBJECT_CLASS_ATTRIBUTE_CI = new CaseIgnoreString(OBJECT_CLASS_ATTRIBUTE); public DefaultObjectDirectoryMapper() { converterManager = createDefaultConverterManager(); @@ -75,12 +77,15 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { private static ConverterManager createDefaultConverterManager() { String springVersion = SpringVersion.getVersion(); - if(springVersion == null) { - LOG.debug("Could not determine the Spring Version. Guessing > Spring 3.0. If this does not work, please ensure to explicitly set converterManager"); + if (springVersion == null) { + LOG.debug( + "Could not determine the Spring Version. Guessing > Spring 3.0. If this does not work, please ensure to explicitly set converterManager"); return new ConversionServiceConverterManager(); - } else if(springVersion.compareTo("3.0") > 0) { + } + else if (springVersion.compareTo("3.0") > 0) { return new ConversionServiceConverterManager(); - } else { + } + else { return new ConverterManagerImpl(); } } @@ -90,17 +95,20 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { } static final class EntityData { + final ObjectMetaData metaData; + final Filter ocFilter; private EntityData(ObjectMetaData metaData, Filter ocFilter) { - this.metaData=metaData; - this.ocFilter=ocFilter; + this.metaData = metaData; + this.ocFilter = ocFilter; } + } // A map of managed classes to to meta data about those classes - private final ConcurrentMap, EntityData> metaDataMap=new ConcurrentHashMap, EntityData>(); + private final ConcurrentMap, EntityData> metaDataMap = new ConcurrentHashMap, EntityData>(); private EntityData getEntityData(Class managedClass) { EntityData result = metaDataMap.get(managedClass); @@ -126,12 +134,14 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { if (attributesOfField != null && attributesOfField.length > 0) { // attribute names are either given through annotation managedAttributeNames.addAll(Arrays.asList(attributesOfField)); - } else { + } + else { // or implicitly by relying on the field name managedAttributeNames.add(field.getName()); } } - // always add the mandatory attribute objectclass (which is always used for the mapping) + // always add the mandatory attribute objectclass (which is always used for the + // mapping) managedAttributeNames.add(OBJECT_CLASS_ATTRIBUTE); return managedAttributeNames.toArray(new String[managedAttributeNames.size()]); } @@ -139,7 +149,6 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { /** * Adds an {@link org.springframework.ldap.odm.annotations} annotated class to the set * managed by this OdmManager. - * * @param managedClass The class to add to the managed set. */ private EntityData addManagedClass(Class managedClass) { @@ -148,14 +157,17 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { } // Extract the meta-data from the class - ObjectMetaData metaData=new ObjectMetaData(managedClass); + ObjectMetaData metaData = new ObjectMetaData(managedClass); - // Check we can construct the target type - it must have a zero argument public constructor + // Check we can construct the target type - it must have a zero argument public + // constructor try { managedClass.getConstructor(); - } catch (NoSuchMethodException e) { - throw new InvalidEntryException(String.format( - "The class %1$s must have a zero argument constructor to be an Entry", managedClass), e); + } + catch (NoSuchMethodException e) { + throw new InvalidEntryException( + String.format("The class %1$s must have a zero argument constructor to be an Entry", managedClass), + e); } // Check we have all of the necessary converters for the class @@ -175,7 +187,7 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { EntityData newValue = new EntityData(metaData, ocFilter); EntityData previousValue = metaDataMap.putIfAbsent(managedClass, newValue); // Just in case someone beat us to it - if(previousValue != null) { + if (previousValue != null) { return previousValue; } @@ -186,31 +198,34 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { Class jndiClass = attributeInfo.getJndiClass(); Class javaClass = attributeInfo.getValueClass(); if (!converterManager.canConvert(jndiClass, attributeInfo.getSyntax(), javaClass)) { - throw new InvalidEntryException(String.format( - "Missing converter from %1$s to %2$s, this is needed for field %3$s on Entry %4$s", - jndiClass, javaClass, field.getName(), managedClass)); + throw new InvalidEntryException( + String.format("Missing converter from %1$s to %2$s, this is needed for field %3$s on Entry %4$s", + jndiClass, javaClass, field.getName(), managedClass)); } - if (!attributeInfo.isReadOnly() && !converterManager.canConvert(javaClass, attributeInfo.getSyntax(), jndiClass)) { - throw new InvalidEntryException(String.format( - "Missing converter from %1$s to %2$s, this is needed for field %3$s on Entry %4$s", - javaClass, jndiClass, field.getName(), managedClass)); + if (!attributeInfo.isReadOnly() + && !converterManager.canConvert(javaClass, attributeInfo.getSyntax(), jndiClass)) { + throw new InvalidEntryException( + String.format("Missing converter from %1$s to %2$s, this is needed for field %3$s on Entry %4$s", + javaClass, jndiClass, field.getName(), managedClass)); } } @Override public void mapToLdapDataEntry(Object entry, LdapDataEntry context) { - ObjectMetaData metaData=getEntityData(entry.getClass()).metaData; + ObjectMetaData metaData = getEntityData(entry.getClass()).metaData; Attribute objectclassAttribute = context.getAttributes().get(OBJECT_CLASS_ATTRIBUTE); - if(objectclassAttribute == null || objectclassAttribute.size() == 0) { - // Object classes are set from the metadata obtained from the @Entity annotation, + if (objectclassAttribute == null || objectclassAttribute.size() == 0) { + // Object classes are set from the metadata obtained from the @Entity + // annotation, // but only if this is a new entry. - int numOcs=metaData.getObjectClasses().size(); - CaseIgnoreString[] metaDataObjectClasses=metaData.getObjectClasses().toArray(new CaseIgnoreString[numOcs]); + int numOcs = metaData.getObjectClasses().size(); + CaseIgnoreString[] metaDataObjectClasses = metaData.getObjectClasses() + .toArray(new CaseIgnoreString[numOcs]); - String[] stringOcs=new String[numOcs]; - for (int ocIndex=0; ocIndex targetClass = attributeInfo.getJndiClass(); // Multi valued? if (!attributeInfo.isCollection()) { populateSingleValueAttribute(entry, context, field, attributeInfo, targetClass); - } else { + } + else { // Multi-valued populateMultiValueAttribute(entry, context, field, attributeInfo, targetClass); } - } catch (IllegalAccessException e) { + } + catch (IllegalAccessException e) { throw new InvalidEntryException(String.format("Can't set attribute %1$s", attributeInfo.getName()), e); } @@ -242,33 +262,36 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { } } - private void populateMultiValueAttribute(Object entry, LdapDataEntry context, Field field, AttributeMetaData attributeInfo, Class targetClass) throws IllegalAccessException { + private void populateMultiValueAttribute(Object entry, LdapDataEntry context, Field field, + AttributeMetaData attributeInfo, Class targetClass) throws IllegalAccessException { // We need to build up a list of of the values List attributeValues = new ArrayList(); // Get the list of values - Collection fieldValues = (Collection)field.get(entry); + Collection fieldValues = (Collection) field.get(entry); // Ignore null lists if (fieldValues != null) { for (final Object o : fieldValues) { // Ignore null values if (o != null) { - attributeValues.add(converterManager.convert(o, attributeInfo.getSyntax(), - targetClass)); + attributeValues.add(converterManager.convert(o, attributeInfo.getSyntax(), targetClass)); } } context.setAttributeValues(attributeInfo.getName().toString(), attributeValues.toArray()); } } - private void populateSingleValueAttribute(Object entry, LdapDataEntry context, Field field, AttributeMetaData attributeInfo, Class targetClass) throws IllegalAccessException { + private void populateSingleValueAttribute(Object entry, LdapDataEntry context, Field field, + AttributeMetaData attributeInfo, Class targetClass) throws IllegalAccessException { // Single valued - get the value of the field Object fieldValue = field.get(entry); // Ignore null field values if (fieldValue != null) { - // Convert the field value to the required type and write it into the JNDI context - context.setAttributeValue(attributeInfo.getName().toString(), converterManager.convert(fieldValue, - attributeInfo.getSyntax(), targetClass)); - } else { + // Convert the field value to the required type and write it into the JNDI + // context + context.setAttributeValue(attributeInfo.getName().toString(), + converterManager.convert(fieldValue, attributeInfo.getSyntax(), targetClass)); + } + else { context.setAttributeValue(attributeInfo.getName().toString(), null); } } @@ -282,7 +305,7 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { // The Java representation of the LDAP entry T result; - ObjectMetaData metaData=getEntityData(clazz).metaData; + ObjectMetaData metaData = getEntityData(clazz).metaData; try { // The result class must have a zero argument constructor @@ -296,12 +319,13 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { // Loop through all of the JNDI attributes while (attributesEnumeration.hasMoreElements()) { Attribute currentAttribute = attributesEnumeration.nextElement(); - // Add the current attribute to the map keyed on the lowercased (case indep) id of the attribute + // Add the current attribute to the map keyed on the lowercased (case + // indep) id of the attribute attributeValueMap.put(new CaseIgnoreString(currentAttribute.getID()), currentAttribute); } - - // If this is the objectclass attribute then check that values correspond to the metadata we have + // If this is the objectclass attribute then check that values correspond to + // the metadata we have // for the Java representation Attribute ocAttribute = attributeValueMap.get(OBJECT_CLASS_ATTRIBUTE_CI); if (ocAttribute != null) { @@ -309,18 +333,20 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { Set objectClassesFromJndi = new HashSet(); NamingEnumeration objectClassesFromJndiEnum = ocAttribute.getAll(); while (objectClassesFromJndiEnum.hasMoreElements()) { - objectClassesFromJndi.add(new CaseIgnoreString((String)objectClassesFromJndiEnum.nextElement())); + objectClassesFromJndi.add(new CaseIgnoreString((String) objectClassesFromJndiEnum.nextElement())); } // OK - checks its the same as the meta-data we have - if(!collectionContainsAll(objectClassesFromJndi, metaData.getObjectClasses())) { + if (!collectionContainsAll(objectClassesFromJndi, metaData.getObjectClasses())) { return null; } - } else { - throw new InvalidEntryException(String.format("No object classes were returned for class %1$s", - clazz.getName())); + } + else { + throw new InvalidEntryException( + String.format("No object classes were returned for class %1$s", clazz.getName())); } - // Now loop through all the fields in the Java representation populating it with values from the + // Now loop through all the fields in the Java representation populating it + // with values from the // attributeValueMap for (Field field : metaData) { // Get the current field @@ -330,38 +356,45 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { if (!attributeInfo.isTransient() && !attributeInfo.isId()) { // Not the ID - but is is multi valued? if (!attributeInfo.isCollection()) { - // No - its single valued, grab the JNDI attribute that corresponds to the metadata on the + // No - its single valued, grab the JNDI attribute that + // corresponds to the metadata on the // current field populateSingleValueField(result, attributeValueMap, field, attributeInfo); - } else { + } + else { // We are dealing with a multi valued attribute populateMultiValueField(result, attributeValueMap, field, attributeInfo); } - } else if(attributeInfo.isId()) { // The id field - field.set(result, converterManager.convert(dn, attributeInfo.getSyntax(), - attributeInfo.getValueClass())); + } + else if (attributeInfo.isId()) { // The id field + field.set(result, + converterManager.convert(dn, attributeInfo.getSyntax(), attributeInfo.getValueClass())); } DnAttribute dnAttribute = attributeInfo.getDnAttribute(); - if(dnAttribute != null) { + if (dnAttribute != null) { String dnValue; int index = dnAttribute.index(); - if(index != -1) { + if (index != -1) { dnValue = LdapUtils.getStringValue(dn, index); - } else { + } + else { dnValue = LdapUtils.getStringValue(dn, dnAttribute.value()); } field.set(result, dnValue); } } - } catch (NamingException ne) { - throw new InvalidEntryException(String.format("Problem creating %1$s from LDAP Entry %2$s", - clazz, context), ne); - } catch (IllegalAccessException iae) { - throw new InvalidEntryException(String.format( - "Could not create an instance of %1$s could not access field", clazz.getName()), iae); - } catch (InstantiationException ie) { + } + catch (NamingException ne) { + throw new InvalidEntryException(String.format("Problem creating %1$s from LDAP Entry %2$s", clazz, context), + ne); + } + catch (IllegalAccessException iae) { + throw new InvalidEntryException( + String.format("Could not create an instance of %1$s could not access field", clazz.getName()), iae); + } + catch (InstantiationException ie) { throw new InvalidEntryException(String.format("Could not instantiate %1$s", clazz), ie); } @@ -372,12 +405,14 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { return result; } - private void populateMultiValueField(T result, Map attributeValueMap, Field field, AttributeMetaData attributeInfo) throws NamingException, IllegalAccessException { + private void populateMultiValueField(T result, Map attributeValueMap, Field field, + AttributeMetaData attributeInfo) throws NamingException, IllegalAccessException { // We need to build up a list of values Collection fieldValues = attributeInfo.newCollectionInstance(); // Grab the attribute from the JNDI representation Attribute currentAttribute = attributeValueMap.get(attributeInfo.getName()); - // There is no guarantee that this attribute is present in the directory - so ignore nulls + // There is no guarantee that this attribute is present in the directory - so + // ignore nulls if (currentAttribute != null) { // Loop through the values of the JNDI attribute NamingEnumeration valuesEmumeration = currentAttribute.getAll(); @@ -386,9 +421,10 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { Object value = valuesEmumeration.nextElement(); // Check the value is not null if (value != null) { - // Convert the value to its Java representation and add it to our working list - fieldValues.add(converterManager.convert(value, attributeInfo.getSyntax(), - attributeInfo.getValueClass())); + // Convert the value to its Java representation and add it to our + // working list + fieldValues.add( + converterManager.convert(value, attributeInfo.getSyntax(), attributeInfo.getValueClass())); } } } @@ -396,15 +432,18 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { field.set(result, fieldValues); } - private void populateSingleValueField(T result, Map attributeValueMap, Field field, AttributeMetaData attributeInfo) throws NamingException, IllegalAccessException { + private void populateSingleValueField(T result, Map attributeValueMap, Field field, + AttributeMetaData attributeInfo) throws NamingException, IllegalAccessException { Attribute attribute = attributeValueMap.get(attributeInfo.getName()); - // There is no guarantee that this attribute is present in the directory - so ignore nulls + // There is no guarantee that this attribute is present in the directory - so + // ignore nulls if (attribute != null) { // Grab the JNDI value Object value = attribute.get(); // Check the value is not null if (value != null) { - // Convert the JNDI value to its Java representation - this will throw if the + // Convert the JNDI value to its Java representation - this will throw if + // the // conversion fails Object convertedValue = converterManager.convert(value, attributeInfo.getSyntax(), attributeInfo.getValueClass()); @@ -418,9 +457,9 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { public Name getId(Object entry) { try { return (Name) getIdField(entry).get(entry); - } catch (Exception e) { - throw new InvalidEntryException(String.format("Can't get Id field from Entry %1$s", entry), - e); + } + catch (Exception e) { + throw new InvalidEntryException(String.format("Can't get Id field from Entry %1$s", entry), e); } } @@ -432,9 +471,9 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { public void setId(Object entry, Name id) { try { getIdField(entry).set(entry, id); - } catch (Exception e) { - throw new InvalidEntryException( - String.format("Can't set Id field on Entry %s to %s", entry, id), e); + } + catch (Exception e) { + throw new InvalidEntryException(String.format("Can't set Id field on Entry %s to %s", entry, id), e); } } @@ -442,13 +481,13 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { public Name getCalculatedId(Object entry) { Assert.notNull(entry, "Entry must not be null"); EntityData entityData = getEntityData(entry.getClass()); - if(entityData.metaData.canCalculateDn()) { + if (entityData.metaData.canCalculateDn()) { Set dnAttributes = entityData.metaData.getDnAttributes(); LdapNameBuilder ldapNameBuilder = LdapNameBuilder.newInstance(entityData.metaData.getBase()); for (AttributeMetaData dnAttribute : dnAttributes) { Object dnFieldValue = ReflectionUtils.getField(dnAttribute.getField(), entry); - if(dnFieldValue == null) { + if (dnFieldValue == null) { throw new IllegalStateException( String.format("DnAttribute for field %s on class %s is null; cannot build DN", dnAttribute.getField().getName(), entry.getClass().getName())); @@ -467,7 +506,7 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { public Filter filterFor(Class clazz, Filter baseFilter) { Filter ocFilter = getEntityData(clazz).ocFilter; - if(baseFilter == null) { + if (baseFilter == null) { return ocFilter; } @@ -479,12 +518,12 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { public String attributeFor(Class clazz, String fieldName) { try { Field field = clazz.getDeclaredField(fieldName); - AttributeMetaData attributeMetaData = - getEntityData(clazz).metaData.getAttribute(field); + AttributeMetaData attributeMetaData = getEntityData(clazz).metaData.getAttribute(field); return attributeMetaData.getName().toString(); - } catch (NoSuchFieldException e) { - throw new IllegalArgumentException( - String.format("Field %s cannot be found in class %s", fieldName, clazz), e); + } + catch (NoSuchFieldException e) { + throw new IllegalArgumentException(String.format("Field %s cannot be found in class %s", fieldName, clazz), + e); } } @@ -495,11 +534,12 @@ public class DefaultObjectDirectoryMapper implements ObjectDirectoryMapper { static boolean collectionContainsAll(Collection collection, Set shouldBePresent) { for (Object o : shouldBePresent) { - if(!collection.contains(o)) { + if (!collection.contains(o)) { return false; } } return true; } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/impl/InvalidEntryException.java b/core/src/main/java/org/springframework/ldap/odm/core/impl/InvalidEntryException.java index facb9a56..901add11 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/impl/InvalidEntryException.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/impl/InvalidEntryException.java @@ -19,13 +19,15 @@ package org.springframework.ldap.odm.core.impl; import org.springframework.ldap.odm.core.OdmException; /** - * Thrown to indicate that an instance is not suitable for persisting in the LDAP directory. - * + * Thrown to indicate that an instance is not suitable for persisting in the LDAP + * directory. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> * */ @SuppressWarnings("serial") public class InvalidEntryException extends OdmException { + public InvalidEntryException(String message) { super(message); } @@ -33,4 +35,5 @@ public class InvalidEntryException extends OdmException { public InvalidEntryException(String message, Throwable reason) { super(message, reason); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/impl/MetaDataException.java b/core/src/main/java/org/springframework/ldap/odm/core/impl/MetaDataException.java index 0b52b82e..7322b42e 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/impl/MetaDataException.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/impl/MetaDataException.java @@ -20,12 +20,13 @@ import org.springframework.ldap.odm.core.OdmException; /** * Thrown to indicate an error in the annotated meta-data. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> * */ @SuppressWarnings("serial") public class MetaDataException extends OdmException { + public MetaDataException(String message) { super(message); } @@ -33,4 +34,5 @@ public class MetaDataException extends OdmException { public MetaDataException(String message, Throwable reason) { super(message, reason); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/impl/ObjectMetaData.java b/core/src/main/java/org/springframework/ldap/odm/core/impl/ObjectMetaData.java index b98690e7..22e9c654 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/impl/ObjectMetaData.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/impl/ObjectMetaData.java @@ -36,10 +36,11 @@ import java.util.TreeSet; /* * An internal class to process the meta-data and reflection data for an entry. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ /* package */ final class ObjectMetaData implements Iterable { + private static final Logger LOG = LoggerFactory.getLogger(ObjectMetaData.class); private AttributeMetaData idAttribute; @@ -49,7 +50,7 @@ import java.util.TreeSet; private Set dnAttributes = new TreeSet(new Comparator() { @Override public int compare(AttributeMetaData a1, AttributeMetaData a2) { - if(!a1.isDnAttribute() || !a2.isDnAttribute()) { + if (!a1.isDnAttribute() || !a2.isDnAttribute()) { // Not interesting to compare these. return 0; } @@ -74,7 +75,7 @@ import java.util.TreeSet; /* * (non-Javadoc) - * + * * @see java.lang.Iterable#iterator() */ public Iterator iterator() { @@ -84,12 +85,12 @@ import java.util.TreeSet; public AttributeMetaData getAttribute(Field field) { return fieldToAttribute.get(field); } - + public ObjectMetaData(Class clazz) { if (LOG.isDebugEnabled()) { LOG.debug(String.format("Extracting metadata from %1$s", clazz)); } - + // Get object class metadata - the @Entity annotation Entry entity = clazz.getAnnotation(Entry.class); if (entity != null) { @@ -97,20 +98,22 @@ import java.util.TreeSet; // in @Entity(name={objectclass1, objectclass2}); String[] localObjectClasses = entity.objectClasses(); if (localObjectClasses != null && localObjectClasses.length > 0 && localObjectClasses[0].length() > 0) { - for (String localObjectClass:localObjectClasses) { + for (String localObjectClass : localObjectClasses) { objectClasses.add(new CaseIgnoreString(localObjectClass)); } - } else { + } + else { objectClasses.add(new CaseIgnoreString(clazz.getSimpleName())); } String base = entity.base(); - if(StringUtils.hasText(base)) { + if (StringUtils.hasText(base)) { this.base = LdapUtils.newLdapName(base); } - } else { - throw new MetaDataException(String.format("Class %1$s must have a class level %2$s annotation", clazz, - Entry.class)); + } + else { + throw new MetaDataException( + String.format("Class %1$s must have a class level %2$s annotation", clazz, Entry.class)); } // Check the class is final @@ -129,26 +132,26 @@ import java.util.TreeSet; continue; } - AttributeMetaData currentAttributeMetaData=new AttributeMetaData(field); + AttributeMetaData currentAttributeMetaData = new AttributeMetaData(field); if (currentAttributeMetaData.isId()) { - if (idAttribute!=null) { + if (idAttribute != null) { // There can be only one id field - throw new MetaDataException( - String.format("You man have only one field with the %1$s annotation in class %2$s", Id.class, clazz)); + throw new MetaDataException(String.format( + "You man have only one field with the %1$s annotation in class %2$s", Id.class, clazz)); } - idAttribute=currentAttributeMetaData; + idAttribute = currentAttributeMetaData; } fieldToAttribute.put(field, currentAttributeMetaData); - if(currentAttributeMetaData.isDnAttribute()) { + if (currentAttributeMetaData.isDnAttribute()) { dnAttributes.add(currentAttributeMetaData); } } if (idAttribute == null) { throw new MetaDataException( - String.format("All Entry classes must define a field with the %1$s annotation, error in class %2$s", Id.class, - clazz)); + String.format("All Entry classes must define a field with the %1$s annotation, error in class %2$s", + Id.class, clazz)); } postProcessDnAttributes(clazz); @@ -165,18 +168,18 @@ import java.util.TreeSet; for (AttributeMetaData dnAttribute : dnAttributes) { int declaredIndex = dnAttribute.getDnAttribute().index(); - if(declaredIndex != -1) { + if (declaredIndex != -1) { hasIndexed = true; } - if(declaredIndex == -1) { + if (declaredIndex == -1) { hasNonIndexed = true; } } - if(hasIndexed && hasNonIndexed) { - throw new MetaDataException(String.format("At least one DnAttribute declared on class %s is indexed, " + - "which means that all DnAttributes must be indexed", clazz.toString())); + if (hasIndexed && hasNonIndexed) { + throw new MetaDataException(String.format("At least one DnAttribute declared on class %s is indexed, " + + "which means that all DnAttributes must be indexed", clazz.toString())); } indexedDnAttributes = hasIndexed; @@ -199,13 +202,14 @@ import java.util.TreeSet; } /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ @Override public String toString() { - return String.format("objectsClasses=%1$s | idField=%2$s | attributes=%3$s", - objectClasses, idAttribute.getName(), fieldToAttribute); + return String.format("objectsClasses=%1$s | idField=%2$s | attributes=%3$s", objectClasses, + idAttribute.getName(), fieldToAttribute); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/impl/UnmanagedClassException.java b/core/src/main/java/org/springframework/ldap/odm/core/impl/UnmanagedClassException.java index 369b30e5..9c22595f 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/impl/UnmanagedClassException.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/impl/UnmanagedClassException.java @@ -19,19 +19,21 @@ package org.springframework.ldap.odm.core.impl; import org.springframework.ldap.odm.core.OdmException; /** - * Thrown when an OdmManager method is called with a class - * which is not being managed by the OdmManager. - * + * Thrown when an OdmManager method is called with a class which is not being managed by + * the OdmManager. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> * */ @SuppressWarnings("serial") public class UnmanagedClassException extends OdmException { + public UnmanagedClassException(String message, Throwable reason) { super(message, reason); } - + public UnmanagedClassException(String message) { super(message); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/core/impl/package-info.java b/core/src/main/java/org/springframework/ldap/odm/core/impl/package-info.java index 58d83451..190d3e8d 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/impl/package-info.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/impl/package-info.java @@ -1,9 +1,11 @@ /** - * Provides a single public class which implements OdmManager. + * Provides a single public class which implements + * OdmManager. *

    - * The OdmManager implementation works in conjunction with {@link org.springframework.ldap.odm.typeconversion} to provide - * conversion between the representation of attributes in LDAP and in Java. - * + * The OdmManager implementation works in conjunction with + * {@link org.springframework.ldap.odm.typeconversion} to provide conversion between the + * representation of attributes in LDAP and in Java. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ + */ package org.springframework.ldap.odm.core.impl; \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/odm/core/package-info.java b/core/src/main/java/org/springframework/ldap/odm/core/package-info.java index 80856fbc..7a44c34b 100755 --- a/core/src/main/java/org/springframework/ldap/odm/core/package-info.java +++ b/core/src/main/java/org/springframework/ldap/odm/core/package-info.java @@ -1,10 +1,10 @@ /** * Provides an OdmManager interface for interaction with an LDAP directory. *

    - * Implementations of this interface are intended to be used in conjunction with classes + * Implementations of this interface are intended to be used in conjunction with classes * annotated with {@link org.springframework.ldap.odm.annotations}. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ + */ package org.springframework.ldap.odm.core; \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/ConverterException.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/ConverterException.java index 6ed6bc67..da6617fe 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/ConverterException.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/ConverterException.java @@ -19,12 +19,14 @@ package org.springframework.ldap.odm.typeconversion; import org.springframework.ldap.NamingException; /** - * Thrown by the conversion framework to indicate an error condition - typically a failed type conversion. - * + * Thrown by the conversion framework to indicate an error condition - typically a failed + * type conversion. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ @SuppressWarnings("serial") public final class ConverterException extends NamingException { + public ConverterException(final String message) { super(message); } @@ -32,4 +34,5 @@ public final class ConverterException extends NamingException { public ConverterException(final String message, final Throwable e) { super(message, e); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/ConverterManager.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/ConverterManager.java index c1b4ed89..e57dd722 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/ConverterManager.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/ConverterManager.java @@ -22,26 +22,28 @@ package org.springframework.ldap.odm.typeconversion; * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public interface ConverterManager { + /** - * Determine whether this converter manager is able to carry out a specified conversion. - * + * Determine whether this converter manager is able to carry out a specified + * conversion. * @param fromClass Convert from the fromClass. * @param syntax Using the LDAP syntax (may be null). * @param toClass To the toClass. - * @return True if the conversion is supported, false otherwise. + * @return True if the conversion is supported, false + * otherwise. */ boolean canConvert(Class fromClass, String syntax, Class toClass); /** - * Convert a given source object with an optional LDAP syntax to an instance of a given class. - * + * Convert a given source object with an optional LDAP syntax to an instance of a + * given class. * @param The class to convert to. * @param source The object to convert. * @param syntax The LDAP syntax to use (may be null). * @param toClass The class to convert to. * @return The converted object. - * * @throws ConverterException If the conversion can not be successfully completed. */ T convert(Object source, String syntax, Class toClass); + } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConversionServiceConverterManager.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConversionServiceConverterManager.java index 780d51ed..d22b21d7 100644 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConversionServiceConverterManager.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConversionServiceConverterManager.java @@ -29,9 +29,10 @@ import javax.naming.Name; * @since 2.0 */ public class ConversionServiceConverterManager implements ConverterManager { + private GenericConversionService conversionService; - private static final String DEFAULT_CONVERSION_SERVICE_CLASS = - "org.springframework.core.convert.support.DefaultConversionService"; + + private static final String DEFAULT_CONVERSION_SERVICE_CLASS = "org.springframework.core.convert.support.DefaultConversionService"; public ConversionServiceConverterManager(GenericConversionService conversionService) { this.conversionService = conversionService; @@ -39,14 +40,16 @@ public class ConversionServiceConverterManager implements ConverterManager { public ConversionServiceConverterManager() { ClassLoader defaultClassLoader = ClassUtils.getDefaultClassLoader(); - if(ClassUtils.isPresent(DEFAULT_CONVERSION_SERVICE_CLASS, defaultClassLoader)) { + if (ClassUtils.isPresent(DEFAULT_CONVERSION_SERVICE_CLASS, defaultClassLoader)) { try { Class clazz = ClassUtils.forName(DEFAULT_CONVERSION_SERVICE_CLASS, defaultClassLoader); conversionService = (GenericConversionService) clazz.newInstance(); - } catch (Exception e) { + } + catch (Exception e) { ReflectionUtils.handleReflectionException(e); } - } else { + } + else { conversionService = new GenericConversionService(); } @@ -69,14 +72,16 @@ public class ConversionServiceConverterManager implements ConverterManager { public final static class NameToStringConverter implements org.springframework.core.convert.converter.Converter { + @Override public String convert(Name source) { - if(source == null) { + if (source == null) { return null; } return source.toString(); } + } public static final class StringToNameConverter @@ -84,12 +89,13 @@ public class ConversionServiceConverterManager implements ConverterManager { @Override public Name convert(String source) { - if(source == null) { + if (source == null) { return null; } return LdapUtils.newLdapName(source); } + } } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/Converter.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/Converter.java index e3cfb6ed..6f034484 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/Converter.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/Converter.java @@ -18,13 +18,13 @@ package org.springframework.ldap.odm.typeconversion.impl; /** * Interface specifying the conversion between two classes - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public interface Converter { + /** * Attempt to convert a given object to a named class. - * * @param The class to convert to. * @param source The object to convert. * @param toClass The class to convert to. @@ -32,4 +32,5 @@ public interface Converter { * @throws Exception Any exception may be throw by a Converter on error. */ T convert(Object source, Class toClass) throws Exception; + } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerFactoryBean.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerFactoryBean.java index 598976fd..4eb12a03 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerFactoryBean.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerFactoryBean.java @@ -25,18 +25,21 @@ import java.util.HashSet; import java.util.Set; /** - * A utility class to allow {@link ConverterManagerImpl} instances to be easily configured via spring.xml. + * A utility class to allow {@link ConverterManagerImpl} instances to be easily configured + * via spring.xml. *

    - * The following shows a typical simple example which creates two {@link Converter} instances: + * The following shows a typical simple example which creates two {@link Converter} + * instances: *

      *
    • fromStringConverter
    • *
    • toStringConverter
    • *
    * Configured in an {@link ConverterManagerImpl} to: *
      - *
    • Use fromStringConverter to convert from String to Byte, Short, - * Integer, Long, Float, Double, Boolean
    • - *
    • Use toStringConverter to convert from Byte, Short, + *
    • Use fromStringConverter to convert from String to + * Byte, Short, + * Integer, Long, Float, Double, Boolean
    • + *
    • Use toStringConverter to convert from Byte, Short, * Integer, Long, Float, Double, Boolean to String
    • *
    *
    @@ -84,102 +87,106 @@ import java.util.Set;
      *	 </set>
      *   </property>
      * </bean>
    - * 
    - * {@link ConverterConfig} has a second constructor which takes an additional parameter to allow - * an LDAP syntax to be defined. - * + * {@link ConverterConfig} has a second constructor which takes an additional + * parameter to allow an LDAP syntax to be defined. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public final class ConverterManagerFactoryBean implements FactoryBean { + private static final Logger LOG = LoggerFactory.getLogger(ConverterManagerFactoryBean.class); - /** + /** * Configuration information for a single Converter instance. */ public static final class ConverterConfig { + // The set of classes the Converter will convert from. private Set> fromClasses = new HashSet>(); // The (optional) LDAP syntax. - private String syntax=null; + private String syntax = null; // The set of classes the Converter will convert to. private Set> toClasses = new HashSet>(); // The Converter to use. - private Converter converter=null; - + private Converter converter = null; + public ConverterConfig() { } - + /** - * @param fromClasses Comma separated list of classes the {@link Converter} should can convert from. + * @param fromClasses Comma separated list of classes the {@link Converter} should + * can convert from. */ public void setFromClasses(Set> fromClasses) { - this.fromClasses=fromClasses; + this.fromClasses = fromClasses; } - + /** - * @param toClasses Comma separated list of classes the {@link Converter} can convert to. + * @param toClasses Comma separated list of classes the {@link Converter} can + * convert to. */ public void setToClasses(Set> toClasses) { - this.toClasses=toClasses; - + this.toClasses = toClasses; + } - + /** * @param syntax An LDAP syntax supported by the {@link Converter}. */ public void setSyntax(String syntax) { - this.syntax=syntax; + this.syntax = syntax; } - + /** * @param converter The {@link Converter} to use. */ public void setConverter(Converter converter) { - this.converter=converter; + this.converter = converter; } - + @Override public String toString() { - return String.format("fromClasses=%1$s, syntax=%2$s, toClasses=%3$s, converter=%4$s", - fromClasses, syntax, toClasses, converter); + return String.format("fromClasses=%1$s, syntax=%2$s, toClasses=%3$s, converter=%4$s", fromClasses, syntax, + toClasses, converter); } + } - - private Set converterConfigList=null; - - + + private Set converterConfigList = null; + /** * @param converterConfigList */ public void setConverterConfig(Set converterConfigList) { - this.converterConfigList=converterConfigList; + this.converterConfigList = converterConfigList; } - + /** - * Creates a ConverterManagerImpl populating it with Converter instances from the converterConfigList property. - * - * @return The newly created {@link org.springframework.ldap.odm.typeconversion.ConverterManager}. - * @throws ClassNotFoundException Thrown if any of the classes to be converted to or from cannot be found. - * + * Creates a ConverterManagerImpl populating it with Converter instances from the + * converterConfigList property. + * @return The newly created + * {@link org.springframework.ldap.odm.typeconversion.ConverterManager}. + * @throws ClassNotFoundException Thrown if any of the classes to be converted to or + * from cannot be found. + * * @see org.springframework.beans.factory.FactoryBean#getObject() */ public Object getObject() throws Exception { - if (converterConfigList==null) { + if (converterConfigList == null) { throw new FactoryBeanNotInitializedException("converterConfigList has not been set"); } - + ConverterManagerImpl result = new ConverterManagerImpl(); for (ConverterConfig converterConfig : converterConfigList) { - if (converterConfig.fromClasses==null || - converterConfig.toClasses==null || - converterConfig.converter==null) { - + if (converterConfig.fromClasses == null || converterConfig.toClasses == null + || converterConfig.converter == null) { + throw new FactoryBeanNotInitializedException( String.format("All of fromClasses, toClasses and converter must be specified in bean %1$s", - converterConfig.toString())); + converterConfig.toString())); } for (Class fromClass : converterConfig.fromClasses) { for (Class toClass : converterConfig.toClasses) { @@ -190,20 +197,25 @@ public final class ConverterManagerFactoryBean implements FactoryBean { } } } - return result; + return result; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.springframework.beans.factory.FactoryBean#getObjectType() */ public Class getObjectType() { return ConverterManagerImpl.class; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.springframework.beans.factory.FactoryBean#isSingleton() */ public boolean isSingleton() { return true; } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerImpl.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerImpl.java index 65244148..aab7112b 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerImpl.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerImpl.java @@ -23,22 +23,26 @@ import java.util.HashMap; import java.util.Map; /** - * An implementation of {@link org.springframework.ldap.odm.typeconversion.ConverterManager}. + * An implementation of + * {@link org.springframework.ldap.odm.typeconversion.ConverterManager}. *

    * The algorithm used is to: *

      - *
    1. Try to find and use a {@link Converter} registered for the - * fromClass, syntax and toClass and use it.
    2. - *
    3. If this fails, then if the toClass isAssignableFrom - * the fromClass then just assign it.
    4. - *
    5. If this fails try to find and use a {@link Converter} registered for the fromClass and - * the toClass ignoring the syntax.
    6. - *
    7. If this fails then throw a {@link org.springframework.ldap.odm.typeconversion.ConverterException}.
    8. + *
    9. Try to find and use a {@link Converter} registered for the fromClass, + * syntax and toClass and use it.
    10. + *
    11. If this fails, then if the toClass isAssignableFrom the + * fromClass then just assign it.
    12. + *
    13. If this fails try to find and use a {@link Converter} registered for the + * fromClass and the toClass ignoring the + * syntax.
    14. + *
    15. If this fails then throw a + * {@link org.springframework.ldap.odm.typeconversion.ConverterException}.
    16. *
    - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public final class ConverterManagerImpl implements ConverterManager { + /** * Separator used to form keys into the converters Map. */ @@ -50,8 +54,8 @@ public final class ConverterManagerImpl implements ConverterManager { private final Map converters = new HashMap(); /** - * Make a key into the converters map - the keys is formed from the fromClass, syntax and toClass - * + * Make a key into the converters map - the keys is formed from the + * fromClass, syntax and toClass * @param fromClass The class to convert from. * @param syntax The LDAP syntax. * @param toClass The class to convert to. @@ -59,8 +63,8 @@ public final class ConverterManagerImpl implements ConverterManager { */ private String makeConverterKey(Class fromClass, String syntax, Class toClass) { StringBuilder key = new StringBuilder(); - if (syntax==null) { - syntax=""; + if (syntax == null) { + syntax = ""; } key.append(fromClass.getName()).append(KEY_SEP).append(syntax).append(KEY_SEP).append(toClass.getName()); return key.toString(); @@ -73,7 +77,7 @@ public final class ConverterManagerImpl implements ConverterManager { } /** - * Used to help in the process of dealing with primitive types by mapping them to + * Used to help in the process of dealing with primitive types by mapping them to * their equivalent boxed class. */ private static Map, Class> primitiveTypeMap = new HashMap, Class>(); @@ -88,10 +92,12 @@ public final class ConverterManagerImpl implements ConverterManager { primitiveTypeMap.put(Character.TYPE, Character.class); } - - /* + /* * (non-Javadoc) - * @see org.springframework.ldap.odm.typeconversion.ConverterManager#canConvert(java.lang.Class, java.lang.String, java.lang.Class) + * + * @see + * org.springframework.ldap.odm.typeconversion.ConverterManager#canConvert(java.lang. + * Class, java.lang.String, java.lang.Class) */ public boolean canConvert(Class fromClass, String syntax, Class toClass) { Class fixedToClass = toClass; @@ -102,15 +108,17 @@ public final class ConverterManagerImpl implements ConverterManager { if (fromClass.isPrimitive()) { fixedFromClass = primitiveTypeMap.get(fromClass); } - return fixedToClass.isAssignableFrom(fixedFromClass) || - (converters.get(makeConverterKey(fixedFromClass, syntax, fixedToClass)) != null) || - (converters.get(makeConverterKey(fixedFromClass, null, fixedToClass)) != null); + return fixedToClass.isAssignableFrom(fixedFromClass) + || (converters.get(makeConverterKey(fixedFromClass, syntax, fixedToClass)) != null) + || (converters.get(makeConverterKey(fixedFromClass, null, fixedToClass)) != null); } - - /* + /* * (non-Javadoc) - * @see org.springframework.ldap.odm.typeconversion.ConverterManager#convert(java.lang.Object, java.lang.String, java.lang.Class) + * + * @see + * org.springframework.ldap.odm.typeconversion.ConverterManager#convert(java.lang. + * Object, java.lang.String, java.lang.Class) */ @SuppressWarnings("unchecked") public T convert(Object source, String syntax, Class toClass) { @@ -130,7 +138,8 @@ public final class ConverterManagerImpl implements ConverterManager { if (syntaxConverter != null) { try { result = syntaxConverter.convert(source, targetClass); - } catch (Exception e) { + } + catch (Exception e) { // Ignore as we may still be able to convert successfully } } @@ -147,26 +156,28 @@ public final class ConverterManagerImpl implements ConverterManager { if (nullSyntaxConverter != null) { try { result = nullSyntaxConverter.convert(source, targetClass); - } catch (Exception e) { + } + catch (Exception e) { // Handled at the end of the method } } } if (result == null) { - throw new ConverterException(String.format( - "Cannot convert %1$s of class %2$s via syntax %3$s to class %4$s", source, source.getClass(), - syntax, toClass)); + throw new ConverterException( + String.format("Cannot convert %1$s of class %2$s via syntax %3$s to class %4$s", source, + source.getClass(), syntax, toClass)); } - // We cannot do the safe thing of doing a .cast as we need to rely on auto-unboxing to deal with primitives! - return (T)result; + // We cannot do the safe thing of doing a .cast as we need to rely on + // auto-unboxing to deal with primitives! + return (T) result; } /** * Add a {@link Converter} to this ConverterManager. - * - * @param fromClass The class the Converter should be used to convert from. + * @param fromClass The class the Converter should be used to convert + * from. * @param syntax The LDAP syntax that the Converter should be used for. * @param toClass The class the Converter should be used to convert to. * @param converter The Converter to add. @@ -174,4 +185,5 @@ public final class ConverterManagerImpl implements ConverterManager { public void addConverter(Class fromClass, String syntax, Class toClass, Converter converter) { converters.put(makeConverterKey(fromClass, syntax, toClass), converter); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/StringConverter.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/StringConverter.java index ed364303..08285e97 100644 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/StringConverter.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/StringConverter.java @@ -4,4 +4,5 @@ package org.springframework.ldap.odm.typeconversion.impl; * @author Mattias Hellborg Arthursson */ public class StringConverter { + } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/FromStringConverter.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/FromStringConverter.java index a36ff2b5..bdb9bfe0 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/FromStringConverter.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/FromStringConverter.java @@ -21,20 +21,24 @@ import org.springframework.ldap.odm.typeconversion.impl.Converter; import java.lang.reflect.Constructor; /** - * A Converter from a {@link java.lang.String} to any class which has a single argument + * A Converter from a {@link java.lang.String} to any class which has a single argument * public constructor taking a {@link java.lang.String}. *

    * This should only be used as a fall-back converter, as a last attempt. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public final class FromStringConverter implements Converter { - /* (non-Javadoc) - * @see org.springframework.ldap.odm.typeconversion.impl.Converter#convert(java.lang.Object, java.lang.Class) + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.odm.typeconversion.impl.Converter#convert(java.lang. + * Object, java.lang.Class) */ public T convert(Object source, Class toClass) throws Exception { Constructor constructor = toClass.getConstructor(java.lang.String.class); return constructor.newInstance(source); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/ToStringConverter.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/ToStringConverter.java index 52bb2076..60318555 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/ToStringConverter.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/ToStringConverter.java @@ -18,20 +18,24 @@ package org.springframework.ldap.odm.typeconversion.impl.converters; import org.springframework.ldap.odm.typeconversion.impl.Converter; - /** - * A Converter from any class to a {@link java.lang.String} via the toString method. + * A Converter from any class to a {@link java.lang.String} via the toString + * method. *

    * This should only be used as a fall-back converter, as a last attempt. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public final class ToStringConverter implements Converter { - /* (non-Javadoc) - * @see org.springframework.ldap.odm.typeconversion.impl.Converter#convert(java.lang.Object, java.lang.Class) + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.odm.typeconversion.impl.Converter#convert(java.lang. + * Object, java.lang.Class) */ public T convert(Object source, Class toClass) { return toClass.cast(source.toString()); } + } diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/package-info.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/package-info.java index f4b8a24b..56e9d915 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/package-info.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/package-info.java @@ -1,6 +1,7 @@ /** - * Provides some basic implementations of the {@link org.springframework.ldap.odm.typeconversion.impl.Converter} interface. - * + * Provides some basic implementations of the + * {@link org.springframework.ldap.odm.typeconversion.impl.Converter} interface. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/package-info.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/package-info.java index 76d9ef63..39af3c87 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/package-info.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/package-info.java @@ -1,8 +1,8 @@ /** - * Provides an implementation of the {@link org.springframework.ldap.odm.typeconversion.ConverterManager} interface. - * + * Provides an implementation of the + * {@link org.springframework.ldap.odm.typeconversion.ConverterManager} interface. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ package org.springframework.ldap.odm.typeconversion.impl; - diff --git a/core/src/main/java/org/springframework/ldap/odm/typeconversion/package-info.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/package-info.java index 164db597..b9a156c7 100755 --- a/core/src/main/java/org/springframework/ldap/odm/typeconversion/package-info.java +++ b/core/src/main/java/org/springframework/ldap/odm/typeconversion/package-info.java @@ -2,9 +2,8 @@ * Provides an interface to be implemented to create a type conversion framework. *

    * This is used to convert between the LDAP and Java representations of attributes. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ package org.springframework.ldap.odm.typeconversion; - diff --git a/core/src/main/java/org/springframework/ldap/pool/DelegatingContext.java b/core/src/main/java/org/springframework/ldap/pool/DelegatingContext.java index ad508b02..05a52f5e 100644 --- a/core/src/main/java/org/springframework/ldap/pool/DelegatingContext.java +++ b/core/src/main/java/org/springframework/ldap/pool/DelegatingContext.java @@ -32,18 +32,19 @@ import java.util.Hashtable; * Used by {@link PoolingContextSource} to wrap a {@link Context}, delegating most methods * to the underlying context, retains a reference to the pool the context was checked out * from and returns itself to the pool when {@link #close()} is called. - * + * * @author Eric Dalquist */ public class DelegatingContext implements Context { + private KeyedObjectPool keyedObjectPool; + private Context delegateContext; + private final DirContextType dirContextType; - /** * Create a new delegating context for the specified pool, context and context type. - * * @param keyedObjectPool The pool the delegate context was checked out from. * @param delegateContext The context to delegate operations to. * @param dirContextType The type of context, used as a key for the pool. @@ -53,37 +54,35 @@ public class DelegatingContext implements Context { Assert.notNull(keyedObjectPool, "keyedObjectPool may not be null"); Assert.notNull(delegateContext, "delegateContext may not be null"); Assert.notNull(dirContextType, "dirContextType may not be null"); - + this.keyedObjectPool = keyedObjectPool; this.delegateContext = delegateContext; this.dirContextType = dirContextType; } - - - //***** Helper Methods *****// - + + // ***** Helper Methods *****// + /** * @return The direct delegate for this context proxy */ public Context getDelegateContext() { return this.delegateContext; } - + /** * Recursivley inspect delegates until a non-delegating context is found. - * * @return The innermost (real) Context that is being delegated to. */ public Context getInnermostDelegateContext() { final Context delegateContext = this.getDelegateContext(); - + if (delegateContext instanceof DelegatingContext) { - return ((DelegatingContext)delegateContext).getInnermostDelegateContext(); + return ((DelegatingContext) delegateContext).getInnermostDelegateContext(); } return delegateContext; } - + /** * @throws NamingException If the delegate is null, {@link #close()} has been called. */ @@ -93,8 +92,7 @@ public class DelegatingContext implements Context { } } - - //***** Object methods *****// + // ***** Object methods *****// /** * @see java.lang.Object#equals(java.lang.Object) @@ -106,13 +104,13 @@ public class DelegatingContext implements Context { if (!(obj instanceof Context)) { return false; } - + final Context thisContext = this.getInnermostDelegateContext(); - Context otherContext = (Context)obj; + Context otherContext = (Context) obj; if (otherContext instanceof DelegatingContext) { - otherContext = ((DelegatingContext)otherContext).getInnermostDelegateContext(); + otherContext = ((DelegatingContext) otherContext).getInnermostDelegateContext(); } - + return thisContext == otherContext || (thisContext != null && thisContext.equals(otherContext)); } @@ -131,9 +129,8 @@ public class DelegatingContext implements Context { final Context context = this.getInnermostDelegateContext(); return (context != null ? context.toString() : "Context is closed"); } - - - //***** Context Interface Delegates *****// + + // ***** Context Interface Delegates *****// /** * @see javax.naming.Context#addToEnvironment(java.lang.String, java.lang.Object) @@ -166,24 +163,25 @@ public class DelegatingContext implements Context { if (context == null) { return; } - - //Get a local reference so the member can be nulled earlier + + // Get a local reference so the member can be nulled earlier this.delegateContext = null; - //Return the object to the Pool and then null the pool reference + // Return the object to the Pool and then null the pool reference try { boolean valid = true; if (context instanceof FailureAwareContext) { FailureAwareContext failureAwareContext = (FailureAwareContext) context; - if(failureAwareContext.hasFailed()) { + if (failureAwareContext.hasFailed()) { valid = false; } } if (valid) { this.keyedObjectPool.returnObject(this.dirContextType, context); - } else { + } + else { this.keyedObjectPool.invalidateObject(this.dirContextType, context); } } @@ -391,4 +389,5 @@ public class DelegatingContext implements Context { this.assertOpen(); this.getDelegateContext().unbind(name); } + } diff --git a/core/src/main/java/org/springframework/ldap/pool/DelegatingDirContext.java b/core/src/main/java/org/springframework/ldap/pool/DelegatingDirContext.java index 69922d99..4b3a5a23 100644 --- a/core/src/main/java/org/springframework/ldap/pool/DelegatingDirContext.java +++ b/core/src/main/java/org/springframework/ldap/pool/DelegatingDirContext.java @@ -30,56 +30,55 @@ import javax.naming.directory.ModificationItem; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; - /** - * Used by {@link PoolingContextSource} to wrap a {@link DirContext}, delegating most methods - * to the underlying context. This class extends {@link DelegatingContext} which handles returning - * the context to the pool on a call to {@link #close()} - * + * Used by {@link PoolingContextSource} to wrap a {@link DirContext}, delegating most + * methods to the underlying context. This class extends {@link DelegatingContext} which + * handles returning the context to the pool on a call to {@link #close()} + * * @author Eric Dalquist */ public class DelegatingDirContext extends DelegatingContext implements DirContext, DirContextProxy { + private DirContext delegateDirContext; /** - * Create a new delegating dir context for the specified pool, context and context type. - * + * Create a new delegating dir context for the specified pool, context and context + * type. * @param keyedObjectPool The pool the delegate context was checked out from. * @param delegateDirContext The dir context to delegate operations to. * @param dirContextType The type of context, used as a key for the pool. * @throws IllegalArgumentException if any of the arguments are null */ - public DelegatingDirContext(KeyedObjectPool keyedObjectPool, DirContext delegateDirContext, DirContextType dirContextType) { + public DelegatingDirContext(KeyedObjectPool keyedObjectPool, DirContext delegateDirContext, + DirContextType dirContextType) { super(keyedObjectPool, delegateDirContext, dirContextType); Assert.notNull(delegateDirContext, "delegateDirContext may not be null"); this.delegateDirContext = delegateDirContext; } - - - //***** Helper Methods *****// - + + // ***** Helper Methods *****// + /** * @return The direct delegate for this dir context proxy */ public DirContext getDelegateDirContext() { return this.delegateDirContext; } - + public Context getDelegateContext() { return this.getDelegateDirContext(); } /** * Recursivley inspect delegates until a non-delegating dir context is found. - * * @return The innermost (real) DirContext that is being delegated to. */ public DirContext getInnermostDelegateDirContext() { final DirContext delegateDirContext = this.getDelegateDirContext(); if (delegateDirContext instanceof DelegatingDirContext) { - return ((DelegatingDirContext)delegateDirContext).getInnermostDelegateDirContext(); + return ((DelegatingDirContext) delegateDirContext).getInnermostDelegateDirContext(); } return delegateDirContext; @@ -93,8 +92,7 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex super.assertOpen(); } - - //***** Object methods *****// + // ***** Object methods *****// /** * @see java.lang.Object#equals(java.lang.Object) @@ -106,13 +104,13 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex if (!(obj instanceof DirContext)) { return false; } - + final DirContext thisDirContext = this.getInnermostDelegateDirContext(); - DirContext otherDirContext = (DirContext)obj; + DirContext otherDirContext = (DirContext) obj; if (otherDirContext instanceof DelegatingDirContext) { - otherDirContext = ((DelegatingDirContext)otherDirContext).getInnermostDelegateDirContext(); + otherDirContext = ((DelegatingDirContext) otherDirContext).getInnermostDelegateDirContext(); } - + return thisDirContext == otherDirContext || (thisDirContext != null && thisDirContext.equals(otherDirContext)); } @@ -132,21 +130,22 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex return (context != null ? context.toString() : "DirContext is closed"); } + // ***** DirContextProxy Interface Methods *****// - //***** DirContextProxy Interface Methods *****// - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.springframework.ldap.core.DirContextProxy#getTargetContext() */ public DirContext getTargetContext() { return this.getInnermostDelegateDirContext(); } - - - //***** DirContext Interface Delegates *****// + + // ***** DirContext Interface Delegates *****// /** - * @see javax.naming.directory.DirContext#bind(javax.naming.Name, java.lang.Object, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#bind(javax.naming.Name, java.lang.Object, + * javax.naming.directory.Attributes) */ public void bind(Name name, Object obj, Attributes attrs) throws NamingException { this.assertOpen(); @@ -154,7 +153,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#bind(java.lang.String, java.lang.Object, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#bind(java.lang.String, java.lang.Object, + * javax.naming.directory.Attributes) */ public void bind(String name, Object obj, Attributes attrs) throws NamingException { this.assertOpen(); @@ -162,21 +162,24 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#createSubcontext(javax.naming.Name, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#createSubcontext(javax.naming.Name, + * javax.naming.directory.Attributes) */ public DirContext createSubcontext(Name name, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Cannot call createSubcontext on a pooled context"); } /** - * @see javax.naming.directory.DirContext#createSubcontext(java.lang.String, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#createSubcontext(java.lang.String, + * javax.naming.directory.Attributes) */ public DirContext createSubcontext(String name, Attributes attrs) throws NamingException { throw new UnsupportedOperationException("Cannot call createSubcontext on a pooled context"); } /** - * @see javax.naming.directory.DirContext#getAttributes(javax.naming.Name, java.lang.String[]) + * @see javax.naming.directory.DirContext#getAttributes(javax.naming.Name, + * java.lang.String[]) */ public Attributes getAttributes(Name name, String[] attrIds) throws NamingException { this.assertOpen(); @@ -192,7 +195,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#getAttributes(java.lang.String, java.lang.String[]) + * @see javax.naming.directory.DirContext#getAttributes(java.lang.String, + * java.lang.String[]) */ public Attributes getAttributes(String name, String[] attrIds) throws NamingException { this.assertOpen(); @@ -236,7 +240,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#modifyAttributes(javax.naming.Name, int, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#modifyAttributes(javax.naming.Name, int, + * javax.naming.directory.Attributes) */ public void modifyAttributes(Name name, int modOp, Attributes attrs) throws NamingException { this.assertOpen(); @@ -244,7 +249,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#modifyAttributes(javax.naming.Name, javax.naming.directory.ModificationItem[]) + * @see javax.naming.directory.DirContext#modifyAttributes(javax.naming.Name, + * javax.naming.directory.ModificationItem[]) */ public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { this.assertOpen(); @@ -252,7 +258,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#modifyAttributes(java.lang.String, int, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#modifyAttributes(java.lang.String, int, + * javax.naming.directory.Attributes) */ public void modifyAttributes(String name, int modOp, Attributes attrs) throws NamingException { this.assertOpen(); @@ -260,7 +267,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#modifyAttributes(java.lang.String, javax.naming.directory.ModificationItem[]) + * @see javax.naming.directory.DirContext#modifyAttributes(java.lang.String, + * javax.naming.directory.ModificationItem[]) */ public void modifyAttributes(String name, ModificationItem[] mods) throws NamingException { this.assertOpen(); @@ -268,7 +276,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#rebind(javax.naming.Name, java.lang.Object, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#rebind(javax.naming.Name, java.lang.Object, + * javax.naming.directory.Attributes) */ public void rebind(Name name, Object obj, Attributes attrs) throws NamingException { this.assertOpen(); @@ -276,7 +285,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#rebind(java.lang.String, java.lang.Object, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#rebind(java.lang.String, java.lang.Object, + * javax.naming.directory.Attributes) */ public void rebind(String name, Object obj, Attributes attrs) throws NamingException { this.assertOpen(); @@ -284,15 +294,18 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#search(javax.naming.Name, javax.naming.directory.Attributes, java.lang.String[]) + * @see javax.naming.directory.DirContext#search(javax.naming.Name, + * javax.naming.directory.Attributes, java.lang.String[]) */ - public NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { + public NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) + throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, matchingAttributes, attributesToReturn); } /** - * @see javax.naming.directory.DirContext#search(javax.naming.Name, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#search(javax.naming.Name, + * javax.naming.directory.Attributes) */ public NamingEnumeration search(Name name, Attributes matchingAttributes) throws NamingException { this.assertOpen(); @@ -300,31 +313,38 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#search(javax.naming.Name, java.lang.String, java.lang.Object[], javax.naming.directory.SearchControls) + * @see javax.naming.directory.DirContext#search(javax.naming.Name, java.lang.String, + * java.lang.Object[], javax.naming.directory.SearchControls) */ - public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { + public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, + SearchControls cons) throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, filterExpr, filterArgs, cons); } /** - * @see javax.naming.directory.DirContext#search(javax.naming.Name, java.lang.String, javax.naming.directory.SearchControls) + * @see javax.naming.directory.DirContext#search(javax.naming.Name, java.lang.String, + * javax.naming.directory.SearchControls) */ - public NamingEnumeration search(Name name, String filter, SearchControls cons) throws NamingException { + public NamingEnumeration search(Name name, String filter, SearchControls cons) + throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, filter, cons); } /** - * @see javax.naming.directory.DirContext#search(java.lang.String, javax.naming.directory.Attributes, java.lang.String[]) + * @see javax.naming.directory.DirContext#search(java.lang.String, + * javax.naming.directory.Attributes, java.lang.String[]) */ - public NamingEnumeration search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { + public NamingEnumeration search(String name, Attributes matchingAttributes, + String[] attributesToReturn) throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, matchingAttributes, attributesToReturn); } /** - * @see javax.naming.directory.DirContext#search(java.lang.String, javax.naming.directory.Attributes) + * @see javax.naming.directory.DirContext#search(java.lang.String, + * javax.naming.directory.Attributes) */ public NamingEnumeration search(String name, Attributes matchingAttributes) throws NamingException { this.assertOpen(); @@ -332,17 +352,21 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } /** - * @see javax.naming.directory.DirContext#search(java.lang.String, java.lang.String, java.lang.Object[], javax.naming.directory.SearchControls) + * @see javax.naming.directory.DirContext#search(java.lang.String, java.lang.String, + * java.lang.Object[], javax.naming.directory.SearchControls) */ - public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { + public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, + SearchControls cons) throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, filterExpr, filterArgs, cons); } /** - * @see javax.naming.directory.DirContext#search(java.lang.String, java.lang.String, javax.naming.directory.SearchControls) + * @see javax.naming.directory.DirContext#search(java.lang.String, java.lang.String, + * javax.naming.directory.SearchControls) */ - public NamingEnumeration search(String name, String filter, SearchControls cons) throws NamingException { + public NamingEnumeration search(String name, String filter, SearchControls cons) + throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, filter, cons); } @@ -358,4 +382,5 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex super.close(); this.delegateDirContext = null; } + } diff --git a/core/src/main/java/org/springframework/ldap/pool/DelegatingLdapContext.java b/core/src/main/java/org/springframework/ldap/pool/DelegatingLdapContext.java index f8446690..0ee5617d 100644 --- a/core/src/main/java/org/springframework/ldap/pool/DelegatingLdapContext.java +++ b/core/src/main/java/org/springframework/ldap/pool/DelegatingLdapContext.java @@ -27,40 +27,41 @@ import javax.naming.ldap.ExtendedResponse; import javax.naming.ldap.LdapContext; /** - * Used by {@link PoolingContextSource} to wrap a {@link LdapContext}, delegating most methods - * to the underlying context. This class extends {@link DelegatingDirContext} which handles returning - * the context to the pool on a call to {@link #close()} - * + * Used by {@link PoolingContextSource} to wrap a {@link LdapContext}, delegating most + * methods to the underlying context. This class extends {@link DelegatingDirContext} + * which handles returning the context to the pool on a call to {@link #close()} + * * @author Eric Dalquist */ public class DelegatingLdapContext extends DelegatingDirContext implements LdapContext { + private LdapContext delegateLdapContext; /** - * Create a new delegating ldap context for the specified pool, context and context type. - * + * Create a new delegating ldap context for the specified pool, context and context + * type. * @param keyedObjectPool The pool the delegate context was checked out from. * @param delegateLdapContext The ldap context to delegate operations to. * @param dirContextType The type of context, used as a key for the pool. * @throws IllegalArgumentException if any of the arguments are null */ - public DelegatingLdapContext(KeyedObjectPool keyedObjectPool, LdapContext delegateLdapContext, DirContextType dirContextType) { + public DelegatingLdapContext(KeyedObjectPool keyedObjectPool, LdapContext delegateLdapContext, + DirContextType dirContextType) { super(keyedObjectPool, delegateLdapContext, dirContextType); Assert.notNull(delegateLdapContext, "delegateLdapContext may not be null"); this.delegateLdapContext = delegateLdapContext; } - - - //***** Helper Methods *****// - + + // ***** Helper Methods *****// + /** * @return The direct delegate for this ldap context proxy */ public LdapContext getDelegateLdapContext() { return this.delegateLdapContext; } - + // cannot return subtype in overridden method unless Java5 public DirContext getDelegateDirContext() { return this.getDelegateLdapContext(); @@ -68,14 +69,13 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC /** * Recursivley inspect delegates until a non-delegating ldap context is found. - * * @return The innermost (real) DirContext that is being delegated to. */ public LdapContext getInnermostDelegateLdapContext() { final LdapContext delegateLdapContext = this.getDelegateLdapContext(); if (delegateLdapContext instanceof DelegatingLdapContext) { - return ((DelegatingLdapContext)delegateLdapContext).getInnermostDelegateLdapContext(); + return ((DelegatingLdapContext) delegateLdapContext).getInnermostDelegateLdapContext(); } return delegateLdapContext; @@ -89,8 +89,7 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC super.assertOpen(); } - - //***** Object methods *****// + // ***** Object methods *****// /** * @see java.lang.Object#equals(java.lang.Object) @@ -102,14 +101,15 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC if (!(obj instanceof LdapContext)) { return false; } - + final LdapContext thisLdapContext = this.getInnermostDelegateLdapContext(); - LdapContext otherLdapContext = (LdapContext)obj; + LdapContext otherLdapContext = (LdapContext) obj; if (otherLdapContext instanceof DelegatingLdapContext) { - otherLdapContext = ((DelegatingLdapContext)otherLdapContext).getInnermostDelegateLdapContext(); + otherLdapContext = ((DelegatingLdapContext) otherLdapContext).getInnermostDelegateLdapContext(); } - - return thisLdapContext == otherLdapContext || (thisLdapContext != null && thisLdapContext.equals(otherLdapContext)); + + return thisLdapContext == otherLdapContext + || (thisLdapContext != null && thisLdapContext.equals(otherLdapContext)); } /** @@ -127,9 +127,8 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC final LdapContext context = this.getInnermostDelegateLdapContext(); return (context != null ? context.toString() : "LdapContext is closed"); } - - - //***** LdapContext Interface Delegates *****// + + // ***** LdapContext Interface Delegates *****// /** * @see javax.naming.ldap.LdapContext#extendedOperation(javax.naming.ldap.ExtendedRequest) @@ -195,4 +194,5 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC super.close(); this.delegateLdapContext = null; } + } diff --git a/core/src/main/java/org/springframework/ldap/pool/DirContextType.java b/core/src/main/java/org/springframework/ldap/pool/DirContextType.java index 35082b48..b777a264 100644 --- a/core/src/main/java/org/springframework/ldap/pool/DirContextType.java +++ b/core/src/main/java/org/springframework/ldap/pool/DirContextType.java @@ -20,14 +20,14 @@ import org.springframework.ldap.core.ContextSource; import javax.naming.directory.DirContext; - /** * An enum representing the two types of {@link DirContext}s that can be returned by a * {@link ContextSource}. - * + * * @author Eric Dalquist */ public final class DirContextType { + private String name; private DirContextType(String name) { @@ -37,14 +37,17 @@ public final class DirContextType { public String toString() { return name; } - + /** - * The type of {@link DirContext} returned by {@link ContextSource#getReadOnlyContext()} + * The type of {@link DirContext} returned by + * {@link ContextSource#getReadOnlyContext()} */ public static final DirContextType READ_ONLY = new DirContextType("READ_ONLY"); - + /** - * The type of {@link DirContext} returned by {@link ContextSource#getReadWriteContext()} + * The type of {@link DirContext} returned by + * {@link ContextSource#getReadWriteContext()} */ public static final DirContextType READ_WRITE = new DirContextType("READ_WRITE"); + } diff --git a/core/src/main/java/org/springframework/ldap/pool/FailureAwareContext.java b/core/src/main/java/org/springframework/ldap/pool/FailureAwareContext.java index a8afcaa5..d5d9f6f8 100644 --- a/core/src/main/java/org/springframework/ldap/pool/FailureAwareContext.java +++ b/core/src/main/java/org/springframework/ldap/pool/FailureAwareContext.java @@ -20,5 +20,7 @@ package org.springframework.ldap.pool; * @author Mattias Hellborg Arthursson */ public interface FailureAwareContext { + boolean hasFailed(); + } diff --git a/core/src/main/java/org/springframework/ldap/pool/MutableDelegatingLdapContext.java b/core/src/main/java/org/springframework/ldap/pool/MutableDelegatingLdapContext.java index 559c291c..8d16584d 100644 --- a/core/src/main/java/org/springframework/ldap/pool/MutableDelegatingLdapContext.java +++ b/core/src/main/java/org/springframework/ldap/pool/MutableDelegatingLdapContext.java @@ -24,22 +24,20 @@ import javax.naming.ldap.Control; import javax.naming.ldap.LdapContext; /** - * Used by {@link MutablePoolingContextSource} to wrap a {@link LdapContext}, - * delegating most methods to the underlying context. This class extends - * {@link DelegatingLdapContext}, allowing request controls to be set on the - * wrapped ldap context. This enables the Spring LDAP pooling to be used for - * scenarios such as paged results. - * + * Used by {@link MutablePoolingContextSource} to wrap a {@link LdapContext}, delegating + * most methods to the underlying context. This class extends + * {@link DelegatingLdapContext}, allowing request controls to be set on the wrapped ldap + * context. This enables the Spring LDAP pooling to be used for scenarios such as paged + * results. + * * @author Ulrik Sandberg */ public class MutableDelegatingLdapContext extends DelegatingLdapContext { /** - * Create a new mutable delegating ldap context for the specified pool, - * context and context type. - * - * @param keyedObjectPool The pool the delegate context was checked out - * from. + * Create a new mutable delegating ldap context for the specified pool, context and + * context type. + * @param keyedObjectPool The pool the delegate context was checked out from. * @param delegateLdapContext The ldap context to delegate operations to. * @param dirContextType The type of context, used as a key for the pool. * @throws IllegalArgumentException if any of the arguments are null @@ -53,4 +51,5 @@ public class MutableDelegatingLdapContext extends DelegatingLdapContext { assertOpen(); getDelegateLdapContext().setRequestControls(requestControls); } + } diff --git a/core/src/main/java/org/springframework/ldap/pool/PoolExhaustedAction.java b/core/src/main/java/org/springframework/ldap/pool/PoolExhaustedAction.java index 6ec08f39..776907fb 100644 --- a/core/src/main/java/org/springframework/ldap/pool/PoolExhaustedAction.java +++ b/core/src/main/java/org/springframework/ldap/pool/PoolExhaustedAction.java @@ -4,9 +4,8 @@ package org.springframework.ldap.pool; * @author Mattias Hellborg Arthursson */ public enum PoolExhaustedAction { - FAIL((byte)0), - BLOCK((byte)1), - GROW((byte)2); + + FAIL((byte) 0), BLOCK((byte) 1), GROW((byte) 2); private final byte value; @@ -17,4 +16,5 @@ public enum PoolExhaustedAction { public byte getValue() { return value; } + } diff --git a/core/src/main/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactory.java b/core/src/main/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactory.java index 835802f9..c25835eb 100644 --- a/core/src/main/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactory.java +++ b/core/src/main/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactory.java @@ -37,14 +37,14 @@ import java.util.HashSet; import java.util.Set; /** - * Factory that creates {@link DirContext} instances for pooling via a - * configured {@link ContextSource}. The {@link DirContext}s are keyed based - * on if they are read only or read/write. The expected key type is the - * {@link DirContextType} enum. - * + * Factory that creates {@link DirContext} instances for pooling via a configured + * {@link ContextSource}. The {@link DirContext}s are keyed based on if they are read only + * or read/write. The expected key type is the {@link DirContextType} enum. + * *
    *
    - * Configuration: + * Configuration: + *
    * * * @@ -53,35 +53,37 @@ import java.util.Set; * * * - * + * * * * * * - * + * * * * *
    PropertyDescription
    contextSource The {@link ContextSource} to get {@link DirContext}s from - * for adding to the pool. The {@link ContextSource} to get {@link DirContext}s from for adding + * to the pool.Yesnull
    dirContextValidator The {@link DirContextValidator} to use to validate - * {@link DirContext}s. This is only required if the pool has validation of any - * kind turned on. The {@link DirContextValidator} to use to validate + * {@link DirContext}s. This is only required if the pool has validation of any kind + * turned on.Nonull
    - * - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu * @author Mattias Hellborg Arthursson */ class DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { + /** * Logger for this class and subclasses */ protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - private static final Set> DEFAULT_NONTRANSIENT_EXCEPTIONS - = new HashSet>(){{ - add(CommunicationException.class); - }}; + private static final Set> DEFAULT_NONTRANSIENT_EXCEPTIONS = new HashSet>() { + { + add(CommunicationException.class); + } + }; private ContextSource contextSource; @@ -101,8 +103,7 @@ class DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { } /** - * @param contextSource - * the contextSource to set + * @param contextSource the contextSource to set */ public void setContextSource(ContextSource contextSource) { if (contextSource == null) { @@ -120,13 +121,11 @@ class DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { } /** - * @param dirContextValidator - * the dirContextValidator to set + * @param dirContextValidator the dirContextValidator to set */ public void setDirContextValidator(DirContextValidator dirContextValidator) { if (dirContextValidator == null) { - throw new IllegalArgumentException( - "dirContextValidator may not be null"); + throw new IllegalArgumentException("dirContextValidator may not be null"); } this.dirContextValidator = dirContextValidator; @@ -137,8 +136,7 @@ class DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { */ public Object makeObject(Object key) throws Exception { Assert.notNull(this.contextSource, "ContextSource may not be null"); - Assert.isTrue(key instanceof DirContextType, - "key must be a DirContextType"); + Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); final DirContextType contextType = (DirContextType) key; if (this.logger.isDebugEnabled()) { @@ -146,103 +144,86 @@ class DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { } if (contextType == DirContextType.READ_WRITE) { - final DirContext readWriteContext = this.contextSource - .getReadWriteContext(); + final DirContext readWriteContext = this.contextSource.getReadWriteContext(); if (this.logger.isDebugEnabled()) { - this.logger.debug("Created new " + DirContextType.READ_WRITE - + " DirContext='" + readWriteContext + "'"); + this.logger + .debug("Created new " + DirContextType.READ_WRITE + " DirContext='" + readWriteContext + "'"); } return makeFailureAwareProxy(readWriteContext); - } else if (contextType == DirContextType.READ_ONLY) { + } + else if (contextType == DirContextType.READ_ONLY) { - final DirContext readOnlyContext = this.contextSource - .getReadOnlyContext(); + final DirContext readOnlyContext = this.contextSource.getReadOnlyContext(); if (this.logger.isDebugEnabled()) { - this.logger.debug("Created new " + DirContextType.READ_ONLY - + " DirContext='" + readOnlyContext + "'"); + this.logger.debug("Created new " + DirContextType.READ_ONLY + " DirContext='" + readOnlyContext + "'"); } return makeFailureAwareProxy(readOnlyContext); - } else { - throw new IllegalArgumentException("Unrecognized ContextType: " - + contextType); + } + else { + throw new IllegalArgumentException("Unrecognized ContextType: " + contextType); } } private Object makeFailureAwareProxy(DirContext readOnlyContext) { - return Proxy.newProxyInstance(DirContextProxy.class - .getClassLoader(), - new Class[]{ - LdapUtils.getActualTargetClass(readOnlyContext), - DirContextProxy.class, - FailureAwareContext.class}, + return Proxy.newProxyInstance(DirContextProxy.class.getClassLoader(), new Class[] { + LdapUtils.getActualTargetClass(readOnlyContext), DirContextProxy.class, FailureAwareContext.class }, new FailureAwareContextProxy(readOnlyContext)); } /** * @see org.apache.commons.pool.BaseKeyedPoolableObjectFactory#validateObject(java.lang.Object, - * java.lang.Object) + * java.lang.Object) */ public boolean validateObject(Object key, Object obj) { - Assert.notNull(this.dirContextValidator, - "DirContextValidator may not be null"); - Assert.isTrue(key instanceof DirContextType, - "key must be a DirContextType"); - Assert.isTrue(obj instanceof DirContext, - "The Object to validate must be of type '" + DirContext.class - + "'"); + Assert.notNull(this.dirContextValidator, "DirContextValidator may not be null"); + Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); + Assert.isTrue(obj instanceof DirContext, "The Object to validate must be of type '" + DirContext.class + "'"); try { final DirContextType contextType = (DirContextType) key; final DirContext dirContext = (DirContext) obj; - return this.dirContextValidator.validateDirContext(contextType, - dirContext); - } catch (Exception e) { - this.logger.warn("Failed to validate '" + obj - + "' due to an unexpected exception.", e); + return this.dirContextValidator.validateDirContext(contextType, dirContext); + } + catch (Exception e) { + this.logger.warn("Failed to validate '" + obj + "' due to an unexpected exception.", e); return false; } } - /** * @see org.apache.commons.pool.BaseKeyedPoolableObjectFactory#destroyObject(java.lang.Object, - * java.lang.Object) + * java.lang.Object) */ public void destroyObject(Object key, Object obj) throws Exception { - Assert.isTrue(obj instanceof DirContext, - "The Object to validate must be of type '" + DirContext.class - + "'"); + Assert.isTrue(obj instanceof DirContext, "The Object to validate must be of type '" + DirContext.class + "'"); try { final DirContext dirContext = (DirContext) obj; if (this.logger.isDebugEnabled()) { - this.logger.debug("Closing " + key + " DirContext='" - + dirContext + "'"); + this.logger.debug("Closing " + key + " DirContext='" + dirContext + "'"); } dirContext.close(); if (this.logger.isDebugEnabled()) { - this.logger.debug("Closed " + key + " DirContext='" - + dirContext + "'"); + this.logger.debug("Closed " + key + " DirContext='" + dirContext + "'"); } - } catch (Exception e) { - this.logger.warn( - "An exception occured while closing '" + obj + "'", e); + } + catch (Exception e) { + this.logger.warn("An exception occured while closing '" + obj + "'", e); } } /** - * Invocation handler that checks thrown exceptions against the configured {@link #nonTransientExceptions}, - * marking the Context as invalid on match. + * Invocation handler that checks thrown exceptions against the configured + * {@link #nonTransientExceptions}, marking the Context as invalid on match. * * @author Mattias Hellborg Arthursson * @since 2.0 */ - private class FailureAwareContextProxy implements - InvocationHandler { + private class FailureAwareContextProxy implements InvocationHandler { private DirContext target; @@ -257,13 +238,13 @@ class DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, * java.lang.reflect.Method, java.lang.Object[]) */ - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if (methodName.equals("getTargetContext")) { return target; - } else if (methodName.equals("hasFailed")) { + } + else if (methodName.equals("hasFailed")) { return hasFailed; } @@ -276,20 +257,22 @@ class DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { boolean nonTransientEncountered = false; for (Class clazz : nonTransientExceptions) { - if(clazz.isAssignableFrom(targetExceptionClass)) { - logger.info( - String.format("An %s - explicitly configured to be a non-transient exception - encountered; eagerly invalidating the target context.", - targetExceptionClass)); + if (clazz.isAssignableFrom(targetExceptionClass)) { + logger.info(String.format( + "An %s - explicitly configured to be a non-transient exception - encountered; eagerly invalidating the target context.", + targetExceptionClass)); nonTransientEncountered = true; break; } } - if(nonTransientEncountered) { + if (nonTransientEncountered) { hasFailed = true; - } else { + } + else { if (logger.isDebugEnabled()) { - logger.debug(String.format("An %s - not explicitly configured to be a non-transient exception - encountered; ignoring.", + logger.debug(String.format( + "An %s - not explicitly configured to be a non-transient exception - encountered; ignoring.", targetExceptionClass)); } } @@ -297,6 +280,7 @@ class DirContextPoolableObjectFactory extends BaseKeyedPoolableObjectFactory { throw targetException; } } + } } diff --git a/core/src/main/java/org/springframework/ldap/pool/factory/MutablePoolingContextSource.java b/core/src/main/java/org/springframework/ldap/pool/factory/MutablePoolingContextSource.java index 7a5b0ca8..f3577ddf 100644 --- a/core/src/main/java/org/springframework/ldap/pool/factory/MutablePoolingContextSource.java +++ b/core/src/main/java/org/springframework/ldap/pool/factory/MutablePoolingContextSource.java @@ -26,11 +26,11 @@ import org.springframework.ldap.pool.MutableDelegatingLdapContext; /** * A {@link PoolingContextSource} subclass that creates - * {@link MutableDelegatingLdapContext} instances. This enables the Spring LDAP - * pooling to be used in scenarios that require request controls to be set, such - * as paged results. + * {@link MutableDelegatingLdapContext} instances. This enables the Spring LDAP pooling to + * be used in scenarios that require request controls to be set, such as paged results. */ public class MutablePoolingContextSource extends PoolingContextSource { + protected DirContext getContext(DirContextType dirContextType) { final DirContext dirContext; try { @@ -46,4 +46,5 @@ public class MutablePoolingContextSource extends PoolingContextSource { return new DelegatingDirContext(this.keyedObjectPool, dirContext, dirContextType); } + } diff --git a/core/src/main/java/org/springframework/ldap/pool/factory/PoolingContextSource.java b/core/src/main/java/org/springframework/ldap/pool/factory/PoolingContextSource.java index c4f17448..f8160fc2 100644 --- a/core/src/main/java/org/springframework/ldap/pool/factory/PoolingContextSource.java +++ b/core/src/main/java/org/springframework/ldap/pool/factory/PoolingContextSource.java @@ -34,31 +34,31 @@ import java.util.Collection; /** * A {@link ContextSource} implementation that wraps an object pool and another - * {@link ContextSource}. {@link DirContext}s are retrieved from the pool which - * maintains them. - * - * + * {@link ContextSource}. {@link DirContext}s are retrieved from the pool which maintains + * them. + * + * *
    *
    * Configuration: * * - * + * + * + * + * * * * - * + * * * * * * - * + * * * * @@ -132,18 +132,17 @@ import java.util.Collection; * * * - * + * * * * *
    Property Description Required DefaultPropertyDescriptionRequiredDefault
    contextSource - * The {@link ContextSource} to get {@link DirContext}s from for adding to the - * pool.The {@link ContextSource} to get {@link DirContext}s from for adding + * to the pool.Yesnull
    dirContextValidator - * The {@link DirContextValidator} to use for validating {@link DirContext}s. - * Required if any of the test/validate options are enabled.The {@link DirContextValidator} to use for validating + * {@link DirContext}s. Required if any of the test/validate options are enabled.Nonull
    numTestsPerEvictionRun - * {@link GenericKeyedObjectPool#setNumTestsPerEvictionRun(int)}{@link GenericKeyedObjectPool#setNumTestsPerEvictionRun(int)}No3
    - * + * * @author Eric Dalquist */ -public class PoolingContextSource - extends DelegatingBaseLdapPathContextSourceSupport +public class PoolingContextSource extends DelegatingBaseLdapPathContextSourceSupport implements ContextSource, DisposableBean { + /** * The logger for this class and sub-classes */ @@ -154,8 +153,8 @@ public class PoolingContextSource private final DirContextPoolableObjectFactory dirContextPoolableObjectFactory; /** - * Creates a new pooling context source, setting up the DirContext object - * factory and generic keyed object pool. + * Creates a new pooling context source, setting up the DirContext object factory and + * generic keyed object pool. */ public PoolingContextSource() { this.dirContextPoolableObjectFactory = new DirContextPoolableObjectFactory(); @@ -364,43 +363,39 @@ public class PoolingContextSource } /** - * @param contextSource the contextSource to set - * Required + * @param contextSource the contextSource to set Required */ public void setContextSource(ContextSource contextSource) { this.dirContextPoolableObjectFactory.setContextSource(contextSource); } /** - * @param dirContextValidator the dirContextValidator to set - * Required + * @param dirContextValidator the dirContextValidator to set Required */ public void setDirContextValidator(DirContextValidator dirContextValidator) { this.dirContextPoolableObjectFactory.setDirContextValidator(dirContextValidator); } /** - * Configure the exception classes that are to be interpreted as no-transient with regards to eager - * context invalidation. If one of the configured exceptions (or subclasses of them) - * is thrown by any method on a pooled DirContext, that instance will immediately be marked - * as invalid without any additional testing (i.e. testOnReturn). - * This allows for more efficient management of dead connections. + * Configure the exception classes that are to be interpreted as no-transient with + * regards to eager context invalidation. If one of the configured exceptions (or + * subclasses of them) is thrown by any method on a pooled DirContext, that instance + * will immediately be marked as invalid without any additional testing (i.e. + * testOnReturn). This allows for more efficient management of dead connections. * Default is {@link javax.naming.CommunicationException}. - * - * @param nonTransientExceptions the exception classes that should be interpreted as non-transient - * with regards to eager invalidation. + * @param nonTransientExceptions the exception classes that should be interpreted as + * non-transient with regards to eager invalidation. * @since 2.0 */ public void setNonTransientExceptions(Collection> nonTransientExceptions) { this.dirContextPoolableObjectFactory.setNonTransientExceptions(nonTransientExceptions); } - // ***** DisposableBean interface methods *****// /* * (non-Javadoc) - * + * * @see org.springframework.beans.factory.DisposableBean#destroy() */ public void destroy() throws Exception { @@ -431,11 +426,10 @@ public class PoolingContextSource /** * Gets a DirContext of the specified type from the keyed object pool. - * * @param dirContextType The type of context to return. * @return A wrapped DirContext of the specified type. - * @throws DataAccessResourceFailureException If retrieving the object from - * the pool throws an exception + * @throws DataAccessResourceFailureException If retrieving the object from the pool + * throws an exception */ protected DirContext getContext(DirContextType dirContextType) { final DirContext dirContext; @@ -457,4 +451,5 @@ public class PoolingContextSource public DirContext getContext(String principal, String credentials) { throw new UnsupportedOperationException("Not supported for this implementation"); } + } diff --git a/core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java b/core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java index 81712cd6..6d11eac9 100644 --- a/core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java +++ b/core/src/main/java/org/springframework/ldap/pool/validation/DefaultDirContextValidator.java @@ -28,79 +28,78 @@ import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; /** - * Default {@link DirContext} validator that executes {@link DirContext#search(String, String, SearchControls)}. The - * name, filter and {@link SearchControls} are all configurable. There is no special handling for read only versus - * read write {@link DirContext}s. - * + * Default {@link DirContext} validator that executes + * {@link DirContext#search(String, String, SearchControls)}. The name, filter and + * {@link SearchControls} are all configurable. There is no special handling for read only + * versus read write {@link DirContext}s. + * *
    *
    * Configuration: * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * *
    PropertyDescriptionRequiredDefault
    base - * The name parameter to the search method. - * No""
    filter - * The filter parameter to the search method. - * No"objectclass=*"
    searchControls - * The {@link SearchControls} parameter to the search method. - * No - * {@link SearchControls#setCountLimit(long)} = 1
    - * {@link SearchControls#setReturningAttributes(String[])} = new String[] { "objectclass" }
    - * {@link SearchControls#setTimeLimit(int)} = 500 - *
    PropertyDescriptionRequiredDefault
    baseThe name parameter to the search method.No""
    filterThe filter parameter to the search method.No"objectclass=*"
    searchControlsThe {@link SearchControls} parameter to the search method.No{@link SearchControls#setCountLimit(long)} = 1
    + * {@link SearchControls#setReturningAttributes(String[])} = new String[] { "objectclass" + * }
    + * {@link SearchControls#setTimeLimit(int)} = 500
    - * + * * @author Eric Dalquist */ public class DefaultDirContextValidator implements DirContextValidator { + public static final String DEFAULT_FILTER = "objectclass=*"; + private static final int DEFAULT_TIME_LIMIT = 500; /** * Logger for this class and sub-classes */ protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - + private String base; + private String filter; + private SearchControls searchControls; - + /** - * Create the default validator, creates {@link SearchControls} with search scope OBJECT_SCOPE, - * a countLimit of 1, returningAttributes of objectclass and timeLimit of 500. - * The default base is an empty string and the default filter is objectclass=* + * Create the default validator, creates {@link SearchControls} with search scope + * OBJECT_SCOPE, a countLimit of 1, returningAttributes of objectclass + * and timeLimit of 500. The default base is an empty string and the default filter is + * objectclass=* */ public DefaultDirContextValidator() { - this(SearchControls.OBJECT_SCOPE); + this(SearchControls.OBJECT_SCOPE); } /** - * Create a validator with all the defaults of the default constructor, but with the search scope set to the - * referred value. - * - * @param searchScope The searchScope to be set in the default SearchControls + * Create a validator with all the defaults of the default constructor, but with the + * search scope set to the referred value. + * @param searchScope The searchScope to be set in the default + * SearchControls */ public DefaultDirContextValidator(int searchScope) { this.searchControls = new SearchControls(); @@ -113,25 +112,28 @@ public class DefaultDirContextValidator implements DirContextValidator { this.filter = DEFAULT_FILTER; } - + /** * @return the baseName */ public String getBase() { return this.base; } + /** * @param base the baseName to set */ public void setBase(String base) { this.base = base; } + /** * @return the filter */ public String getFilter() { return this.filter; } + /** * @param filter the filter to set */ @@ -139,15 +141,17 @@ public class DefaultDirContextValidator implements DirContextValidator { if (filter == null) { throw new IllegalArgumentException("filter may not be null"); } - + this.filter = filter; } + /** * @return the searchControls */ public SearchControls getSearchControls() { return this.searchControls; } + /** * @param searchControls the searchControls to set */ @@ -155,19 +159,19 @@ public class DefaultDirContextValidator implements DirContextValidator { if (searchControls == null) { throw new IllegalArgumentException("searchControls may not be null"); } - + this.searchControls = searchControls; } - /** - * @see DirContextValidator#validateDirContext(DirContextType, javax.naming.directory.DirContext) + * @see DirContextValidator#validateDirContext(DirContextType, + * javax.naming.directory.DirContext) */ public boolean validateDirContext(DirContextType contextType, DirContext dirContext) { Assert.notNull(contextType, "contextType may not be null"); Assert.notNull(dirContext, "dirContext may not be null"); - NamingEnumeration searchResults = null; + NamingEnumeration searchResults = null; try { searchResults = dirContext.search(this.base, this.filter, this.searchControls); @@ -183,9 +187,10 @@ public class DefaultDirContextValidator implements DirContextValidator { } finally { if (searchResults != null) { - try { + try { searchResults.close(); - } catch (NamingException ignored) { + } + catch (NamingException ignored) { } } } @@ -193,4 +198,5 @@ public class DefaultDirContextValidator implements DirContextValidator { this.logger.debug("DirContext '{}' failed validation.", dirContext); return false; } + } diff --git a/core/src/main/java/org/springframework/ldap/pool/validation/DirContextValidator.java b/core/src/main/java/org/springframework/ldap/pool/validation/DirContextValidator.java index 904265b7..a4e37ecf 100644 --- a/core/src/main/java/org/springframework/ldap/pool/validation/DirContextValidator.java +++ b/core/src/main/java/org/springframework/ldap/pool/validation/DirContextValidator.java @@ -23,17 +23,22 @@ import org.springframework.ldap.pool.DirContextType; /** * A validator for {@link DirContext}s. - * + * * @author Eric Dalquist */ public interface DirContextValidator { + /** - * Validates the {@link DirContext}. A valid {@link DirContext} should be able - * to answer queries and if applicable write to the directory. - * - * @param contextType The type of the {@link DirContext}, refers to if {@link ContextSource#getReadOnlyContext()} or {@link ContextSource#getReadWriteContext()} was called to create the {@link DirContext} + * Validates the {@link DirContext}. A valid {@link DirContext} should be able to + * answer queries and if applicable write to the directory. + * @param contextType The type of the {@link DirContext}, refers to if + * {@link ContextSource#getReadOnlyContext()} or + * {@link ContextSource#getReadWriteContext()} was called to create the + * {@link DirContext} * @param dirContext The {@link DirContext} to validate. - * @return true if the {@link DirContext} operated correctly during validation. + * @return true if the {@link DirContext} operated correctly during + * validation. */ boolean validateDirContext(DirContextType contextType, DirContext dirContext); + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/DelegatingContext.java b/core/src/main/java/org/springframework/ldap/pool2/DelegatingContext.java index 7160945d..676fc68d 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/DelegatingContext.java +++ b/core/src/main/java/org/springframework/ldap/pool2/DelegatingContext.java @@ -15,7 +15,6 @@ */ package org.springframework.ldap.pool2; - import org.apache.commons.pool2.KeyedObjectPool; import org.springframework.ldap.pool2.factory.PooledContextSource; import org.springframework.util.Assert; @@ -32,20 +31,22 @@ import java.util.Hashtable; * @author Eric Dalquist */ public class DelegatingContext implements Context { - private KeyedObjectPool keyedObjectPool; - private Context delegateContext; - private final DirContextType dirContextType; + private KeyedObjectPool keyedObjectPool; + + private Context delegateContext; + + private final DirContextType dirContextType; /** * Create a new delegating context for the specified pool, context and context type. - * * @param keyedObjectPool The pool the delegate context was checked out from. * @param delegateContext The context to delegate operations to. * @param dirContextType The type of context, used as a key for the pool. * @throws IllegalArgumentException if any of the arguments are null */ - public DelegatingContext(KeyedObjectPool keyedObjectPool, Context delegateContext, DirContextType dirContextType) { + public DelegatingContext(KeyedObjectPool keyedObjectPool, Context delegateContext, + DirContextType dirContextType) { Assert.notNull(keyedObjectPool, "keyedObjectPool may not be null"); Assert.notNull(delegateContext, "delegateContext may not be null"); Assert.notNull(dirContextType, "dirContextType may not be null"); @@ -55,8 +56,7 @@ public class DelegatingContext implements Context { this.dirContextType = dirContextType; } - - //***** Helper Methods *****// + // ***** Helper Methods *****// /** * @return The direct delegate for this context proxy @@ -67,14 +67,13 @@ public class DelegatingContext implements Context { /** * Recursivley inspect delegates until a non-delegating context is found. - * * @return The innermost (real) Context that is being delegated to. */ public Context getInnermostDelegateContext() { final Context delegateContext = this.getDelegateContext(); if (delegateContext instanceof DelegatingContext) { - return ((DelegatingContext)delegateContext).getInnermostDelegateContext(); + return ((DelegatingContext) delegateContext).getInnermostDelegateContext(); } return delegateContext; @@ -89,8 +88,7 @@ public class DelegatingContext implements Context { } } - - //***** Object methods *****// + // ***** Object methods *****// /** * @see Object#equals(Object) @@ -104,9 +102,9 @@ public class DelegatingContext implements Context { } final Context thisContext = this.getInnermostDelegateContext(); - Context otherContext = (Context)obj; + Context otherContext = (Context) obj; if (otherContext instanceof DelegatingContext) { - otherContext = ((DelegatingContext)otherContext).getInnermostDelegateContext(); + otherContext = ((DelegatingContext) otherContext).getInnermostDelegateContext(); } return thisContext == otherContext || (thisContext != null && thisContext.equals(otherContext)); @@ -128,8 +126,7 @@ public class DelegatingContext implements Context { return (context != null ? context.toString() : "Context is closed"); } - - //***** Context Interface Delegates *****// + // ***** Context Interface Delegates *****// /** * @see Context#addToEnvironment(String, Object) @@ -163,23 +160,24 @@ public class DelegatingContext implements Context { return; } - //Get a local reference so the member can be nulled earlier + // Get a local reference so the member can be nulled earlier this.delegateContext = null; - //Return the object to the Pool and then null the pool reference + // Return the object to the Pool and then null the pool reference try { boolean valid = true; if (context instanceof FailureAwareContext) { FailureAwareContext failureAwareContext = (FailureAwareContext) context; - if(failureAwareContext.hasFailed()) { + if (failureAwareContext.hasFailed()) { valid = false; } } if (valid) { this.keyedObjectPool.returnObject(this.dirContextType, context); - } else { + } + else { this.keyedObjectPool.invalidateObject(this.dirContextType, context); } } @@ -387,4 +385,5 @@ public class DelegatingContext implements Context { this.assertOpen(); this.getDelegateContext().unbind(name); } + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/DelegatingDirContext.java b/core/src/main/java/org/springframework/ldap/pool2/DelegatingDirContext.java index 87198d83..bcbe702e 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/DelegatingDirContext.java +++ b/core/src/main/java/org/springframework/ldap/pool2/DelegatingDirContext.java @@ -27,37 +27,36 @@ import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.*; - /** - * Used by {@link PooledContextSource} to wrap a {@link DirContext}, delegating most methods - * to the underlying context. This class extends {@link DelegatingContext} which handles returning - * the context to the pool on a call to {@link #close()} + * Used by {@link PooledContextSource} to wrap a {@link DirContext}, delegating most + * methods to the underlying context. This class extends {@link DelegatingContext} which + * handles returning the context to the pool on a call to {@link #close()} * * @since 2.0 * @author Eric Dalquist * @author Anindya Chatterjee */ public class DelegatingDirContext extends DelegatingContext implements DirContext, DirContextProxy { + private DirContext delegateDirContext; /** - * Create a new delegating dir context for the specified pool, context and context type. - * + * Create a new delegating dir context for the specified pool, context and context + * type. * @param keyedObjectPool The pool the delegate context was checked out from. * @param delegateDirContext The dir context to delegate operations to. * @param dirContextType The type of context, used as a key for the pool. * @throws IllegalArgumentException if any of the arguments are null */ - public DelegatingDirContext(KeyedObjectPool keyedObjectPool, - DirContext delegateDirContext, DirContextType dirContextType) { + public DelegatingDirContext(KeyedObjectPool keyedObjectPool, DirContext delegateDirContext, + DirContextType dirContextType) { super(keyedObjectPool, delegateDirContext, dirContextType); Assert.notNull(delegateDirContext, "delegateDirContext may not be null"); this.delegateDirContext = delegateDirContext; } - - //***** Helper Methods *****// + // ***** Helper Methods *****// /** * @return The direct delegate for this dir context proxy @@ -72,14 +71,13 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex /** * Recursivley inspect delegates until a non-delegating dir context is found. - * * @return The innermost (real) DirContext that is being delegated to. */ public DirContext getInnermostDelegateDirContext() { final DirContext delegateDirContext = this.getDelegateDirContext(); if (delegateDirContext instanceof DelegatingDirContext) { - return ((DelegatingDirContext)delegateDirContext).getInnermostDelegateDirContext(); + return ((DelegatingDirContext) delegateDirContext).getInnermostDelegateDirContext(); } return delegateDirContext; @@ -93,8 +91,7 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex super.assertOpen(); } - - //***** Object methods *****// + // ***** Object methods *****// /** * @see Object#equals(Object) @@ -108,9 +105,9 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex } final DirContext thisDirContext = this.getInnermostDelegateDirContext(); - DirContext otherDirContext = (DirContext)obj; + DirContext otherDirContext = (DirContext) obj; if (otherDirContext instanceof DelegatingDirContext) { - otherDirContext = ((DelegatingDirContext)otherDirContext).getInnermostDelegateDirContext(); + otherDirContext = ((DelegatingDirContext) otherDirContext).getInnermostDelegateDirContext(); } return thisDirContext == otherDirContext || (thisDirContext != null && thisDirContext.equals(otherDirContext)); @@ -132,18 +129,18 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex return (context != null ? context.toString() : "DirContext is closed"); } + // ***** DirContextProxy Interface Methods *****// - //***** DirContextProxy Interface Methods *****// - - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.springframework.ldap.core.DirContextProxy#getTargetContext() */ public DirContext getTargetContext() { return this.getInnermostDelegateDirContext(); } - - //***** DirContext Interface Delegates *****// + // ***** DirContext Interface Delegates *****// /** * @see DirContext#bind(Name, Object, Attributes) @@ -286,7 +283,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex /** * @see DirContext#search(Name, Attributes, String[]) */ - public NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { + public NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) + throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, matchingAttributes, attributesToReturn); } @@ -302,7 +300,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex /** * @see DirContext#search(Name, String, Object[], SearchControls) */ - public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { + public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, + SearchControls cons) throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, filterExpr, filterArgs, cons); } @@ -310,7 +309,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex /** * @see DirContext#search(Name, String, SearchControls) */ - public NamingEnumeration search(Name name, String filter, SearchControls cons) throws NamingException { + public NamingEnumeration search(Name name, String filter, SearchControls cons) + throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, filter, cons); } @@ -318,7 +318,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex /** * @see DirContext#search(String, Attributes, String[]) */ - public NamingEnumeration search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { + public NamingEnumeration search(String name, Attributes matchingAttributes, + String[] attributesToReturn) throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, matchingAttributes, attributesToReturn); } @@ -334,7 +335,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex /** * @see DirContext#search(String, String, Object[], SearchControls) */ - public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { + public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, + SearchControls cons) throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, filterExpr, filterArgs, cons); } @@ -342,7 +344,8 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex /** * @see DirContext#search(String, String, SearchControls) */ - public NamingEnumeration search(String name, String filter, SearchControls cons) throws NamingException { + public NamingEnumeration search(String name, String filter, SearchControls cons) + throws NamingException { this.assertOpen(); return this.getDelegateDirContext().search(name, filter, cons); } @@ -358,4 +361,5 @@ public class DelegatingDirContext extends DelegatingContext implements DirContex super.close(); this.delegateDirContext = null; } + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/DelegatingLdapContext.java b/core/src/main/java/org/springframework/ldap/pool2/DelegatingLdapContext.java index f08b8f22..889836cb 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/DelegatingLdapContext.java +++ b/core/src/main/java/org/springframework/ldap/pool2/DelegatingLdapContext.java @@ -28,35 +28,35 @@ import javax.naming.ldap.ExtendedResponse; import javax.naming.ldap.LdapContext; /** - * Used by {@link PooledContextSource} to wrap a {@link LdapContext}, delegating most methods - * to the underlying context. This class extends {@link DelegatingDirContext} which handles returning - * the context to the pool on a call to {@link #close()} + * Used by {@link PooledContextSource} to wrap a {@link LdapContext}, delegating most + * methods to the underlying context. This class extends {@link DelegatingDirContext} + * which handles returning the context to the pool on a call to {@link #close()} * * @since 2.0 * @author Eric Dalquist * @author Anindya Chatterjee */ public class DelegatingLdapContext extends DelegatingDirContext implements LdapContext { + private LdapContext delegateLdapContext; /** - * Create a new delegating ldap context for the specified pool, context and context type. - * + * Create a new delegating ldap context for the specified pool, context and context + * type. * @param keyedObjectPool The pool the delegate context was checked out from. * @param delegateLdapContext The ldap context to delegate operations to. * @param dirContextType The type of context, used as a key for the pool. * @throws IllegalArgumentException if any of the arguments are null */ - public DelegatingLdapContext(KeyedObjectPool keyedObjectPool, - LdapContext delegateLdapContext, DirContextType dirContextType) { + public DelegatingLdapContext(KeyedObjectPool keyedObjectPool, LdapContext delegateLdapContext, + DirContextType dirContextType) { super(keyedObjectPool, delegateLdapContext, dirContextType); Assert.notNull(delegateLdapContext, "delegateLdapContext may not be null"); this.delegateLdapContext = delegateLdapContext; } - - //***** Helper Methods *****// + // ***** Helper Methods *****// /** * @return The direct delegate for this ldap context proxy @@ -72,14 +72,13 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC /** * Recursivley inspect delegates until a non-delegating ldap context is found. - * * @return The innermost (real) DirContext that is being delegated to. */ public LdapContext getInnermostDelegateLdapContext() { final LdapContext delegateLdapContext = this.getDelegateLdapContext(); if (delegateLdapContext instanceof DelegatingLdapContext) { - return ((DelegatingLdapContext)delegateLdapContext).getInnermostDelegateLdapContext(); + return ((DelegatingLdapContext) delegateLdapContext).getInnermostDelegateLdapContext(); } return delegateLdapContext; @@ -93,8 +92,7 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC super.assertOpen(); } - - //***** Object methods *****// + // ***** Object methods *****// /** * @see Object#equals(Object) @@ -108,12 +106,13 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC } final LdapContext thisLdapContext = this.getInnermostDelegateLdapContext(); - LdapContext otherLdapContext = (LdapContext)obj; + LdapContext otherLdapContext = (LdapContext) obj; if (otherLdapContext instanceof DelegatingLdapContext) { - otherLdapContext = ((DelegatingLdapContext)otherLdapContext).getInnermostDelegateLdapContext(); + otherLdapContext = ((DelegatingLdapContext) otherLdapContext).getInnermostDelegateLdapContext(); } - return thisLdapContext == otherLdapContext || (thisLdapContext != null && thisLdapContext.equals(otherLdapContext)); + return thisLdapContext == otherLdapContext + || (thisLdapContext != null && thisLdapContext.equals(otherLdapContext)); } /** @@ -132,8 +131,7 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC return (context != null ? context.toString() : "LdapContext is closed"); } - - //***** LdapContext Interface Delegates *****// + // ***** LdapContext Interface Delegates *****// /** * @see LdapContext#extendedOperation(ExtendedRequest) @@ -199,4 +197,5 @@ public class DelegatingLdapContext extends DelegatingDirContext implements LdapC super.close(); this.delegateLdapContext = null; } + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/DirContextType.java b/core/src/main/java/org/springframework/ldap/pool2/DirContextType.java index 7f82767a..dc865b51 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/DirContextType.java +++ b/core/src/main/java/org/springframework/ldap/pool2/DirContextType.java @@ -20,14 +20,14 @@ import org.springframework.ldap.core.ContextSource; import javax.naming.directory.DirContext; - /** * An enum representing the two types of {@link DirContext}s that can be returned by a * {@link ContextSource}. - * + * * @author Eric Dalquist */ public final class DirContextType { + private String name; private DirContextType(String name) { @@ -37,14 +37,17 @@ public final class DirContextType { public String toString() { return name; } - + /** - * The type of {@link DirContext} returned by {@link ContextSource#getReadOnlyContext()} + * The type of {@link DirContext} returned by + * {@link ContextSource#getReadOnlyContext()} */ public static final DirContextType READ_ONLY = new DirContextType("READ_ONLY"); - + /** - * The type of {@link DirContext} returned by {@link ContextSource#getReadWriteContext()} + * The type of {@link DirContext} returned by + * {@link ContextSource#getReadWriteContext()} */ public static final DirContextType READ_WRITE = new DirContextType("READ_WRITE"); + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/FailureAwareContext.java b/core/src/main/java/org/springframework/ldap/pool2/FailureAwareContext.java index 748d864d..1c45ff75 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/FailureAwareContext.java +++ b/core/src/main/java/org/springframework/ldap/pool2/FailureAwareContext.java @@ -20,5 +20,7 @@ package org.springframework.ldap.pool2; * @author Mattias Hellborg Arthursson */ public interface FailureAwareContext { + boolean hasFailed(); + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/MutableDelegatingLdapContext.java b/core/src/main/java/org/springframework/ldap/pool2/MutableDelegatingLdapContext.java index 63820f72..b436d619 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/MutableDelegatingLdapContext.java +++ b/core/src/main/java/org/springframework/ldap/pool2/MutableDelegatingLdapContext.java @@ -24,11 +24,11 @@ import javax.naming.ldap.Control; import javax.naming.ldap.LdapContext; /** - * Used by {@link MutablePooledContextSource} to wrap a {@link LdapContext}, - * delegating most methods to the underlying context. This class extends - * {@link DelegatingLdapContext}, allowing request controls to be set on the - * wrapped ldap context. This enables the Spring LDAP pooling to be used for - * scenarios such as paged results. + * Used by {@link MutablePooledContextSource} to wrap a {@link LdapContext}, delegating + * most methods to the underlying context. This class extends + * {@link DelegatingLdapContext}, allowing request controls to be set on the wrapped ldap + * context. This enables the Spring LDAP pooling to be used for scenarios such as paged + * results. * * @since 2.0 * @author Ulrik Sandberg @@ -37,11 +37,9 @@ import javax.naming.ldap.LdapContext; public class MutableDelegatingLdapContext extends DelegatingLdapContext { /** - * Create a new mutable delegating ldap context for the specified pool, - * context and context type. - * - * @param keyedObjectPool The pool the delegate context was checked out - * from. + * Create a new mutable delegating ldap context for the specified pool, context and + * context type. + * @param keyedObjectPool The pool the delegate context was checked out from. * @param delegateLdapContext The ldap context to delegate operations to. * @param dirContextType The type of context, used as a key for the pool. * @throws IllegalArgumentException if any of the arguments are null @@ -55,4 +53,5 @@ public class MutableDelegatingLdapContext extends DelegatingLdapContext { assertOpen(); getDelegateLdapContext().setRequestControls(requestControls); } + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/factory/DirContextPoolableObjectFactory.java b/core/src/main/java/org/springframework/ldap/pool2/factory/DirContextPoolableObjectFactory.java index 93b5d1a5..a7bcb269 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/factory/DirContextPoolableObjectFactory.java +++ b/core/src/main/java/org/springframework/ldap/pool2/factory/DirContextPoolableObjectFactory.java @@ -39,14 +39,15 @@ import java.util.HashSet; import java.util.Set; /** - * Factory that creates {@link DirContext} instances for pooling via a - * configured {@link ContextSource}. The {@link DirContext}s are keyed based - * on if they are read only or read/write. The expected key type is the + * Factory that creates {@link DirContext} instances for pooling via a configured + * {@link ContextSource}. The {@link DirContext}s are keyed based on if they are read only + * or read/write. The expected key type is the * {@link org.springframework.ldap.pool2.DirContextType} enum. * *
    *
    - * Configuration: + * Configuration: + *
    * * * @@ -55,35 +56,35 @@ import java.util.Set; * * * - * + * * * * * * - * + * * * * *
    PropertyDescription
    contextSource The {@link ContextSource} to get {@link DirContext}s from - * for adding to the pool. The {@link ContextSource} to get {@link DirContext}s from for adding + * to the pool.Yesnull
    dirContextValidator The {@link DirContextValidator} to use to validate - * {@link DirContext}s. This is only required if the pool has validation of any - * kind turned on. The {@link DirContextValidator} to use to validate + * {@link DirContext}s. This is only required if the pool has validation of any kind + * turned on.Nonull
    * * @since 2.0 - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu * @author Mattias Hellborg Arthursson * @author Anindya Chatterjee */ -class DirContextPooledObjectFactory extends BaseKeyedPooledObjectFactory { +class DirContextPooledObjectFactory extends BaseKeyedPooledObjectFactory { + /** * Logger for this class and subclasses */ protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - private static final Set> DEFAULT_NONTRANSIENT_EXCEPTIONS - = new HashSet>(); + private static final Set> DEFAULT_NONTRANSIENT_EXCEPTIONS = new HashSet>(); static { DEFAULT_NONTRANSIENT_EXCEPTIONS.add(CommunicationException.class); @@ -107,8 +108,7 @@ class DirContextPooledObjectFactory extends BaseKeyedPooledObjectFactory[]{ - LdapUtils.getActualTargetClass(readOnlyContext), - DirContextProxy.class, - FailureAwareContext.class}, + return Proxy.newProxyInstance(DirContextProxy.class.getClassLoader(), new Class[] { + LdapUtils.getActualTargetClass(readOnlyContext), DirContextProxy.class, FailureAwareContext.class }, new FailureAwareContextProxy(readOnlyContext)); } /** * @see BaseKeyedPooledObjectFactory#validateObject(Object, PooledObject) * - * */ + */ @Override public boolean validateObject(Object key, PooledObject pooledObject) { - Assert.notNull(this.dirContextValidator, - "DirContextValidator may not be null"); - Assert.isTrue(key instanceof DirContextType, - "key must be a DirContextType"); - Assert.notNull(pooledObject, - "The Object to validate must not be null"); + Assert.notNull(this.dirContextValidator, "DirContextValidator may not be null"); + Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); + Assert.notNull(pooledObject, "The Object to validate must not be null"); Assert.isTrue(pooledObject.getObject() instanceof DirContext, - "The Object to validate must be of type '" + DirContext.class - + "'"); + "The Object to validate must be of type '" + DirContext.class + "'"); try { final DirContextType contextType = (DirContextType) key; final DirContext dirContext = (DirContext) pooledObject.getObject(); - return this.dirContextValidator.validateDirContext(contextType, - dirContext); - } catch (Exception e) { - this.logger.warn("Failed to validate '" + pooledObject.getObject() - + "' due to an unexpected exception.", e); + return this.dirContextValidator.validateDirContext(contextType, dirContext); + } + catch (Exception e) { + this.logger.warn("Failed to validate '" + pooledObject.getObject() + "' due to an unexpected exception.", + e); return false; } } @@ -179,41 +169,36 @@ class DirContextPooledObjectFactory extends BaseKeyedPooledObjectFactory pooledObject) throws Exception { - Assert.notNull(pooledObject, - "The Object to destroy must not be null"); + Assert.notNull(pooledObject, "The Object to destroy must not be null"); Assert.isTrue(pooledObject.getObject() instanceof DirContext, - "The Object to destroy must be of type '" + DirContext.class - + "'"); + "The Object to destroy must be of type '" + DirContext.class + "'"); try { final DirContext dirContext = (DirContext) pooledObject.getObject(); if (this.logger.isDebugEnabled()) { - this.logger.debug("Closing " + key + " DirContext='" - + dirContext + "'"); + this.logger.debug("Closing " + key + " DirContext='" + dirContext + "'"); } dirContext.close(); if (this.logger.isDebugEnabled()) { - this.logger.debug("Closed " + key + " DirContext='" - + dirContext + "'"); + this.logger.debug("Closed " + key + " DirContext='" + dirContext + "'"); } - } catch (Exception e) { - this.logger.warn( - "An exception occured while closing '" + pooledObject.getObject() + "'", e); + } + catch (Exception e) { + this.logger.warn("An exception occured while closing '" + pooledObject.getObject() + "'", e); } } /** * @see BaseKeyedPooledObjectFactory#create(Object) * - * */ + */ @Override public Object create(Object key) throws Exception { Assert.notNull(this.contextSource, "ContextSource may not be null"); - Assert.isTrue(key instanceof DirContextType, - "key must be a DirContextType"); + Assert.isTrue(key instanceof DirContextType, "key must be a DirContextType"); final DirContextType contextType = (DirContextType) key; if (this.logger.isDebugEnabled()) { @@ -221,50 +206,47 @@ class DirContextPooledObjectFactory extends BaseKeyedPooledObjectFactory wrap(Object value) { return new DefaultPooledObject(value); } /** - * Invocation handler that checks thrown exceptions against the configured {@link #nonTransientExceptions}, - * marking the Context as invalid on match. + * Invocation handler that checks thrown exceptions against the configured + * {@link #nonTransientExceptions}, marking the Context as invalid on match. * * @author Mattias Hellborg Arthursson * @since 2.0 */ - private class FailureAwareContextProxy implements - InvocationHandler { + private class FailureAwareContextProxy implements InvocationHandler { private DirContext target; @@ -279,13 +261,13 @@ class DirContextPooledObjectFactory extends BaseKeyedPooledObjectFactory clazz : nonTransientExceptions) { - if(clazz.isAssignableFrom(targetExceptionClass)) { + if (clazz.isAssignableFrom(targetExceptionClass)) { if (logger.isDebugEnabled()) { - logger.debug( - String.format("A %s - explicitly configured to be a non-transient exception - encountered; eagerly invalidating the target context.", - targetExceptionClass)); + logger.debug(String.format( + "A %s - explicitly configured to be a non-transient exception - encountered; eagerly invalidating the target context.", + targetExceptionClass)); } nonTransientEncountered = true; break; } } - if(nonTransientEncountered) { + if (nonTransientEncountered) { hasFailed = true; - } else { + } + else { if (logger.isDebugEnabled()) { - logger.debug(String.format("A %s - not explicitly configured to be a non-transient exception - encountered; ignoring.", + logger.debug(String.format( + "A %s - not explicitly configured to be a non-transient exception - encountered; ignoring.", targetExceptionClass)); } } @@ -321,5 +305,7 @@ class DirContextPooledObjectFactory extends BaseKeyedPooledObjectFactory + * NOTE: This implementation is based on apache commons-pool2.
    *
    * Configuration: * * - * + * + * + * + * * * * - * + * * * * * * - * + * * * * @@ -75,34 +76,34 @@ import java.util.Collection; * @author Eric Dalquist * @author Anindya Chatterjee */ -public class PooledContextSource - extends DelegatingBaseLdapPathContextSourceSupport +public class PooledContextSource extends DelegatingBaseLdapPathContextSourceSupport implements ContextSource, DisposableBean { + /** * The logger for this class and sub-classes */ protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - protected final GenericKeyedObjectPool keyedObjectPool; + protected final GenericKeyedObjectPool keyedObjectPool; private final DirContextPooledObjectFactory dirContextPooledObjectFactory; private PoolConfig poolConfig; /** - * Creates a new pooling context source, setting up the DirContext object - * factory and generic keyed object pool. + * Creates a new pooling context source, setting up the DirContext object factory and + * generic keyed object pool. */ public PooledContextSource(PoolConfig poolConfig) { this.dirContextPooledObjectFactory = new DirContextPooledObjectFactory(); if (poolConfig != null) { this.poolConfig = poolConfig; GenericKeyedObjectPoolConfig objectPoolConfig = getConfig(poolConfig); - this.keyedObjectPool = - new GenericKeyedObjectPool(this.dirContextPooledObjectFactory, objectPoolConfig); - } else { - this.keyedObjectPool = - new GenericKeyedObjectPool(this.dirContextPooledObjectFactory); + this.keyedObjectPool = new GenericKeyedObjectPool(this.dirContextPooledObjectFactory, + objectPoolConfig); + } + else { + this.keyedObjectPool = new GenericKeyedObjectPool(this.dirContextPooledObjectFactory); } } @@ -110,56 +111,56 @@ public class PooledContextSource /** * @return the poolConfig - * */ + */ public PoolConfig getPoolConfig() { return poolConfig; } /** * @see GenericKeyedObjectPool#getNumIdle() - * */ + */ public int getNumIdle() { return this.keyedObjectPool.getNumIdle(); } /** * @see GenericKeyedObjectPool#getNumIdle(Object) - * */ + */ public int getNumIdleRead() { return this.keyedObjectPool.getNumIdle(DirContextType.READ_ONLY); } /** * @see GenericKeyedObjectPool#getNumIdle(Object) - * */ + */ public int getNumIdleWrite() { return this.keyedObjectPool.getNumIdle(DirContextType.READ_WRITE); } /** * @see GenericKeyedObjectPool#getNumActive() - * */ + */ public int getNumActive() { return this.keyedObjectPool.getNumActive(); } /** * @see GenericKeyedObjectPool#getNumActive(Object) - * */ + */ public int getNumActiveRead() { return this.keyedObjectPool.getNumActive(DirContextType.READ_ONLY); } /** * @see GenericKeyedObjectPool#getNumActive(Object) - * */ + */ public int getNumActiveWrite() { return this.keyedObjectPool.getNumActive(DirContextType.READ_WRITE); } /** * @see GenericKeyedObjectPool#getNumWaiters() - * */ + */ public int getNumWaiters() { return this.keyedObjectPool.getNumWaiters(); } @@ -181,38 +182,34 @@ public class PooledContextSource } /** - * @param contextSource the contextSource to set - * Required + * @param contextSource the contextSource to set Required */ public void setContextSource(ContextSource contextSource) { this.dirContextPooledObjectFactory.setContextSource(contextSource); } /** - * @param dirContextValidator the dirContextValidator to set - * Required + * @param dirContextValidator the dirContextValidator to set Required */ public void setDirContextValidator(DirContextValidator dirContextValidator) { this.dirContextPooledObjectFactory.setDirContextValidator(dirContextValidator); } /** - * Configure the exception classes that are to be interpreted as no-transient with regards to eager - * context invalidation. If one of the configured exceptions (or subclasses of them) - * is thrown by any method on a pooled DirContext, that instance will immediately be marked - * as invalid without any additional testing (i.e. testOnReturn). - * This allows for more efficient management of dead connections. + * Configure the exception classes that are to be interpreted as no-transient with + * regards to eager context invalidation. If one of the configured exceptions (or + * subclasses of them) is thrown by any method on a pooled DirContext, that instance + * will immediately be marked as invalid without any additional testing (i.e. + * testOnReturn). This allows for more efficient management of dead connections. * Default is {@link javax.naming.CommunicationException}. - * - * @param nonTransientExceptions the exception classes that should be interpreted as non-transient - * with regards to eager invalidation. + * @param nonTransientExceptions the exception classes that should be interpreted as + * non-transient with regards to eager invalidation. * @since 2.0 */ public void setNonTransientExceptions(Collection> nonTransientExceptions) { this.dirContextPooledObjectFactory.setNonTransientExceptions(nonTransientExceptions); } - // ***** DisposableBean interface methods *****// /* @@ -248,11 +245,10 @@ public class PooledContextSource /** * Gets a DirContext of the specified type from the keyed object pool. - * * @param dirContextType The type of context to return. * @return A wrapped DirContext of the specified type. - * @throws DataAccessResourceFailureException If retrieving the object from - * the pool throws an exception + * @throws DataAccessResourceFailureException If retrieving the object from the pool + * throws an exception */ protected DirContext getContext(DirContextType dirContextType) { final DirContext dirContext; @@ -307,4 +303,5 @@ public class PooledContextSource return objectPoolConfig; } + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java b/core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java index 684c902b..15bde89d 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java +++ b/core/src/main/java/org/springframework/ldap/pool2/validation/DefaultDirContextValidator.java @@ -28,79 +28,78 @@ import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; /** - * Default {@link DirContext} validator that executes {@link DirContext#search(String, String, SearchControls)}. The - * name, filter and {@link SearchControls} are all configurable. There is no special handling for read only versus - * read write {@link DirContext}s. - * + * Default {@link DirContext} validator that executes + * {@link DirContext#search(String, String, SearchControls)}. The name, filter and + * {@link SearchControls} are all configurable. There is no special handling for read only + * versus read write {@link DirContext}s. + * *
    *
    * Configuration: *
    Property Description Required DefaultPropertyDescriptionRequiredDefault
    contextSource - * The {@link ContextSource} to get {@link DirContext}s from for adding to the - * pool.The {@link ContextSource} to get {@link DirContext}s from for adding + * to the pool.Yesnull
    dirContextValidator - * The {@link org.springframework.ldap.pool2.validation.DirContextValidator} to use for validating {@link DirContext}s. - * Required if any of the test/validate options are enabled.The + * {@link org.springframework.ldap.pool2.validation.DirContextValidator} to use for + * validating {@link DirContext}s. Required if any of the test/validate options are + * enabled.Nonull
    - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * *
    PropertyDescriptionRequiredDefault
    base - * The name parameter to the search method. - * No""
    filter - * The filter parameter to the search method. - * No"objectclass=*"
    searchControls - * The {@link SearchControls} parameter to the search method. - * No - * {@link SearchControls#setCountLimit(long)} = 1
    - * {@link SearchControls#setReturningAttributes(String[])} = new String[] { "objectclass" }
    - * {@link SearchControls#setTimeLimit(int)} = 500 - *
    PropertyDescriptionRequiredDefault
    baseThe name parameter to the search method.No""
    filterThe filter parameter to the search method.No"objectclass=*"
    searchControlsThe {@link SearchControls} parameter to the search method.No{@link SearchControls#setCountLimit(long)} = 1
    + * {@link SearchControls#setReturningAttributes(String[])} = new String[] { "objectclass" + * }
    + * {@link SearchControls#setTimeLimit(int)} = 500
    - * + * * @author Eric Dalquist */ public class DefaultDirContextValidator implements DirContextValidator { + public static final String DEFAULT_FILTER = "objectclass=*"; + private static final int DEFAULT_TIME_LIMIT = 500; /** * Logger for this class and sub-classes */ protected final Logger logger = LoggerFactory.getLogger(this.getClass()); - + private String base; + private String filter; + private SearchControls searchControls; - + /** - * Create the default validator, creates {@link SearchControls} with search scope OBJECT_SCOPE, - * a countLimit of 1, returningAttributes of objectclass and timeLimit of 500. - * The default base is an empty string and the default filter is objectclass=* + * Create the default validator, creates {@link SearchControls} with search scope + * OBJECT_SCOPE, a countLimit of 1, returningAttributes of objectclass + * and timeLimit of 500. The default base is an empty string and the default filter is + * objectclass=* */ public DefaultDirContextValidator() { - this(SearchControls.OBJECT_SCOPE); + this(SearchControls.OBJECT_SCOPE); } /** - * Create a validator with all the defaults of the default constructor, but with the search scope set to the - * referred value. - * - * @param searchScope The searchScope to be set in the default SearchControls + * Create a validator with all the defaults of the default constructor, but with the + * search scope set to the referred value. + * @param searchScope The searchScope to be set in the default + * SearchControls */ public DefaultDirContextValidator(int searchScope) { this.searchControls = new SearchControls(); @@ -113,25 +112,28 @@ public class DefaultDirContextValidator implements DirContextValidator { this.filter = DEFAULT_FILTER; } - + /** * @return the baseName */ public String getBase() { return this.base; } + /** * @param base the baseName to set */ public void setBase(String base) { this.base = base; } + /** * @return the filter */ public String getFilter() { return this.filter; } + /** * @param filter the filter to set */ @@ -139,15 +141,17 @@ public class DefaultDirContextValidator implements DirContextValidator { if (filter == null) { throw new IllegalArgumentException("filter may not be null"); } - + this.filter = filter; } + /** * @return the searchControls */ public SearchControls getSearchControls() { return this.searchControls; } + /** * @param searchControls the searchControls to set */ @@ -155,25 +159,24 @@ public class DefaultDirContextValidator implements DirContextValidator { if (searchControls == null) { throw new IllegalArgumentException("searchControls may not be null"); } - + this.searchControls = searchControls; } - /** * @see DirContextValidator#validateDirContext(DirContextType, DirContext) */ public boolean validateDirContext(DirContextType contextType, DirContext dirContext) { Assert.notNull(contextType, "contextType may not be null"); Assert.notNull(dirContext, "dirContext may not be null"); - + NamingEnumeration searchResults = null; try { searchResults = dirContext.search(this.base, this.filter, this.searchControls); if (searchResults.hasMore()) { this.logger.debug("DirContext '{}' passed validation.", dirContext); - + return true; } } @@ -185,7 +188,8 @@ public class DefaultDirContextValidator implements DirContextValidator { if (searchResults != null) { try { searchResults.close(); - } catch (NamingException ignored) { + } + catch (NamingException ignored) { } } } @@ -193,4 +197,5 @@ public class DefaultDirContextValidator implements DirContextValidator { this.logger.debug("DirContext '{}' failed validation.", dirContext); return false; } + } diff --git a/core/src/main/java/org/springframework/ldap/pool2/validation/DirContextValidator.java b/core/src/main/java/org/springframework/ldap/pool2/validation/DirContextValidator.java index edcbe7ef..0f1e1405 100644 --- a/core/src/main/java/org/springframework/ldap/pool2/validation/DirContextValidator.java +++ b/core/src/main/java/org/springframework/ldap/pool2/validation/DirContextValidator.java @@ -23,17 +23,22 @@ import javax.naming.directory.DirContext; /** * A validator for {@link DirContext}s. - * + * * @author Eric Dalquist */ public interface DirContextValidator { + /** - * Validates the {@link DirContext}. A valid {@link DirContext} should be able - * to answer queries and if applicable write to the directory. - * - * @param contextType The type of the {@link DirContext}, refers to if {@link ContextSource#getReadOnlyContext()} or {@link ContextSource#getReadWriteContext()} was called to create the {@link DirContext} + * Validates the {@link DirContext}. A valid {@link DirContext} should be able to + * answer queries and if applicable write to the directory. + * @param contextType The type of the {@link DirContext}, refers to if + * {@link ContextSource#getReadOnlyContext()} or + * {@link ContextSource#getReadWriteContext()} was called to create the + * {@link DirContext} * @param dirContext The {@link DirContext} to validate. - * @return true if the {@link DirContext} operated correctly during validation. + * @return true if the {@link DirContext} operated correctly during + * validation. */ boolean validateDirContext(DirContextType contextType, DirContext dirContext); + } diff --git a/core/src/main/java/org/springframework/ldap/query/AppendableContainerCriteria.java b/core/src/main/java/org/springframework/ldap/query/AppendableContainerCriteria.java index cd06cd86..313e625d 100644 --- a/core/src/main/java/org/springframework/ldap/query/AppendableContainerCriteria.java +++ b/core/src/main/java/org/springframework/ldap/query/AppendableContainerCriteria.java @@ -22,5 +22,7 @@ import org.springframework.ldap.filter.Filter; * @author Mattias Hellborg Arthursson */ interface AppendableContainerCriteria extends ContainerCriteria { + ContainerCriteria append(Filter filter); + } diff --git a/core/src/main/java/org/springframework/ldap/query/ConditionCriteria.java b/core/src/main/java/org/springframework/ldap/query/ConditionCriteria.java index 2af1f10b..e11de397 100644 --- a/core/src/main/java/org/springframework/ldap/query/ConditionCriteria.java +++ b/core/src/main/java/org/springframework/ldap/query/ConditionCriteria.java @@ -17,10 +17,10 @@ package org.springframework.ldap.query; /** - * Constructs a conditional LDAP filter based on the attribute specified in the previous builder step. + * Constructs a conditional LDAP filter based on the attribute specified in the previous + * builder step. * * @author Mattias Hellborg Arthursson - * * @see LdapQueryBuilder#where(String) * @see ContainerCriteria#and(String) * @see ContainerCriteria#or(String) @@ -30,10 +30,9 @@ public interface ConditionCriteria { /** * Appends an {@link org.springframework.ldap.filter.EqualsFilter}. - * * @param value the value to compare with. - * @return an ContainerCriteria instance that can be used to continue append more criteria - * or as the LdapQuery instance to be used as instance to e.g. + * @return an ContainerCriteria instance that can be used to continue append more + * criteria or as the LdapQuery instance to be used as instance to e.g. * {@link org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper)}. * * @see org.springframework.ldap.filter.EqualsFilter @@ -42,10 +41,9 @@ public interface ConditionCriteria { /** * Appends an {@link org.springframework.ldap.filter.GreaterThanOrEqualsFilter}. - * * @param value the value to compare with. - * @return an ContainerCriteria instance that can be used to continue append more criteria - * or as the LdapQuery instance to be used as instance to e.g. + * @return an ContainerCriteria instance that can be used to continue append more + * criteria or as the LdapQuery instance to be used as instance to e.g. * {@link org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper)}. * * @see org.springframework.ldap.filter.GreaterThanOrEqualsFilter @@ -54,10 +52,9 @@ public interface ConditionCriteria { /** * Appends a {@link org.springframework.ldap.filter.LessThanOrEqualsFilter}. - * * @param value the value to compare with. - * @return an ContainerCriteria instance that can be used to continue append more criteria - * or as the LdapQuery instance to be used as instance to e.g. + * @return an ContainerCriteria instance that can be used to continue append more + * criteria or as the LdapQuery instance to be used as instance to e.g. * {@link org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper)}. * * @see org.springframework.ldap.filter.LessThanOrEqualsFilter @@ -66,10 +63,9 @@ public interface ConditionCriteria { /** * Appends a {@link org.springframework.ldap.filter.LikeFilter}. - * * @param value the value to compare with. - * @return an ContainerCriteria instance that can be used to continue append more criteria - * or as the LdapQuery instance to be used as instance to e.g. + * @return an ContainerCriteria instance that can be used to continue append more + * criteria or as the LdapQuery instance to be used as instance to e.g. * {@link org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper)}. * * @see org.springframework.ldap.filter.LikeFilter @@ -78,10 +74,9 @@ public interface ConditionCriteria { /** * Appends a {@link org.springframework.ldap.filter.WhitespaceWildcardsFilter}. - * * @param value the value to compare with. - * @return an ContainerCriteria instance that can be used to continue append more criteria - * or as the LdapQuery instance to be used as instance to e.g. + * @return an ContainerCriteria instance that can be used to continue append more + * criteria or as the LdapQuery instance to be used as instance to e.g. * {@link org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper)}. * * @see org.springframework.ldap.filter.WhitespaceWildcardsFilter @@ -90,9 +85,8 @@ public interface ConditionCriteria { /** * Appends a {@link org.springframework.ldap.filter.PresentFilter}. - * - * @return an ContainerCriteria instance that can be used to continue append more criteria - * or as the LdapQuery instance to be used as instance to e.g. + * @return an ContainerCriteria instance that can be used to continue append more + * criteria or as the LdapQuery instance to be used as instance to e.g. * {@link org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper)}. * * @see org.springframework.ldap.filter.PresentFilter @@ -100,14 +94,15 @@ public interface ConditionCriteria { ContainerCriteria isPresent(); /** - * Negates the currently constructed operation. In effect this means that the resulting filter will be - * wrapped in a {@link org.springframework.ldap.filter.NotFilter}. - * - * @return an ContainerCriteria instance that can be used to continue append more criteria - * or as the LdapQuery instance to be used as instance to e.g. + * Negates the currently constructed operation. In effect this means that the + * resulting filter will be wrapped in a + * {@link org.springframework.ldap.filter.NotFilter}. + * @return an ContainerCriteria instance that can be used to continue append more + * criteria or as the LdapQuery instance to be used as instance to e.g. * {@link org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper)}. * * @see org.springframework.ldap.filter.NotFilter */ ConditionCriteria not(); + } diff --git a/core/src/main/java/org/springframework/ldap/query/ContainerCriteria.java b/core/src/main/java/org/springframework/ldap/query/ContainerCriteria.java index 2200360d..a2ddff54 100644 --- a/core/src/main/java/org/springframework/ldap/query/ContainerCriteria.java +++ b/core/src/main/java/org/springframework/ldap/query/ContainerCriteria.java @@ -23,41 +23,43 @@ package org.springframework.ldap.query; * @since 2.0 */ public interface ContainerCriteria extends LdapQuery { + /** * Append a logical And condition to the currently built filter. - * * @param attribute Name of the attribute to specify a condition for. * @return A ConditionCriteria instance for specifying the compare operation. - * @throws IllegalStateException if {@link #or(String)} has previously been called on this instance. + * @throws IllegalStateException if {@link #or(String)} has previously been called on + * this instance. */ ConditionCriteria and(String attribute); /** * Append a logical Or condition to the currently built filter. - * * @param attribute Name of the attribute to specify a condition for. * @return A ConditionCriteria instance for specifying the compare operation. - * @throws IllegalStateException if {@link #and(String)} has previously been called on this instance. + * @throws IllegalStateException if {@link #and(String)} has previously been called on + * this instance. */ ConditionCriteria or(String attribute); /** - * Append an And condition for a nested criterion. Use {@link org.springframework.ldap.query.LdapQueryBuilder#query()} - * to start the nested condition. Any base query information on the nested builder instance will not be considered. - * + * Append an And condition for a nested criterion. Use + * {@link org.springframework.ldap.query.LdapQueryBuilder#query()} to start the nested + * condition. Any base query information on the nested builder instance will not be + * considered. * @param nested the nested criterion. - * * @return A ConditionCriteria instance for specifying the compare operation. */ ContainerCriteria and(ContainerCriteria nested); /** - * Append an Or condition for a nested criterion. Use {@link org.springframework.ldap.query.LdapQueryBuilder#query()} - * to start the nested condition. Any base query information on the nested builder instance will not be considered. - * + * Append an Or condition for a nested criterion. Use + * {@link org.springframework.ldap.query.LdapQueryBuilder#query()} to start the nested + * condition. Any base query information on the nested builder instance will not be + * considered. * @param nested the nested criterion. - * * @return A ConditionCriteria instance for specifying the compare operation. */ ContainerCriteria or(ContainerCriteria nested); + } diff --git a/core/src/main/java/org/springframework/ldap/query/CriteriaContainerType.java b/core/src/main/java/org/springframework/ldap/query/CriteriaContainerType.java index e27e0a14..4230ccf6 100644 --- a/core/src/main/java/org/springframework/ldap/query/CriteriaContainerType.java +++ b/core/src/main/java/org/springframework/ldap/query/CriteriaContainerType.java @@ -25,12 +25,14 @@ import org.springframework.ldap.filter.OrFilter; * @since 2.0 */ enum CriteriaContainerType { + AND { @Override public BinaryLogicalFilter constructFilter() { return new AndFilter(); } - }, OR { + }, + OR { @Override public BinaryLogicalFilter constructFilter() { return new OrFilter(); @@ -41,11 +43,11 @@ enum CriteriaContainerType { if (oldType != null && oldType != this) { throw new IllegalStateException( String.format("Container type has already been specified as %s, cannot change it to %s", - oldType.toString(), - this.toString())); + oldType.toString(), this.toString())); } } public abstract BinaryLogicalFilter constructFilter(); + } diff --git a/core/src/main/java/org/springframework/ldap/query/DefaultConditionCriteria.java b/core/src/main/java/org/springframework/ldap/query/DefaultConditionCriteria.java index 1f50e803..1c1d260e 100644 --- a/core/src/main/java/org/springframework/ldap/query/DefaultConditionCriteria.java +++ b/core/src/main/java/org/springframework/ldap/query/DefaultConditionCriteria.java @@ -30,8 +30,11 @@ import org.springframework.ldap.filter.WhitespaceWildcardsFilter; * @since 2.0 */ class DefaultConditionCriteria implements ConditionCriteria { + private final AppendableContainerCriteria parent; + private final String attribute; + private boolean negated = false; DefaultConditionCriteria(AppendableContainerCriteria parent, String attribute) { @@ -86,4 +89,5 @@ class DefaultConditionCriteria implements ConditionCriteria { negated = !negated; return this; } + } diff --git a/core/src/main/java/org/springframework/ldap/query/DefaultContainerCriteria.java b/core/src/main/java/org/springframework/ldap/query/DefaultContainerCriteria.java index 04d182bd..fd62e6a7 100644 --- a/core/src/main/java/org/springframework/ldap/query/DefaultContainerCriteria.java +++ b/core/src/main/java/org/springframework/ldap/query/DefaultContainerCriteria.java @@ -30,8 +30,11 @@ import static org.springframework.ldap.query.CriteriaContainerType.OR; * @since 2.0 */ class DefaultContainerCriteria implements AppendableContainerCriteria { + private final Set filters = new LinkedHashSet(); + private final LdapQuery topQuery; + private CriteriaContainerType type; DefaultContainerCriteria(LdapQuery topQuery) { @@ -67,12 +70,10 @@ class DefaultContainerCriteria implements AppendableContainerCriteria { @Override public ContainerCriteria and(ContainerCriteria nested) { - if(type == OR) { - return new DefaultContainerCriteria(topQuery) - .withType(AND) - .append(this.filter()) - .append(nested.filter()); - } else { + if (type == OR) { + return new DefaultContainerCriteria(topQuery).withType(AND).append(this.filter()).append(nested.filter()); + } + else { type = AND; this.filters.add(nested.filter()); return this; @@ -82,11 +83,9 @@ class DefaultContainerCriteria implements AppendableContainerCriteria { @Override public ContainerCriteria or(ContainerCriteria nested) { if (type == AND) { - return new DefaultContainerCriteria(topQuery) - .withType(OR) - .append(this.filter()) - .append(nested.filter()); - } else { + return new DefaultContainerCriteria(topQuery).withType(OR).append(this.filter()).append(nested.filter()); + } + else { type = OR; this.filters.add(nested.filter()); return this; @@ -95,7 +94,7 @@ class DefaultContainerCriteria implements AppendableContainerCriteria { @Override public Filter filter() { - if(filters.size() == 1) { + if (filters.size() == 1) { // No need to wrap in And/OrFilter if there's just one condition. return filters.iterator().next(); } @@ -127,4 +126,5 @@ class DefaultContainerCriteria implements AppendableContainerCriteria { public String[] attributes() { return topQuery.attributes(); } + } diff --git a/core/src/main/java/org/springframework/ldap/query/LdapQuery.java b/core/src/main/java/org/springframework/ldap/query/LdapQuery.java index 399b7d43..25b992c9 100644 --- a/core/src/main/java/org/springframework/ldap/query/LdapQuery.java +++ b/core/src/main/java/org/springframework/ldap/query/LdapQuery.java @@ -21,57 +21,61 @@ import org.springframework.ldap.filter.Filter; import javax.naming.Name; /** - * Holds all information regarding a Ldap query to be performed. Contains information regarding search base, - * search scope, time and count limits, and search filter. + * Holds all information regarding a Ldap query to be performed. Contains information + * regarding search base, search scope, time and count limits, and search filter. * * @author Mattias Hellborg Arthursson * @since 2.0 * @see LdapQueryBuilder - * - * @see org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.AttributesMapper) - * @see org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper) - * @see org.springframework.ldap.core.LdapOperations#searchForObject(LdapQuery, org.springframework.ldap.core.ContextMapper) + * @see org.springframework.ldap.core.LdapOperations#search(LdapQuery, + * org.springframework.ldap.core.AttributesMapper) + * @see org.springframework.ldap.core.LdapOperations#search(LdapQuery, + * org.springframework.ldap.core.ContextMapper) + * @see org.springframework.ldap.core.LdapOperations#searchForObject(LdapQuery, + * org.springframework.ldap.core.ContextMapper) * @see org.springframework.ldap.core.LdapOperations#searchForContext(LdapQuery) */ public interface LdapQuery { + /** - * Get the search base. Default is {@link org.springframework.ldap.support.LdapUtils#emptyLdapName()}. - * + * Get the search base. Default is + * {@link org.springframework.ldap.support.LdapUtils#emptyLdapName()}. * @return the search base. */ Name base(); /** - * Get the search scope. Default is null, indicating that the LdapTemplate default should be used. - * + * Get the search scope. Default is null, indicating that the + * LdapTemplate default should be used. * @return the search scope. */ SearchScope searchScope(); /** - * Get the time limit. Default is null, indicating that the LdapTemplate default should be used. - * + * Get the time limit. Default is null, indicating that the LdapTemplate + * default should be used. * @return the time limit. */ Integer timeLimit(); /** - * Get the count limit. Default is null, indicating that the LdapTemplate default should be used. + * Get the count limit. Default is null, indicating that the LdapTemplate + * default should be used. * @return the count limit. */ Integer countLimit(); /** - * Get the attributes to return. Default is null, indicating that all attributes should be returned. - * + * Get the attributes to return. Default is null, indicating that all + * attributes should be returned. * @return the attributes to return. */ String[] attributes(); /** * Get the filter. - * * @return the filter. */ Filter filter(); + } diff --git a/core/src/main/java/org/springframework/ldap/query/LdapQueryBuilder.java b/core/src/main/java/org/springframework/ldap/query/LdapQueryBuilder.java index 3ccec08f..04ce7689 100644 --- a/core/src/main/java/org/springframework/ldap/query/LdapQueryBuilder.java +++ b/core/src/main/java/org/springframework/ldap/query/LdapQueryBuilder.java @@ -26,10 +26,9 @@ import javax.naming.Name; import java.text.MessageFormat; /** - * Builder of LdapQueries. Start with a call to {@link #query()}, proceed with specifying the - * basic search configuration (e.g. search base, time limit, etc.), finally specify the actual query. - * Example: - *
    + * Builder of LdapQueries. Start with a call to {@link #query()}, proceed with specifying
    + * the basic search configuration (e.g. search base, time limit, etc.), finally specify
    + * the actual query. Example: 
      * import static org.springframework.ldap.query.LdapQueryBuilder.query;
      * ...
      *
    @@ -41,24 +40,33 @@ import java.text.MessageFormat;
      *  .where("objectclass").is("person").and("cn").is("John Doe");
      * 
    *

    - * Default configuration is that base path is {@link org.springframework.ldap.support.LdapUtils#emptyLdapName()}. - * All other parameters are undefined, meaning that (in the case of base search parameters), the LdapTemplate - * defaults will be used. Filter conditions must always be specified. + * Default configuration is that base path is + * {@link org.springframework.ldap.support.LdapUtils#emptyLdapName()}. All other + * parameters are undefined, meaning that (in the case of base search parameters), the + * LdapTemplate defaults will be used. Filter conditions must always be specified. *

    + * * @author Mattias Hellborg Arthursson * @since 2.0 - * * @see javax.naming.directory.SearchControls - * @see org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.AttributesMapper) - * @see org.springframework.ldap.core.LdapOperations#search(LdapQuery, org.springframework.ldap.core.ContextMapper) - * @see org.springframework.ldap.core.LdapOperations#searchForObject(LdapQuery, org.springframework.ldap.core.ContextMapper) + * @see org.springframework.ldap.core.LdapOperations#search(LdapQuery, + * org.springframework.ldap.core.AttributesMapper) + * @see org.springframework.ldap.core.LdapOperations#search(LdapQuery, + * org.springframework.ldap.core.ContextMapper) + * @see org.springframework.ldap.core.LdapOperations#searchForObject(LdapQuery, + * org.springframework.ldap.core.ContextMapper) * @see org.springframework.ldap.core.LdapOperations#searchForContext(LdapQuery) */ public final class LdapQueryBuilder implements LdapQuery { + private Name base = LdapUtils.emptyLdapName(); + private SearchScope searchScope = null; + private Integer countLimit = null; + private Integer timeLimit = null; + private String[] attributes = null; private DefaultContainerCriteria rootContainer = null; @@ -74,7 +82,6 @@ public final class LdapQueryBuilder implements LdapQuery { /** * Construct a new LdapQueryBuilder. - * * @return a new instance. */ public static LdapQueryBuilder query() { @@ -82,13 +89,12 @@ public final class LdapQueryBuilder implements LdapQuery { } /** - * Construct a new {@link LdapQueryBuilder} based on an existing {@link LdapQuery} - * All fields are copied, including giving the query a default filter. + * Construct a new {@link LdapQueryBuilder} based on an existing {@link LdapQuery} All + * fields are copied, including giving the query a default filter. * *

    * Note that all filter invariants are still enforced; an application cannot specify * any non-filter values after it specifies a filter. - * * @return a new instance. * @since 3.0 */ @@ -107,9 +113,8 @@ public final class LdapQueryBuilder implements LdapQuery { } /** - * Set the base search path for the query. - * Default is {@link org.springframework.ldap.support.LdapUtils#emptyLdapName()}. - * + * Set the base search path for the query. Default is + * {@link org.springframework.ldap.support.LdapUtils#emptyLdapName()}. * @param baseDn the base search path. * @return this instance. */ @@ -120,9 +125,8 @@ public final class LdapQueryBuilder implements LdapQuery { } /** - * Set the base search path for the query. - * Default is {@link org.springframework.ldap.support.LdapUtils#emptyLdapName()}. - * + * Set the base search path for the query. Default is + * {@link org.springframework.ldap.support.LdapUtils#emptyLdapName()}. * @param baseDn the base search path. * @return this instance. */ @@ -133,9 +137,7 @@ public final class LdapQueryBuilder implements LdapQuery { } /** - * Set the search scope for the query. - * Default is {@link SearchScope#SUBTREE}. - * + * Set the search scope for the query. Default is {@link SearchScope#SUBTREE}. * @param searchScope the search scope. * @return this instance. */ @@ -146,9 +148,7 @@ public final class LdapQueryBuilder implements LdapQuery { } /** - * Set the count limit for the query. - * Default is 0 (no limit). - * + * Set the count limit for the query. Default is 0 (no limit). * @param countLimit the count limit. * @return this instance. */ @@ -165,9 +165,7 @@ public final class LdapQueryBuilder implements LdapQuery { } /** - * Set the time limit for the query. - * Default is 0 (no limit). - * + * Set the time limit for the query. Default is 0 (no limit). * @param timeLimit the time limit. * @return this instance. */ @@ -179,8 +177,8 @@ public final class LdapQueryBuilder implements LdapQuery { /** * Start specifying the filter conditions in this query. - * - * @param attribute The attribute that the first part of the filter should test against. + * @param attribute The attribute that the first part of the filter should test + * against. * @return A ConditionCriteria instance for specifying the compare operation. * @throws IllegalStateException if a filter has already been specified. */ @@ -196,12 +194,13 @@ public final class LdapQueryBuilder implements LdapQuery { } /** - * Specify a hardcoded filter. Please note that using this method, the filter string will not be - * validated or escaped in any way. Never use direct user input and use it concatenating strings - * to use as LDAP filters. Doing so opens up for "LDAP injection", where malicious user - * may inject specifically constructed data to form filters at their convenience. When user input is used - * consider using {@link #where(String)}, {@link #filter(String, Object...)}, or {@link #filter(Filter)} instead. - * + * Specify a hardcoded filter. Please note that using this method, the filter string + * will not be validated or escaped in any way. Never use direct user input and + * use it concatenating strings to use as LDAP filters. Doing so opens up for + * "LDAP injection", where malicious user may inject specifically + * constructed data to form filters at their convenience. When user input is used + * consider using {@link #where(String)}, {@link #filter(String, Object...)}, or + * {@link #filter(Filter)} instead. * @param hardcodedFilter The hardcoded filter string to use in the search. * @return this instance. * @throws IllegalStateException if a filter has already been specified. @@ -214,7 +213,6 @@ public final class LdapQueryBuilder implements LdapQuery { /** * Specify the filter to use. - * * @param filter The filter to use in the search. * @return this instance. * @throws IllegalStateException if a filter has already been specified. @@ -226,19 +224,21 @@ public final class LdapQueryBuilder implements LdapQuery { } /** - * Specify a hardcoded filter using the specified parameters. The parameters will be properly encoded using - * {@link LdapEncoder#filterEncode(String)} to make sure no malicious data gets through. The filterFormat - * String should be formatted for input to {@link MessageFormat#format(String, Object...)}. - * - * @param filterFormat the filter format string, formatted for input to {@link MessageFormat#format(String, Object...)}. - * @param params the parameters that will be used for building the final filter. All parameters will be properly encoded. + * Specify a hardcoded filter using the specified parameters. The parameters will be + * properly encoded using {@link LdapEncoder#filterEncode(String)} to make sure no + * malicious data gets through. The filterFormat String should be + * formatted for input to {@link MessageFormat#format(String, Object...)}. + * @param filterFormat the filter format string, formatted for input to + * {@link MessageFormat#format(String, Object...)}. + * @param params the parameters that will be used for building the final filter. All + * parameters will be properly encoded. * @return this instance. * @throws IllegalStateException if a filter has already been specified. */ public LdapQuery filter(String filterFormat, Object... params) { Object[] encodedParams = new String[params.length]; - for (int i=0; i < params.length; i++) { + for (int i = 0; i < params.length; i++) { encodedParams[i] = LdapEncoder.filterEncode(params[i].toString()); } @@ -274,12 +274,12 @@ public final class LdapQueryBuilder implements LdapQuery { return attributes; } - @Override public Filter filter() { - if(rootContainer == null) { + if (rootContainer == null) { throw new IllegalStateException("No filter conditions have been specified"); } return rootContainer.filter(); } -} \ No newline at end of file + +} diff --git a/core/src/main/java/org/springframework/ldap/query/SearchScope.java b/core/src/main/java/org/springframework/ldap/query/SearchScope.java index 83a17ffc..5a685e52 100644 --- a/core/src/main/java/org/springframework/ldap/query/SearchScope.java +++ b/core/src/main/java/org/springframework/ldap/query/SearchScope.java @@ -25,6 +25,7 @@ import javax.naming.directory.SearchControls; * @since 2.0 */ public enum SearchScope { + /** * Corresponds to {@link SearchControls#OBJECT_SCOPE} */ @@ -47,4 +48,5 @@ public enum SearchScope { public int getId() { return id; } + } diff --git a/core/src/main/java/org/springframework/ldap/support/AttributeValueCallbackHandler.java b/core/src/main/java/org/springframework/ldap/support/AttributeValueCallbackHandler.java index b442f9e8..7f7fdb12 100644 --- a/core/src/main/java/org/springframework/ldap/support/AttributeValueCallbackHandler.java +++ b/core/src/main/java/org/springframework/ldap/support/AttributeValueCallbackHandler.java @@ -17,17 +17,18 @@ package org.springframework.ldap.support; /** * Callback interface for use when looping through Attribute values. - * + * * @author Mattias Hellborg Arthursson * @since 1.3 */ public interface AttributeValueCallbackHandler { + /** * Implement to take handle one of the Attribute values. - * * @param attributeName the name of the Attribute. * @param attributeValue the value. * @param index the index of the value within the Attribute. */ void handleAttributeValue(String attributeName, Object attributeValue, int index); + } diff --git a/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java b/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java index 87a1769e..eeb836b8 100644 --- a/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java +++ b/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java @@ -31,6 +31,7 @@ import org.springframework.util.Assert; public final class LdapEncoder { private static final int HEX = 16; + private static String[] NAME_ESCAPE_TABLE = new String[96]; private static String[] FILTER_ESCAPE_TABLE = new String['\\' + 1]; @@ -84,16 +85,15 @@ public final class LdapEncoder { if (raw.length() > 1) { return raw; - } else { + } + else { return "0" + raw; } } /** * Escape a value for use in a filter. - * - * @param value - * the value to escape. + * @param value the value to escape. * @return a properly escaped representation of the supplied value. */ public static String filterEncode(String value) { @@ -112,7 +112,8 @@ public final class LdapEncoder { if (c < FILTER_ESCAPE_TABLE.length) { encodedValue.append(FILTER_ESCAPE_TABLE[c]); - } else { + } + else { // default: add the char encodedValue.append(c); } @@ -124,14 +125,19 @@ public final class LdapEncoder { /** * LDAP Encodes a value for use with a DN. Escapes for LDAP, not JNDI! * - *
    Escapes:
    ' ' [space] - "\ " [if first or last]
    '#' - * [hash] - "\#"
    ',' [comma] - "\,"
    ';' [semicolon] - "\;"
    '= - * [equals] - "\="
    '+' [plus] - "\+"
    '<' [less than] - - * "\<"
    '>' [greater than] - "\>"
    '"' [double quote] - - * "\""
    '\' [backslash] - "\\"
    - * - * @param value - * the value to escape. + *
    + * Escapes:
    + * ' ' [space] - "\ " [if first or last]
    + * '#' [hash] - "\#"
    + * ',' [comma] - "\,"
    + * ';' [semicolon] - "\;"
    + * '= [equals] - "\="
    + * '+' [plus] - "\+"
    + * '<' [less than] - "\<"
    + * '>' [greater than] - "\>"
    + * '"' [double quote] - "\""
    + * '\' [backslash] - "\\"
    + * @param value the value to escape. * @return The escaped value. */ public static String nameEncode(String value) { @@ -175,15 +181,12 @@ public final class LdapEncoder { /** * Decodes a value. Converts escaped chars to ordinary chars. - * - * @param value - * Trimmed value, so no leading an trailing blanks, except an - * escaped space last. + * @param value Trimmed value, so no leading an trailing blanks, except an escaped + * space last. * @return The decoded value as a string. * @throws BadLdapGrammarException */ - static public String nameDecode(String value) - throws BadLdapGrammarException { + static public String nameDecode(String value) throws BadLdapGrammarException { if (value == null) return null; @@ -197,35 +200,32 @@ public final class LdapEncoder { if (currentChar == '\\') { if (value.length() <= i + 1) { // Ending with a single backslash is not allowed - throw new BadLdapGrammarException( - "Unexpected end of value " + "unterminated '\\'"); - } else { + throw new BadLdapGrammarException("Unexpected end of value " + "unterminated '\\'"); + } + else { char nextChar = value.charAt(i + 1); - if (nextChar == ',' || nextChar == '=' || nextChar == '+' - || nextChar == '<' || nextChar == '>' - || nextChar == '#' || nextChar == ';' - || nextChar == '\\' || nextChar == '\"' + if (nextChar == ',' || nextChar == '=' || nextChar == '+' || nextChar == '<' || nextChar == '>' + || nextChar == '#' || nextChar == ';' || nextChar == '\\' || nextChar == '\"' || nextChar == ' ') { // Normal backslash escape decoded.append(nextChar); i += 2; - } else { + } + else { if (value.length() <= i + 2) { throw new BadLdapGrammarException( - "Unexpected end of value " - + "expected special or hex, found '" - + nextChar + "'"); - } else { + "Unexpected end of value " + "expected special or hex, found '" + nextChar + "'"); + } + else { // This should be a hex value - String hexString = "" + nextChar - + value.charAt(i + 2); - decoded.append((char) Integer.parseInt(hexString, - HEX)); + String hexString = "" + nextChar + value.charAt(i + 2); + decoded.append((char) Integer.parseInt(hexString, HEX)); i += 3; } } } - } else { + } + else { // This character wasn't escaped - just append it decoded.append(currentChar); i++; @@ -237,11 +237,11 @@ public final class LdapEncoder { } /** - * Converts an array of bytes into a Base64 encoded string according to the rules for converting LDAP Attributes in RFC2849. - * + * Converts an array of bytes into a Base64 encoded string according to the rules for + * converting LDAP Attributes in RFC2849. * @param val - * @return - * A string containing a lexical representation of base64Binary wrapped around 76 characters. + * @return A string containing a lexical representation of base64Binary wrapped around + * 76 characters. * @throws IllegalArgumentException if val is null. */ public static String printBase64Binary(byte[] val) { @@ -267,11 +267,10 @@ public final class LdapEncoder { /** * Converts the Base64 encoded string argument into an array of bytes. - * * @param val - * @return - * An array of bytes represented by the string argument. - * @throws IllegalArgumentException if val is null or does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:base64Binary. + * @return An array of bytes represented by the string argument. + * @throws IllegalArgumentException if val is null or does not conform to + * lexical value space defined in XML Schema Part 2: Datatypes for xsd:base64Binary. */ public static byte[] parseBase64Binary(String val) { @@ -283,8 +282,8 @@ public final class LdapEncoder { char c = val.charAt(i); - if(c == '\n'){ - if(i + 1 < len && val.charAt(i + 1) == ' ') { + if (c == '\n') { + if (i + 1 < len && val.charAt(i + 1) == ' ') { i++; } continue; @@ -303,4 +302,5 @@ public final class LdapEncoder { private static byte[] decode(String encoded) { return Base64.getDecoder().decode(encoded); } + } diff --git a/core/src/main/java/org/springframework/ldap/support/LdapNameBuilder.java b/core/src/main/java/org/springframework/ldap/support/LdapNameBuilder.java index 83e415de..45a1b58d 100644 --- a/core/src/main/java/org/springframework/ldap/support/LdapNameBuilder.java +++ b/core/src/main/java/org/springframework/ldap/support/LdapNameBuilder.java @@ -26,12 +26,11 @@ import javax.naming.ldap.Rdn; /** * Helper class for building {@link javax.naming.ldap.LdapName} instances. * - * Note that the first part of a Distinguished Name is the least significant, which means that when adding components, - * they will be added to the beginning of the resulting string, e.g. - *

    + * Note that the first part of a Distinguished Name is the least significant, which means
    + * that when adding components, they will be added to the beginning of the
    + * resulting string, e.g. 
      *	 LdapNameBuilder.newInstance("dc=261consulting,dc=com").add("ou=people").build().toString();
    - * 
    - * will result in ou=people,dc=261consulting,dc=com. + *
    will result in ou=people,dc=261consulting,dc=com. * * @author Mattias Hellborg Arthursson * @since 2.0 @@ -46,7 +45,6 @@ public final class LdapNameBuilder { /** * Construct a new instance, starting with a blank LdapName. - * * @return a new instance. */ public static LdapNameBuilder newInstance() { @@ -56,7 +54,6 @@ public final class LdapNameBuilder { /** * Construct a new instance, starting with a copy of the supplied LdapName. * @param name the starting point of the LdapName to be built. - * * @return a new instance. */ public static LdapNameBuilder newInstance(Name name) { @@ -64,9 +61,9 @@ public final class LdapNameBuilder { } /** - * Construct a new instance, starting with an LdapName constructed from the supplied string. + * Construct a new instance, starting with an LdapName constructed from the supplied + * string. * @param name the starting point of the LdapName to be built. - * * @return a new instance. */ public static LdapNameBuilder newInstance(String name) { @@ -77,7 +74,6 @@ public final class LdapNameBuilder { * Add a Rdn to the built LdapName. * @param key the rdn attribute key. * @param value the rdn value. - * * @return this builder. */ public LdapNameBuilder add(String key, Object value) { @@ -87,14 +83,14 @@ public final class LdapNameBuilder { try { ldapName.add(new Rdn(key, value)); return this; - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw new org.springframework.ldap.InvalidNameException(e); } } /** * Append the specified name to the currently built LdapName. - * * @param name the name to add. * @return this builder. */ @@ -104,14 +100,15 @@ public final class LdapNameBuilder { try { ldapName.addAll(ldapName.size(), name); return this; - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw new org.springframework.ldap.InvalidNameException(e); } } /** - * Append the LdapName represented by the specified string to the currently built LdapName. - * + * Append the LdapName represented by the specified string to the currently built + * LdapName. * @param name the name to add. * @return this builder. */ @@ -123,10 +120,10 @@ public final class LdapNameBuilder { /** * Build the LdapName instance. - * * @return the LdapName instance that has been built. */ public LdapName build() { return LdapUtils.newLdapName(ldapName); } + } diff --git a/core/src/main/java/org/springframework/ldap/support/LdapUtils.java b/core/src/main/java/org/springframework/ldap/support/LdapUtils.java index 81994614..a1a09a9f 100644 --- a/core/src/main/java/org/springframework/ldap/support/LdapUtils.java +++ b/core/src/main/java/org/springframework/ldap/support/LdapUtils.java @@ -39,9 +39,9 @@ import java.util.List; import java.util.NoSuchElementException; /** - * Generic utility methods for working with LDAP. Mainly for internal use within - * the framework, but also useful for custom code. - * + * Generic utility methods for working with LDAP. Mainly for internal use within the + * framework, but also useful for custom code. + * * @author Ulrik Sandberg * @author Mattias Hellborg Arthursson * @since 1.2 @@ -49,6 +49,7 @@ import java.util.NoSuchElementException; public final class LdapUtils { private static final Logger LOGGER = LoggerFactory.getLogger(LdapUtils.class); + private static final int HEX = 16; /** @@ -59,9 +60,8 @@ public final class LdapUtils { } /** - * Close the given JNDI Context and ignore any thrown exception. This is - * useful for typical finally blocks in JNDI code. - * + * Close the given JNDI Context and ignore any thrown exception. This is useful for + * typical finally blocks in JNDI code. * @param context the JNDI Context to close (may be null) */ public static void closeContext(DirContext context) { @@ -81,14 +81,11 @@ public final class LdapUtils { } /** - * Convert the specified checked {@link javax.naming.NamingException - * NamingException} to a Spring LDAP runtime - * {@link org.springframework.ldap.NamingException NamingException} - * equivalent. - * + * Convert the specified checked {@link javax.naming.NamingException NamingException} + * to a Spring LDAP runtime {@link org.springframework.ldap.NamingException + * NamingException} equivalent. * @param ex the original checked NamingException to convert - * @return the Spring LDAP runtime NamingException wrapping the given - * exception + * @return the Spring LDAP runtime NamingException wrapping the given exception */ public static NamingException convertLdapException(javax.naming.NamingException ex) { Assert.notNull(ex, "NamingException must not be null"); @@ -118,7 +115,8 @@ public final class LdapUtils { (javax.naming.InsufficientResourcesException) ex); } if (javax.naming.InterruptedNamingException.class.isAssignableFrom(ex.getClass())) { - return new org.springframework.ldap.InterruptedNamingException((javax.naming.InterruptedNamingException) ex); + return new org.springframework.ldap.InterruptedNamingException( + (javax.naming.InterruptedNamingException) ex); } if (javax.naming.directory.InvalidAttributeIdentifierException.class.isAssignableFrom(ex.getClass())) { return new org.springframework.ldap.InvalidAttributeIdentifierException( @@ -154,10 +152,12 @@ public final class LdapUtils { // LimitExceededException hierarchy if (javax.naming.SizeLimitExceededException.class.isAssignableFrom(ex.getClass())) { - return new org.springframework.ldap.SizeLimitExceededException((javax.naming.SizeLimitExceededException) ex); + return new org.springframework.ldap.SizeLimitExceededException( + (javax.naming.SizeLimitExceededException) ex); } if (javax.naming.TimeLimitExceededException.class.isAssignableFrom(ex.getClass())) { - return new org.springframework.ldap.TimeLimitExceededException((javax.naming.TimeLimitExceededException) ex); + return new org.springframework.ldap.TimeLimitExceededException( + (javax.naming.TimeLimitExceededException) ex); } // this class is the superclass of the two above if (javax.naming.LimitExceededException.class.isAssignableFrom(ex.getClass())) { @@ -231,10 +231,8 @@ public final class LdapUtils { /** * Get the actual class of the supplied DirContext instance; LdapContext or * DirContext. - * * @param context the DirContext instance to check. - * @return LdapContext.class if context is an LdapContext, DirContext.class - * otherwise. + * @return LdapContext.class if context is an LdapContext, DirContext.class otherwise. */ public static Class getActualTargetClass(DirContext context) { if (context instanceof LdapContext) { @@ -245,14 +243,11 @@ public final class LdapUtils { } /** - * Collect all the values of a the specified attribute from the supplied - * Attributes. - * + * Collect all the values of a the specified attribute from the supplied Attributes. * @param attributes The Attributes; not null. * @param name The name of the Attribute to get values for. * @param collection the collection to collect the values in. - * @throws NoSuchAttributeException if no attribute with the specified name - * exists. + * @throws NoSuchAttributeException if no attribute with the specified name exists. * @since 1.3 */ public static void collectAttributeValues(Attributes attributes, String name, Collection collection) { @@ -260,20 +255,19 @@ public final class LdapUtils { } /** - * Collect all the values of a the specified attribute from the supplied - * Attributes as the specified class. - * + * Collect all the values of a the specified attribute from the supplied Attributes as + * the specified class. * @param attributes The Attributes; not null. * @param name The name of the Attribute to get values for. * @param collection the collection to collect the values in. * @param clazz the class of the collected attribute values - * @throws NoSuchAttributeException if no attribute with the specified name - * exists. - * @throws IllegalArgumentException if an attribute value cannot be cast to the specified class. + * @throws NoSuchAttributeException if no attribute with the specified name exists. + * @throws IllegalArgumentException if an attribute value cannot be cast to the + * specified class. * @since 2.0 */ - public static void collectAttributeValues( - Attributes attributes, String name, Collection collection, Class clazz) { + public static void collectAttributeValues(Attributes attributes, String name, Collection collection, + Class clazz) { Assert.notNull(attributes, "Attributes must not be null"); Assert.hasText(name, "Name must not be empty"); @@ -289,8 +283,8 @@ public final class LdapUtils { } /** - * Iterate through all the values of the specified Attribute calling back to - * the specified callbackHandler. + * Iterate through all the values of the specified Attribute calling back to the + * specified callbackHandler. * @param attribute the Attribute to work with; not null. * @param callbackHandler the callbackHandler; not null. * @since 1.3 @@ -310,25 +304,29 @@ public final class LdapUtils { for (int i = 0; i < attribute.size(); i++) { try { handleAttributeValue(attribute.getID(), attribute.get(i), i, callbackHandler); - } catch (javax.naming.NamingException e) { + } + catch (javax.naming.NamingException e) { throw convertLdapException(e); } } } } - private static void handleAttributeValue(String attributeID, Object value, int i, AttributeValueCallbackHandler callbackHandler) { + private static void handleAttributeValue(String attributeID, Object value, int i, + AttributeValueCallbackHandler callbackHandler) { callbackHandler.handleAttributeValue(attributeID, value, i); } /** * An {@link AttributeValueCallbackHandler} to collect values in a supplied * collection. - * + * * @author Mattias Hellborg Arthursson */ private static final class CollectingAttributeValueCallbackHandler implements AttributeValueCallbackHandler { + private final Collection collection; + private final Class clazz; public CollectingAttributeValueCallbackHandler(Collection collection, Class clazz) { @@ -343,17 +341,16 @@ public final class LdapUtils { Assert.isTrue(attributeName == null || clazz.isAssignableFrom(attributeValue.getClass())); collection.add(clazz.cast(attributeValue)); } + } /** - * Converts a CompositeName to a String in a way that avoids escaping - * problems, such as the dreaded "triple backslash" problem. - * + * Converts a CompositeName to a String in a way that avoids escaping problems, such + * as the dreaded "triple backslash" problem. * @param compositeName The CompositeName to convert * @return String containing the String representation of name */ - public static String convertCompositeNameToString( - CompositeName compositeName) { + public static String convertCompositeNameToString(CompositeName compositeName) { if (compositeName.size() > 0) { // A lookup with an empty String seems to produce an empty // compositeName here; need to take this into account. @@ -365,33 +362,39 @@ public final class LdapUtils { } /** - * Construct a new LdapName instance from the supplied Name instance. - * LdapName instances will be cloned, CompositeName tweaks will be managed using - * {@link #convertCompositeNameToString(javax.naming.CompositeName)}; for all other Name - * implementations, new LdapName instances are constructed using {@link LdapName#addAll(int, javax.naming.Name)}. - * + * Construct a new LdapName instance from the supplied Name instance. LdapName + * instances will be cloned, CompositeName tweaks will be managed using + * {@link #convertCompositeNameToString(javax.naming.CompositeName)}; for all other + * Name implementations, new LdapName instances are constructed using + * {@link LdapName#addAll(int, javax.naming.Name)}. * @param name the Name instance to convert to LdapName, not null. - * @return a new LdapName representing the same Distinguished Name as the supplied instance. - * @throws org.springframework.ldap.InvalidNameException to wrap any InvalidNameExceptions thrown by LdapName. + * @return a new LdapName representing the same Distinguished Name as the supplied + * instance. + * @throws org.springframework.ldap.InvalidNameException to wrap any + * InvalidNameExceptions thrown by LdapName. * @since 2.0 */ public static LdapName newLdapName(Name name) { Assert.notNull(name, "name must not be null"); - if(name instanceof LdapName) { + if (name instanceof LdapName) { return (LdapName) name.clone(); - } else if (name instanceof CompositeName) { + } + else if (name instanceof CompositeName) { CompositeName compositeName = (CompositeName) name; try { return new LdapName(convertCompositeNameToString(compositeName)); - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw convertLdapException(e); } - } else { + } + else { LdapName result = emptyLdapName(); try { result.addAll(0, name); - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw convertLdapException(e); } @@ -401,10 +404,10 @@ public final class LdapUtils { /** * Construct a new LdapName instance from the supplied distinguished name string. - * * @param distinguishedName the string to parse for constructing an LdapName instance. * @return a new LdapName instance. - * @throws org.springframework.ldap.InvalidNameException to wrap any InvalidNameExceptions thrown by LdapName. + * @throws org.springframework.ldap.InvalidNameException to wrap any + * InvalidNameExceptions thrown by LdapName. * @since 2.0 */ public static LdapName newLdapName(String distinguishedName) { @@ -412,30 +415,29 @@ public final class LdapUtils { try { return new LdapName(distinguishedName); - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw convertLdapException(e); } } - private static LdapName returnOrConstructLdapNameFromName(Name name) { if (name instanceof LdapName) { return (LdapName) name; - } else { + } + else { return newLdapName(name); } } /** - * Remove the supplied path from the beginning the specified - * Name if the name instance starts with - * path. Useful for stripping base path suffix from a - * Name. The original Name will not be affected. - * + * Remove the supplied path from the beginning the specified Name if the + * name instance starts with path. Useful for stripping base path suffix + * from a Name. The original Name will not be affected. * @param dn the dn to strip from. * @param pathToRemove the path to remove from the beginning the dn instance. - * @return an LdapName instance that is a copy of the original name with the - * specified path stripped from its beginning. + * @return an LdapName instance that is a copy of the original name with the specified + * path stripped from its beginning. * @since 2.0 */ public static LdapName removeFirst(Name dn, Name pathToRemove) { @@ -445,14 +447,15 @@ public final class LdapUtils { LdapName result = newLdapName(dn); LdapName path = returnOrConstructLdapNameFromName(pathToRemove); - if(path.size() == 0 || !dn.startsWith(path)) { + if (path.size() == 0 || !dn.startsWith(path)) { return result; } - for(int i = 0; i < path.size(); i++) { + for (int i = 0; i < path.size(); i++) { try { result.remove(0); - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw convertLdapException(e); } } @@ -461,14 +464,13 @@ public final class LdapUtils { } /** - * Prepend the supplied path in the beginning the specified - * Name if the name instance starts with - * path. The original Name will not be affected. - * + * Prepend the supplied path in the beginning the specified Name if the + * name instance starts with path. The original Name will not be + * affected. * @param dn the dn to strip from. * @param pathToPrepend the path to prepend in the beginning of the dn. - * @return an LdapName instance that is a copy of the original name with the - * specified path inserted at its beginning. + * @return an LdapName instance that is a copy of the original name with the specified + * path inserted at its beginning. * @since 2.0 */ public static LdapName prepend(Name dn, Name pathToPrepend) { @@ -478,7 +480,8 @@ public final class LdapUtils { LdapName result = newLdapName(dn); try { result.addAll(0, pathToPrepend); - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw convertLdapException(e); } @@ -496,7 +499,6 @@ public final class LdapUtils { /** * Find the Rdn with the requested key in the supplied Name. - * * @param name the Name in which to search for the key. * @param key the attribute key to search for. * @return the rdn corresponding to the first occurrence of the requested key. @@ -514,7 +516,7 @@ public final class LdapUtils { NamingEnumeration ids = rdn.toAttributes().getIDs(); while (ids.hasMoreElements()) { String id = ids.nextElement(); - if(key.equalsIgnoreCase(id)) { + if (key.equalsIgnoreCase(id)) { return rdn; } } @@ -525,10 +527,10 @@ public final class LdapUtils { /** * Get the value of the Rdn with the requested key in the supplied Name. - * * @param name the Name in which to search for the key. * @param key the attribute key to search for. - * @return the value of the rdn corresponding to the first occurrence of the requested key. + * @return the value of the rdn corresponding to the first occurrence of the + * requested key. * @throws NoSuchElementException if no corresponding entry is found. * @since 2.0 */ @@ -536,10 +538,11 @@ public final class LdapUtils { NamingEnumeration allAttributes = getRdn(name, key).toAttributes().getAll(); while (allAttributes.hasMoreElements()) { Attribute oneAttribute = allAttributes.nextElement(); - if(key.equalsIgnoreCase(oneAttribute.getID())) { + if (key.equalsIgnoreCase(oneAttribute.getID())) { try { return oneAttribute.get(); - } catch (javax.naming.NamingException e) { + } + catch (javax.naming.NamingException e) { throw convertLdapException(e); } } @@ -551,9 +554,9 @@ public final class LdapUtils { /** * Get the value of the Rdn at the requested index in the supplied Name. - * * @param name the Name to work on. - * @param index The 0-based index of the rdn value to retrieve. Must be in the range [0,size()). + * @param index The 0-based index of the rdn value to retrieve. Must be in the range + * [0,size()). * @return the value of the rdn at the requested index. * @throws IndexOutOfBoundsException if index is outside the specified range. * @since 2.0 @@ -563,19 +566,19 @@ public final class LdapUtils { LdapName ldapName = returnOrConstructLdapNameFromName(name); Rdn rdn = ldapName.getRdn(index); - if(rdn.size() > 1) { - LOGGER.warn("Rdn at position " + index + " of dn '" + name + - "' is multi-value - returned value is not to be trusted. " + - "Consider using name-based getValue method instead"); + if (rdn.size() > 1) { + LOGGER.warn("Rdn at position " + index + " of dn '" + name + + "' is multi-value - returned value is not to be trusted. " + + "Consider using name-based getValue method instead"); } return rdn.getValue(); } /** * Get the value of the Rdn at the requested index in the supplied Name as a String. - * * @param name the Name to work on. - * @param index The 0-based index of the rdn value to retrieve. Must be in the range [0,size()). + * @param index The 0-based index of the rdn value to retrieve. Must be in the range + * [0,size()). * @return the value of the rdn at the requested index as a String. * @throws IndexOutOfBoundsException if index is outside the specified range. * @throws ClassCastException if the value of the requested component is not a String. @@ -587,10 +590,10 @@ public final class LdapUtils { /** * Get the value of the Rdn with the requested key in the supplied Name as a String. - * * @param name the Name in which to search for the key. * @param key the attribute key to search for. - * @return the String value of the rdn corresponding to the first occurrence of the requested key. + * @return the String value of the rdn corresponding to the first occurrence of + * the requested key. * @throws NoSuchElementException if no corresponding entry is found. * @throws ClassCastException if the value of the requested component is not a String. * @since 2.0 @@ -600,16 +603,16 @@ public final class LdapUtils { } /** - * Converts a binary SID to its String representation, according to the - * algorithm described here. Thanks to Eyal + * Converts a binary SID to its String representation, according to the algorithm + * described + * here. Thanks to + * Eyal * Lupu for algorithmic inspiration. - * + * *
     	 * If you have a SID like S-a-b-c-d-e-f-g-...
    -	 * 
    +	 *
     	 * Then the bytes are
     	 * a	(revision)
     	 * N	(number of dashes minus two)
    @@ -619,11 +622,11 @@ public final class LdapUtils {
     	 * eeee	(four bytes of "e" treated as a 32-bit number in little-endian format)
     	 * ffff	(four bytes of "f" treated as a 32-bit number in little-endian format)
     	 * etc.	
    -	 * 
    +	 *
     	 * So for example, if your SID is S-1-5-21-2127521184-1604012920-1887927527-72713, then your raw hex SID is
    -	 * 
    +	 *
     	 * 010500000000000515000000A065CF7E784B9B5FE77C8770091C0100
    -	 * 
    +	 *
     	 * This breaks down as follows:
     	 * 01	S-1
     	 * 05	(seven dashes, seven minus two = 5)
    @@ -633,14 +636,13 @@ public final class LdapUtils {
     	 * 784B9B5F	(1604012920 = 0x5F9B4B78, little-endian)
     	 * E77C8770	(1887927527 = 0X70877CE7, little-endian)
     	 * 091C0100	(72713 = 0x00011c09, little-endian)
    -	 * 
    +	 *
     	 * S-1-	version number (SID_REVISION)
     	 * -5-	SECURITY_NT_AUTHORITY
     	 * -21-	SECURITY_NT_NON_UNIQUE
     	 * -...-...-...-	these identify the machine that issued the SID
     	 * 72713	unique user id on the machine
     	 * 
    - * * @param sid binary SID in byte array format * @return String version of the given sid * @since 1.3.1 @@ -680,13 +682,12 @@ public final class LdapUtils { // That's it - we have the SID return sidAsString.toString(); } - + /** - * Converts a String SID to its binary representation, according to the - * algorithm described here. - * + * Converts a String SID to its binary representation, according to the algorithm + * described + * here. * @param string SID in readable format * @return Binary version of the given sid * @see LdapUtils#convertBinarySidToString(byte[]) @@ -697,7 +698,7 @@ public final class LdapUtils { byte sidRevision = (byte) Integer.parseInt(parts[1]); int subAuthCount = parts.length - 3; - byte[] sid = new byte[] {sidRevision, (byte) subAuthCount}; + byte[] sid = new byte[] { sidRevision, (byte) subAuthCount }; sid = addAll(sid, numberToBytes(parts[2], 6, true)); for (int i = 0; i < subAuthCount; i++) { sid = addAll(sid, numberToBytes(parts[3 + i], 4, false)); @@ -713,13 +714,12 @@ public final class LdapUtils { } /** - * Converts the given number to a binary representation of the specified - * length and "endian-ness". - * + * Converts the given number to a binary representation of the specified length and + * "endian-ness". * @param number String with number to convert * @param length How long the resulting binary array should be - * @param bigEndian true if big endian (5=0005), or - * false if little endian (5=5000) + * @param bigEndian true if big endian (5=0005), or false if + * little endian (5=5000) * @return byte array containing the binary result in the given order */ static byte[] numberToBytes(String number, int length, boolean bigEndian) { @@ -728,7 +728,8 @@ public final class LdapUtils { int remaining = length - bytes.length; if (remaining < 0) { bytes = Arrays.copyOfRange(bytes, -remaining, bytes.length); - } else { + } + else { byte[] fill = new byte[remaining]; bytes = addAll(fill, bytes); } @@ -752,9 +753,8 @@ public final class LdapUtils { } /** - * Converts a byte into its hexadecimal representation, padding with a - * leading zero to get an even number of characters. - * + * Converts a byte into its hexadecimal representation, padding with a leading zero to + * get an even number of characters. * @param b value to convert * @return hex string, possibly padded with a zero */ @@ -768,9 +768,8 @@ public final class LdapUtils { } /** - * Converts a byte array into its hexadecimal representation, padding each - * with a leading zero to get an even number of characters. - * + * Converts a byte array into its hexadecimal representation, padding each with a + * leading zero to get an even number of characters. * @param b values to convert * @return hex string, possibly with elements padded with a zero */ @@ -785,4 +784,5 @@ public final class LdapUtils { sb.append("}"); return sb.toString(); } + } diff --git a/core/src/main/java/org/springframework/ldap/support/ListComparator.java b/core/src/main/java/org/springframework/ldap/support/ListComparator.java index 05dc2e63..32341adc 100644 --- a/core/src/main/java/org/springframework/ldap/support/ListComparator.java +++ b/core/src/main/java/org/springframework/ldap/support/ListComparator.java @@ -21,19 +21,19 @@ import java.util.List; /** * Comparator for comparing lists of Comparable objects. - * + * * @author Mattias Hellborg Arthursson */ public class ListComparator implements Comparator, Serializable { + private static final long serialVersionUID = -3068381879731157178L; /** * Compare two lists of Comparable objects. - * * @param o1 the first object to be compared. * @param o2 the second object to be compared. - * @throws ClassCastException if any of the lists contains an object that - * is not Comparable. + * @throws ClassCastException if any of the lists contains an object that is not + * Comparable. */ public int compare(Object o1, Object o2) { List list1 = (List) o1; @@ -64,4 +64,5 @@ public class ListComparator implements Comparator, Serializable { return 0; } } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/BindOperationExecutor.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/BindOperationExecutor.java index 391ee712..4a9f55ae 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/BindOperationExecutor.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/BindOperationExecutor.java @@ -24,15 +24,15 @@ import javax.naming.Name; import javax.naming.directory.Attributes; /** - * A {@link CompensatingTransactionOperationExecutor} to manage a bind - * operation. Performs a bind in {@link #performOperation()}, a corresponding - * unbind in {@link #rollback()}, and nothing in {@link #commit()}. - * + * A {@link CompensatingTransactionOperationExecutor} to manage a bind operation. Performs + * a bind in {@link #performOperation()}, a corresponding unbind in {@link #rollback()}, + * and nothing in {@link #commit()}. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class BindOperationExecutor implements - CompensatingTransactionOperationExecutor { +public class BindOperationExecutor implements CompensatingTransactionOperationExecutor { + private static Logger log = LoggerFactory.getLogger(BindOperationExecutor.class); private LdapOperations ldapOperations; @@ -45,21 +45,16 @@ public class BindOperationExecutor implements /** * Constructor. - * - * @param ldapOperations - * {@link LdapOperations} to use for performing the rollback - * operation. - * @param dn - * DN of the entry to be unbound. - * @param originalObject - * original value sent to the 'object' parameter of the bind - * operation. - * @param originalAttributes - * original value sent to the 'attributes' parameter of the bind - * operation. + * @param ldapOperations {@link LdapOperations} to use for performing the rollback + * operation. + * @param dn DN of the entry to be unbound. + * @param originalObject original value sent to the 'object' parameter of the bind + * operation. + * @param originalAttributes original value sent to the 'attributes' parameter of the + * bind operation. */ - public BindOperationExecutor(LdapOperations ldapOperations, Name dn, - Object originalObject, Attributes originalAttributes) { + public BindOperationExecutor(LdapOperations ldapOperations, Name dn, Object originalObject, + Attributes originalAttributes) { this.ldapOperations = ldapOperations; this.dn = dn; this.originalObject = originalObject; @@ -68,21 +63,24 @@ public class BindOperationExecutor implements /* * (non-Javadoc) - * - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#rollback() + * + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#rollback() */ public void rollback() { try { ldapOperations.unbind(dn); - } catch (Exception e) { + } + catch (Exception e) { log.warn("Failed to rollback, dn:" + dn.toString(), e); } } /* * (non-Javadoc) - * - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#commit() + * + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#commit() */ public void commit() { log.debug("Nothing to do in commit for bind operation"); @@ -90,8 +88,9 @@ public class BindOperationExecutor implements /* * (non-Javadoc) - * - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#performOperation() + * + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#performOperation() */ public void performOperation() { log.debug("Performing bind operation"); @@ -100,7 +99,6 @@ public class BindOperationExecutor implements /** * Get the DN. Package private for testing purposes. - * * @return the target DN. */ Name getDn() { @@ -109,7 +107,6 @@ public class BindOperationExecutor implements /** * Get the LdapOperations. Package private for testing purposes. - * * @return the LdapOperations. */ LdapOperations getLdapOperations() { diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/BindOperationRecorder.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/BindOperationRecorder.java index 29efa0af..d53552f5 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/BindOperationRecorder.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/BindOperationRecorder.java @@ -23,45 +23,40 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; /** - * A {@link CompensatingTransactionOperationRecorder} keeping track of bind - * operations. Creates {@link BindOperationExecutor} objects in - * {@link #recordOperation(Object[])}. - * + * A {@link CompensatingTransactionOperationRecorder} keeping track of bind operations. + * Creates {@link BindOperationExecutor} objects in {@link #recordOperation(Object[])}. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class BindOperationRecorder implements - CompensatingTransactionOperationRecorder { +public class BindOperationRecorder implements CompensatingTransactionOperationRecorder { private LdapOperations ldapOperations; /** * Constructor. - * - * @param ldapOperations - * {@link LdapOperations} to use for supplying to the - * corresponding rollback operation. + * @param ldapOperations {@link LdapOperations} to use for supplying to the + * corresponding rollback operation. */ public BindOperationRecorder(LdapOperations ldapOperations) { this.ldapOperations = ldapOperations; } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { + public CompensatingTransactionOperationExecutor recordOperation(Object[] args) { if (args == null || args.length != 3) { - throw new IllegalArgumentException( - "Invalid arguments for bind operation"); + throw new IllegalArgumentException("Invalid arguments for bind operation"); } Name dn = LdapTransactionUtils.getFirstArgumentAsName(args); Object object = args[1]; Attributes attributes = null; if (args[2] != null && !(args[2] instanceof Attributes)) { - throw new IllegalArgumentException( - "Invalid third argument to bind operation"); - } else if (args[2] != null) { + throw new IllegalArgumentException("Invalid third argument to bind operation"); + } + else if (args[2] != null) { attributes = (Attributes) args[2]; } @@ -70,10 +65,10 @@ public class BindOperationRecorder implements /** * Get the LdapOperations. For testing purposes.s - * * @return the LdapOperations. */ LdapOperations getLdapOperations() { return ldapOperations; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactory.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactory.java index dd6be6a4..e9581126 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactory.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactory.java @@ -15,7 +15,6 @@ */ package org.springframework.ldap.transaction.compensating; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.ldap.core.LdapOperations; @@ -28,22 +27,21 @@ import org.springframework.util.ObjectUtils; import javax.naming.directory.DirContext; /** - * {@link CompensatingTransactionOperationRecorder} implementation for LDAP - * operations. - * + * {@link CompensatingTransactionOperationRecorder} implementation for LDAP operations. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ public class LdapCompensatingTransactionOperationFactory implements CompensatingTransactionOperationFactory { + private static Logger log = LoggerFactory.getLogger(LdapCompensatingTransactionOperationFactory.class); private TempEntryRenamingStrategy renamingStrategy; /** * Constructor. - * - * @param renamingStrategy the {@link TempEntryRenamingStrategy} to supply - * to relevant operations. + * @param renamingStrategy the {@link TempEntryRenamingStrategy} to supply to relevant + * operations. */ public LdapCompensatingTransactionOperationFactory(TempEntryRenamingStrategy renamingStrategy) { this.renamingStrategy = renamingStrategy; @@ -51,8 +49,8 @@ public class LdapCompensatingTransactionOperationFactory implements Compensating /* * @see org.springframework.transaction.compensating. - * CompensatingTransactionOperationFactory - * #createRecordingOperation(java.lang.Object, java.lang.String) + * CompensatingTransactionOperationFactory #createRecordingOperation(java.lang.Object, + * java.lang.String) */ public CompensatingTransactionOperationRecorder createRecordingOperation(Object resource, String operation) { if (ObjectUtils.nullSafeEquals(operation, LdapTransactionUtils.BIND_METHOD_NAME)) { @@ -82,4 +80,5 @@ public class LdapCompensatingTransactionOperationFactory implements Compensating LdapOperations createLdapOperationsInstance(DirContext ctx) { return new LdapTemplate(new SingleContextSource(ctx)); } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtils.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtils.java index b022ff02..2600c9fb 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtils.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtils.java @@ -23,7 +23,7 @@ import javax.naming.Name; /** * Utility methods for working with LDAP transactions. - * + * * @author Mattias Hellborg Arthursson * @since 1.2 */ @@ -48,11 +48,9 @@ public final class LdapTransactionUtils { /** * Get the first parameter in the argument list as a Name. - * - * @param args - * arguments supplied to a ldap operation. - * @return a Name representation of the first argument, or the Name itself - * if it is a name. + * @param args arguments supplied to a ldap operation. + * @return a Name representation of the first argument, or the Name itself if it is a + * name. */ public static Name getFirstArgumentAsName(Object[] args) { Assert.notEmpty(args); @@ -63,31 +61,27 @@ public final class LdapTransactionUtils { /** * Get the argument as a Name. - * - * @param arg - * an argument supplied to an Ldap operation. - * @return a Name representation of the argument, or the Name itself if it - * is a Name. + * @param arg an argument supplied to an Ldap operation. + * @return a Name representation of the argument, or the Name itself if it is a Name. */ public static Name getArgumentAsName(Object arg) { if (arg instanceof String) { return LdapUtils.newLdapName((String) arg); - } else if (arg instanceof Name) { + } + else if (arg instanceof Name) { return (Name) arg; - } else { - throw new IllegalArgumentException( - "First argument needs to be a Name or a String representation thereof"); + } + else { + throw new IllegalArgumentException("First argument needs to be a Name or a String representation thereof"); } } /** - * Check whether the supplied method is a method for which transactions is - * supported (and which should be recorded for possible rollback later). - * - * @param methodName - * name of the method to check. + * Check whether the supplied method is a method for which transactions is supported + * (and which should be recorded for possible rollback later). + * @param methodName name of the method to check. * @return true if this is a supported transaction operation, - * false otherwise. + * false otherwise. */ public static boolean isSupportedWriteTransactionOperation(String methodName) { return (ObjectUtils.nullSafeEquals(methodName, BIND_METHOD_NAME) @@ -97,4 +91,5 @@ public final class LdapTransactionUtils { || ObjectUtils.nullSafeEquals(methodName, UNBIND_METHOD_NAME)); } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutor.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutor.java index a85c11ce..0ede0c4b 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutor.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutor.java @@ -25,15 +25,14 @@ import javax.naming.directory.ModificationItem; /** * A {@link CompensatingTransactionOperationExecutor} to manage a - * modifyAttributes operation. Performs a - * modifyAttributes in {@link #performOperation()}, a negating - * modifyAttributes in {@link #rollback()}, and nothing in {@link #commit()}. - * + * modifyAttributes operation. Performs a modifyAttributes in + * {@link #performOperation()}, a negating modifyAttributes in {@link #rollback()}, and + * nothing in {@link #commit()}. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class ModifyAttributesOperationExecutor implements - CompensatingTransactionOperationExecutor { +public class ModifyAttributesOperationExecutor implements CompensatingTransactionOperationExecutor { private static Logger log = LoggerFactory.getLogger(ModifyAttributesOperationExecutor.class); @@ -47,21 +46,16 @@ public class ModifyAttributesOperationExecutor implements /** * Constructor. - * - * @param ldapOperations - * The {@link LdapOperations} to use to perform the rollback - * operation. - * @param dn - * the DN of the target entry. - * @param actualModifications - * the actual modificationItems that were sent to the - * modifyAttributes operation. - * @param compensatingModifications - * the ModificationItems to undo the recorded operation. + * @param ldapOperations The {@link LdapOperations} to use to perform the rollback + * operation. + * @param dn the DN of the target entry. + * @param actualModifications the actual modificationItems that were sent to the + * modifyAttributes operation. + * @param compensatingModifications the ModificationItems to undo the recorded + * operation. */ - public ModifyAttributesOperationExecutor(LdapOperations ldapOperations, - Name dn, ModificationItem[] actualModifications, - ModificationItem[] compensatingModifications) { + public ModifyAttributesOperationExecutor(LdapOperations ldapOperations, Name dn, + ModificationItem[] actualModifications, ModificationItem[] compensatingModifications) { this.ldapOperations = ldapOperations; this.dn = dn; this.actualModifications = actualModifications.clone(); @@ -69,28 +63,30 @@ public class ModifyAttributesOperationExecutor implements } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#rollback() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#rollback() */ public void rollback() { try { log.debug("Rolling back modifyAttributes operation"); ldapOperations.modifyAttributes(dn, compensatingModifications); - } catch (Exception e) { - log - .warn("Failed to rollback ModifyAttributes operation, dn: " - + dn); + } + catch (Exception e) { + log.warn("Failed to rollback ModifyAttributes operation, dn: " + dn); } } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#commit() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#commit() */ public void commit() { log.debug("Nothing to do in commit for modifyAttributes"); } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#performOperation() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#performOperation() */ public void performOperation() { log.debug("Performing modifyAttributes operation"); @@ -112,4 +108,5 @@ public class ModifyAttributesOperationExecutor implements ModificationItem[] getCompensatingModifications() { return compensatingModifications; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorder.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorder.java index f9035c73..034ddbdc 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorder.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorder.java @@ -34,15 +34,14 @@ import java.util.HashSet; import java.util.Set; /** - * A {@link CompensatingTransactionOperationRecorder} keeping track of - * modifyAttributes operations, creating corresponding - * {@link ModifyAttributesOperationExecutor} instances for rollback. - * + * A {@link CompensatingTransactionOperationRecorder} keeping track of modifyAttributes + * operations, creating corresponding {@link ModifyAttributesOperationExecutor} instances + * for rollback. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class ModifyAttributesOperationRecorder implements - CompensatingTransactionOperationRecorder { +public class ModifyAttributesOperationRecorder implements CompensatingTransactionOperationRecorder { private LdapOperations ldapOperations; @@ -51,15 +50,14 @@ public class ModifyAttributesOperationRecorder implements } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { + public CompensatingTransactionOperationExecutor recordOperation(Object[] args) { Assert.notNull(args); Name dn = LdapTransactionUtils.getFirstArgumentAsName(args); if (args.length != 2 || !(args[1] instanceof ModificationItem[])) { - throw new IllegalArgumentException( - "Unexpected arguments to ModifyAttributes operation"); + throw new IllegalArgumentException("Unexpected arguments to ModifyAttributes operation"); } ModificationItem[] incomingModifications = (ModificationItem[]) args[1]; @@ -73,7 +71,8 @@ public class ModifyAttributesOperationRecorder implements String[] attributeNameArray = set.toArray(new String[set.size()]); // LDAP-234: We need to explicitly an IncrementalAttributesMapper in - // case we're working against AD and there are too many attribute values to be returned + // case we're working against AD and there are too many attribute values to be + // returned // by one query. IncrementalAttributesMapper attributesMapper = getAttributesMapper(attributeNameArray); while (attributesMapper.hasMore()) { @@ -86,20 +85,16 @@ public class ModifyAttributesOperationRecorder implements // modification. ModificationItem[] rollbackItems = new ModificationItem[incomingModifications.length]; for (int i = 0; i < incomingModifications.length; i++) { - rollbackItems[i] = getCompensatingModificationItem( - currentAttributes, incomingModifications[i]); + rollbackItems[i] = getCompensatingModificationItem(currentAttributes, incomingModifications[i]); } - return new ModifyAttributesOperationExecutor(ldapOperations, dn, - incomingModifications, rollbackItems); + return new ModifyAttributesOperationExecutor(ldapOperations, dn, incomingModifications, rollbackItems); } /** - * Get an {@link AttributesMapper} that just returns the supplied - * Attributes. - * - * @return the {@link AttributesMapper} to use for getting the current - * Attributes of the target DN. + * Get an {@link AttributesMapper} that just returns the supplied Attributes. + * @return the {@link AttributesMapper} to use for getting the current Attributes of + * the target DN. */ IncrementalAttributesMapper getAttributesMapper(String[] attributeNames) { return new DefaultIncrementalAttributesMapper(attributeNames); @@ -107,57 +102,53 @@ public class ModifyAttributesOperationRecorder implements /** * Get a ModificationItem to use for rollback of the supplied modification. - * - * @param originalAttributes - * All Attributes of the target DN that are affected of any of - * the ModificationItems. - * @param modificationItem - * the ModificationItem to create a rollback item for. - * @return A ModificationItem to use for rollback of the supplied - * ModificationItem. + * @param originalAttributes All Attributes of the target DN that are affected of any + * of the ModificationItems. + * @param modificationItem the ModificationItem to create a rollback item for. + * @return A ModificationItem to use for rollback of the supplied ModificationItem. */ - protected ModificationItem getCompensatingModificationItem( - Attributes originalAttributes, ModificationItem modificationItem) { + protected ModificationItem getCompensatingModificationItem(Attributes originalAttributes, + ModificationItem modificationItem) { Attribute modificationAttribute = modificationItem.getAttribute(); - Attribute originalAttribute = originalAttributes - .get(modificationAttribute.getID()); + Attribute originalAttribute = originalAttributes.get(modificationAttribute.getID()); if (modificationItem.getModificationOp() == DirContext.REMOVE_ATTRIBUTE) { if (modificationAttribute.size() == 0) { // If the modification attribute size it means that the // Attribute should be removed entirely - we should store a // ModificationItem to restore all present values for rollback. - return new ModificationItem(DirContext.ADD_ATTRIBUTE, - (Attribute) originalAttribute.clone()); - } else { + return new ModificationItem(DirContext.ADD_ATTRIBUTE, (Attribute) originalAttribute.clone()); + } + else { // The rollback modification will be to re-add the removed // attribute values. - return new ModificationItem(DirContext.ADD_ATTRIBUTE, - (Attribute) modificationAttribute.clone()); + return new ModificationItem(DirContext.ADD_ATTRIBUTE, (Attribute) modificationAttribute.clone()); } - } else if (modificationItem.getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { + } + else if (modificationItem.getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { if (originalAttribute != null) { - return new ModificationItem(DirContext.REPLACE_ATTRIBUTE, - (Attribute) originalAttribute.clone()); - } else { + return new ModificationItem(DirContext.REPLACE_ATTRIBUTE, (Attribute) originalAttribute.clone()); + } + else { // The attribute doesn't previously exist - the rollback // operation will be to remove the attribute. return new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(modificationAttribute.getID())); } - } else { + } + else { // An ADD_ATTRIBUTE operation if (originalAttribute == null) { // The attribute doesn't previously exist - the rollback // operation will be to remove the attribute. return new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute(modificationAttribute.getID())); - } else { + } + else { // The attribute does exist before - we should store the // previous value and it should be used for replacing in // rollback. - return new ModificationItem(DirContext.REPLACE_ATTRIBUTE, - (Attribute) originalAttribute.clone()); + return new ModificationItem(DirContext.REPLACE_ATTRIBUTE, (Attribute) originalAttribute.clone()); } } } @@ -165,4 +156,5 @@ public class ModifyAttributesOperationRecorder implements LdapOperations getLdapOperations() { return ldapOperations; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/NullOperationExecutor.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/NullOperationExecutor.java index f4effbfd..9cf1f9ea 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/NullOperationExecutor.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/NullOperationExecutor.java @@ -21,17 +21,17 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera /** * A {@link CompensatingTransactionOperationExecutor} that performs nothing. - * + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class NullOperationExecutor implements - CompensatingTransactionOperationExecutor { +public class NullOperationExecutor implements CompensatingTransactionOperationExecutor { private static Logger log = LoggerFactory.getLogger(NullOperationExecutor.class); /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#rollback() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#rollback() */ public void rollback() { log.info("Rolling back null operation"); @@ -44,4 +44,5 @@ public class NullOperationExecutor implements public void performOperation() { log.info("Performing null operation"); } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/NullOperationRecorder.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/NullOperationRecorder.java index 2590e70b..ac574399 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/NullOperationRecorder.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/NullOperationRecorder.java @@ -20,24 +20,22 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; /** - * A {@link CompensatingTransactionOperationRecorder} performing nothing, - * returning a {@link NullOperationExecutor} regardless of the input. Instances - * of this class will be created if the - * {@link CompensatingTransactionOperationManager} cannot determine any - * appropriate {@link CompensatingTransactionOperationRecorder} for the current - * operation. - * + * A {@link CompensatingTransactionOperationRecorder} performing nothing, returning a + * {@link NullOperationExecutor} regardless of the input. Instances of this class will be + * created if the {@link CompensatingTransactionOperationManager} cannot determine any + * appropriate {@link CompensatingTransactionOperationRecorder} for the current operation. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class NullOperationRecorder implements - CompensatingTransactionOperationRecorder { +public class NullOperationRecorder implements CompensatingTransactionOperationRecorder { /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { + public CompensatingTransactionOperationExecutor recordOperation(Object[] args) { return new NullOperationExecutor(); } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutor.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutor.java index 6f9d4b63..b80eb5bd 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutor.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutor.java @@ -24,20 +24,18 @@ import javax.naming.Name; import javax.naming.directory.Attributes; /** - * A {@link CompensatingTransactionOperationExecutor} to manage a rebind - * operation. The methods in this class do not behave as expected, since it - * might be impossible to retrieve all the original attributes from the entry. - * Instead this class performs a rename in {@link #performOperation()}, - * a negating rename in {@link #rollback()}, and the {@link #commit()} - * operation unbinds the original entry from its temporary location and binds a - * new entry to the original location using the attributes supplied to the - * original rebind opertaion. - * + * A {@link CompensatingTransactionOperationExecutor} to manage a rebind operation. The + * methods in this class do not behave as expected, since it might be impossible to + * retrieve all the original attributes from the entry. Instead this class performs a + * rename in {@link #performOperation()}, a negating rename in {@link #rollback()}, + * and the {@link #commit()} operation unbinds the original entry from its temporary + * location and binds a new entry to the original location using the attributes supplied + * to the original rebind opertaion. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class RebindOperationExecutor implements - CompensatingTransactionOperationExecutor { +public class RebindOperationExecutor implements CompensatingTransactionOperationExecutor { private static Logger log = LoggerFactory.getLogger(RebindOperationExecutor.class); @@ -53,21 +51,15 @@ public class RebindOperationExecutor implements /** * Constructor. - * - * @param ldapOperations - * the {@link LdapOperations} to use to perform the rollback. - * @param originalDn - * The original DN of the entry to bind. - * @param temporaryDn - * The temporary DN of the entry. - * @param originalObject - * Original 'object' parameter sent to the rebind operation. - * @param originalAttributes - * Original 'attributes' parameter sent to the rebind operation + * @param ldapOperations the {@link LdapOperations} to use to perform the rollback. + * @param originalDn The original DN of the entry to bind. + * @param temporaryDn The temporary DN of the entry. + * @param originalObject Original 'object' parameter sent to the rebind operation. + * @param originalAttributes Original 'attributes' parameter sent to the rebind + * operation */ - public RebindOperationExecutor(LdapOperations ldapOperations, - Name originalDn, Name temporaryDn, Object originalObject, - Attributes originalAttributes) { + public RebindOperationExecutor(LdapOperations ldapOperations, Name originalDn, Name temporaryDn, + Object originalObject, Attributes originalAttributes) { this.ldapOperations = ldapOperations; this.originalDn = originalDn; this.temporaryDn = temporaryDn; @@ -77,7 +69,6 @@ public class RebindOperationExecutor implements /** * Get the LdapOperations. Package private for testing purposes. - * * @return the LdapOperations. */ LdapOperations getLdapOperations() { @@ -85,21 +76,23 @@ public class RebindOperationExecutor implements } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#rollback() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#rollback() */ public void rollback() { log.debug("Rolling back rebind operation"); try { ldapOperations.unbind(originalDn); ldapOperations.rename(temporaryDn, originalDn); - } catch (Exception e) { - log.warn("Failed to rollback operation, dn: " + originalDn - + "; temporary DN: " + temporaryDn, e); + } + catch (Exception e) { + log.warn("Failed to rollback operation, dn: " + originalDn + "; temporary DN: " + temporaryDn, e); } } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#commit() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#commit() */ public void commit() { log.debug("Committing rebind operation"); @@ -107,12 +100,11 @@ public class RebindOperationExecutor implements } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#performOperation() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#performOperation() */ public void performOperation() { - log.debug("Performing rebind operation - " - + "renaming original entry and " - + "binding new contents to entry."); + log.debug("Performing rebind operation - " + "renaming original entry and " + "binding new contents to entry."); ldapOperations.rename(originalDn, temporaryDn); ldapOperations.bind(originalDn, originalObject, originalAttributes); } @@ -132,4 +124,5 @@ public class RebindOperationExecutor implements Name getTemporaryDn() { return temporaryDn; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorder.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorder.java index a991c007..4b4f629f 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorder.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorder.java @@ -23,15 +23,13 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; /** - * A {@link CompensatingTransactionOperationRecorder} keeping track of a rebind - * operation. Creates {@link RebindOperationExecutor} objects in - * {@link #recordOperation(Object[])}. - * + * A {@link CompensatingTransactionOperationRecorder} keeping track of a rebind operation. + * Creates {@link RebindOperationExecutor} objects in {@link #recordOperation(Object[])}. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class RebindOperationRecorder implements - CompensatingTransactionOperationRecorder { +public class RebindOperationRecorder implements CompensatingTransactionOperationRecorder { private LdapOperations ldapOperations; @@ -39,48 +37,41 @@ public class RebindOperationRecorder implements /** * Constructor. - * - * @param ldapOperations - * {@link LdapOperations} to use for getting the rollback - * information and supply to the {@link RebindOperationExecutor}. - * @param renamingStrategy - * {@link TempEntryRenamingStrategy} to use for generating temp - * DNs. + * @param ldapOperations {@link LdapOperations} to use for getting the rollback + * information and supply to the {@link RebindOperationExecutor}. + * @param renamingStrategy {@link TempEntryRenamingStrategy} to use for generating + * temp DNs. */ - public RebindOperationRecorder(LdapOperations ldapOperations, - TempEntryRenamingStrategy renamingStrategy) { + public RebindOperationRecorder(LdapOperations ldapOperations, TempEntryRenamingStrategy renamingStrategy) { this.ldapOperations = ldapOperations; this.renamingStrategy = renamingStrategy; } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { + public CompensatingTransactionOperationExecutor recordOperation(Object[] args) { if (args == null || args.length != 3) { - throw new IllegalArgumentException( - "Invalid arguments for bind operation"); + throw new IllegalArgumentException("Invalid arguments for bind operation"); } Name dn = LdapTransactionUtils.getFirstArgumentAsName(args); Object object = args[1]; Attributes attributes = null; if (args[2] != null && !(args[2] instanceof Attributes)) { - throw new IllegalArgumentException( - "Invalid third argument to bind operation"); - } else if (args[2] != null) { + throw new IllegalArgumentException("Invalid third argument to bind operation"); + } + else if (args[2] != null) { attributes = (Attributes) args[2]; } Name temporaryName = renamingStrategy.getTemporaryName(dn); - return new RebindOperationExecutor(ldapOperations, dn, temporaryName, - object, attributes); + return new RebindOperationExecutor(ldapOperations, dn, temporaryName, object, attributes); } /** * Get the LdapOperations. For testing purposes. - * * @return the LdapOperations. */ LdapOperations getLdapOperations() { @@ -90,4 +81,5 @@ public class RebindOperationRecorder implements public TempEntryRenamingStrategy getRenamingStrategy() { return renamingStrategy; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutor.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutor.java index bc867e8d..61e3717f 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutor.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutor.java @@ -23,15 +23,14 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera import javax.naming.Name; /** - * A {@link CompensatingTransactionOperationExecutor} to manage a rename - * operation. Performs a rename operation in {@link #performOperation()}, a - * negating rename in {@link #rollback()}, and nothing in {@link #commit()}. - * + * A {@link CompensatingTransactionOperationExecutor} to manage a rename operation. + * Performs a rename operation in {@link #performOperation()}, a negating rename in + * {@link #rollback()}, and nothing in {@link #commit()}. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class RenameOperationExecutor implements - CompensatingTransactionOperationExecutor { +public class RenameOperationExecutor implements CompensatingTransactionOperationExecutor { private static Logger log = LoggerFactory.getLogger(RenameOperationExecutor.class); @@ -43,44 +42,42 @@ public class RenameOperationExecutor implements /** * Constructor. - * - * @param ldapOperations - * The {@link LdapOperations} to use for performing the rollback - * operation. - * @param originalDn - * DN that the entry was moved from in the recorded operation. - * @param newDn - * DN that the entry has been moved to in the recorded operation. + * @param ldapOperations The {@link LdapOperations} to use for performing the rollback + * operation. + * @param originalDn DN that the entry was moved from in the recorded operation. + * @param newDn DN that the entry has been moved to in the recorded operation. */ - public RenameOperationExecutor(LdapOperations ldapOperations, - Name originalDn, Name newDn) { + public RenameOperationExecutor(LdapOperations ldapOperations, Name originalDn, Name newDn) { this.ldapOperations = ldapOperations; this.originalDn = originalDn; this.newDn = newDn; } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#rollback() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#rollback() */ public void rollback() { log.debug("Rolling back rename operation"); try { ldapOperations.rename(newDn, originalDn); - } catch (Exception e) { - log.warn("Unable to rollback rename operation. " + "originalDn: " - + newDn + "; newDn: " + originalDn); + } + catch (Exception e) { + log.warn("Unable to rollback rename operation. " + "originalDn: " + newDn + "; newDn: " + originalDn); } } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#commit() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#commit() */ public void commit() { log.debug("Nothing to do in commit for rename operation"); } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#performOperation() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#performOperation() */ public void performOperation() { log.debug("Performing rename operation"); @@ -98,4 +95,5 @@ public class RenameOperationExecutor implements Name getOriginalDn() { return originalDn; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorder.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorder.java index 63a04072..a09ff222 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorder.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorder.java @@ -25,15 +25,13 @@ import org.springframework.util.Assert; import javax.naming.Name; /** - * A {@link CompensatingTransactionOperationRecorder} for keeping track of - * rename operations. Creates {@link RenameOperationExecutor} objects for - * rolling back. - * + * A {@link CompensatingTransactionOperationRecorder} for keeping track of rename + * operations. Creates {@link RenameOperationExecutor} objects for rolling back. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class RenameOperationRecorder implements - CompensatingTransactionOperationRecorder { +public class RenameOperationRecorder implements CompensatingTransactionOperationRecorder { private static Logger log = LoggerFactory.getLogger(RenameOperationRecorder.class); @@ -41,20 +39,18 @@ public class RenameOperationRecorder implements /** * Constructor. - * - * @param ldapOperations - * The {@link LdapOperations} to supply to the created - * {@link RebindOperationExecutor} objects. + * @param ldapOperations The {@link LdapOperations} to supply to the created + * {@link RebindOperationExecutor} objects. */ public RenameOperationRecorder(LdapOperations ldapOperations) { this.ldapOperations = ldapOperations; } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { + public CompensatingTransactionOperationExecutor recordOperation(Object[] args) { log.debug("Storing rollback information for rename operation"); Assert.notEmpty(args); if (args.length != 2) { @@ -69,4 +65,5 @@ public class RenameOperationRecorder implements LdapOperations getLdapOperations() { return ldapOperations; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/TempEntryRenamingStrategy.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/TempEntryRenamingStrategy.java index 5221bebb..25cc8721 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/TempEntryRenamingStrategy.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/TempEntryRenamingStrategy.java @@ -18,9 +18,9 @@ package org.springframework.ldap.transaction.compensating; import javax.naming.Name; /** - * Interface for different strategies to rename temporary entries for unbind and - * rebind operations. - * + * Interface for different strategies to rename temporary entries for unbind and rebind + * operations. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ @@ -28,11 +28,10 @@ public interface TempEntryRenamingStrategy { /** * Get a temporary name for the current entry to be renamed to. - * - * @param originalName - * The original name of the entry. - * @return The name to which the entry should be temporarily renamed - * according to this strategy. + * @param originalName The original name of the entry. + * @return The name to which the entry should be temporarily renamed according to this + * strategy. */ Name getTemporaryName(Name originalName); + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutor.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutor.java index 24439eb2..ad2a89ea 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutor.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutor.java @@ -23,18 +23,16 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera import javax.naming.Name; /** - * A {@link CompensatingTransactionOperationExecutor} to manage an unbind - * operation. The methods in this class do not behave as expected, since it - * might be impossible to retrieve all the original attributes from the entry. - * Instead this class performs a rename in {@link #performOperation()}, - * a negating rename in {@link #rollback()}, and {@link #commit()} unbinds the - * entry from its temporary location. - * + * A {@link CompensatingTransactionOperationExecutor} to manage an unbind operation. The + * methods in this class do not behave as expected, since it might be impossible to + * retrieve all the original attributes from the entry. Instead this class performs a + * rename in {@link #performOperation()}, a negating rename in {@link #rollback()}, + * and {@link #commit()} unbinds the entry from its temporary location. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class UnbindOperationExecutor implements - CompensatingTransactionOperationExecutor { +public class UnbindOperationExecutor implements CompensatingTransactionOperationExecutor { private static Logger log = LoggerFactory.getLogger(UnbindOperationExecutor.class); @@ -46,37 +44,34 @@ public class UnbindOperationExecutor implements /** * Constructor. - * - * @param ldapOperations - * The {@link LdapOperations} to use for performing the rollback - * operation. - * @param originalDn - * The original DN of the entry to be removed. - * @param temporaryDn - * Temporary DN of the entry to be removed; this is where the - * entry is temporarily stored during the transaction. + * @param ldapOperations The {@link LdapOperations} to use for performing the rollback + * operation. + * @param originalDn The original DN of the entry to be removed. + * @param temporaryDn Temporary DN of the entry to be removed; this is where the entry + * is temporarily stored during the transaction. */ - public UnbindOperationExecutor(LdapOperations ldapOperations, - Name originalDn, Name temporaryDn) { + public UnbindOperationExecutor(LdapOperations ldapOperations, Name originalDn, Name temporaryDn) { this.ldapOperations = ldapOperations; this.originalDn = originalDn; this.temporaryDn = temporaryDn; } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#rollback() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#rollback() */ public void rollback() { try { ldapOperations.rename(temporaryDn, originalDn); - } catch (Exception e) { - log.warn("Filed to rollback unbind operation, temporaryDn: " - + temporaryDn + "; originalDn: " + originalDn); + } + catch (Exception e) { + log.warn("Filed to rollback unbind operation, temporaryDn: " + temporaryDn + "; originalDn: " + originalDn); } } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#commit() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#commit() */ public void commit() { log.debug("Committing unbind operation - unbinding temporary entry"); @@ -84,11 +79,11 @@ public class UnbindOperationExecutor implements } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationExecutor#performOperation() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationExecutor#performOperation() */ public void performOperation() { - log.debug("Performing operation for unbind -" - + " renaming to temporary entry."); + log.debug("Performing operation for unbind -" + " renaming to temporary entry."); ldapOperations.rename(originalDn, temporaryDn); } @@ -103,4 +98,5 @@ public class UnbindOperationExecutor implements Name getTemporaryDn() { return temporaryDn; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorder.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorder.java index a8a95016..ee013b05 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorder.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorder.java @@ -22,15 +22,13 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; /** - * {@link CompensatingTransactionOperationRecorder} to keep track of unbind - * operations. This class creates {@link UnbindOperationExecutor} objects for - * rollback. - * + * {@link CompensatingTransactionOperationRecorder} to keep track of unbind operations. + * This class creates {@link UnbindOperationExecutor} objects for rollback. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class UnbindOperationRecorder implements - CompensatingTransactionOperationRecorder { +public class UnbindOperationRecorder implements CompensatingTransactionOperationRecorder { private LdapOperations ldapOperations; @@ -38,26 +36,22 @@ public class UnbindOperationRecorder implements /** * Constructor. - * - * @param ldapOperations - * {@link LdapOperations} to use for getting the data prior to - * unbinding the entry and to supply to the - * {@link UnbindOperationExecutor} for rollback. - * @param renamingStrategy - * the {@link TempEntryRenamingStrategy} to use when generating - * DNs for temporary entries. + * @param ldapOperations {@link LdapOperations} to use for getting the data prior to + * unbinding the entry and to supply to the {@link UnbindOperationExecutor} for + * rollback. + * @param renamingStrategy the {@link TempEntryRenamingStrategy} to use when + * generating DNs for temporary entries. */ - public UnbindOperationRecorder(LdapOperations ldapOperations, - TempEntryRenamingStrategy renamingStrategy) { + public UnbindOperationRecorder(LdapOperations ldapOperations, TempEntryRenamingStrategy renamingStrategy) { this.ldapOperations = ldapOperations; this.renamingStrategy = renamingStrategy; } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { + public CompensatingTransactionOperationExecutor recordOperation(Object[] args) { Name dn = LdapTransactionUtils.getFirstArgumentAsName(args); Name temporaryDn = renamingStrategy.getTemporaryName(dn); @@ -71,4 +65,5 @@ public class UnbindOperationRecorder implements public TempEntryRenamingStrategy getRenamingStrategy() { return renamingStrategy; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceAndDataSourceTransactionManager.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceAndDataSourceTransactionManager.java index b03fae66..9246acc6 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceAndDataSourceTransactionManager.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceAndDataSourceTransactionManager.java @@ -25,20 +25,20 @@ import org.springframework.transaction.TransactionSuspensionNotSupportedExceptio import org.springframework.transaction.support.DefaultTransactionStatus; /** - * A Transaction Manager to manage LDAP and JDBC operations within the same - * transaction. Note that even though the same logical transaction is used, this - * is not a JTA XA transaction; no two-phase commit will be performed, - * and thus commit and rollback may yield unexpected results. - * + * A Transaction Manager to manage LDAP and JDBC operations within the same transaction. + * Note that even though the same logical transaction is used, this is not a JTA XA + * transaction; no two-phase commit will be performed, and thus commit and rollback may + * yield unexpected results. + * * Note that nested transactions are not supported. - * + * * @author Mattias Hellborg Arthursson * @since 1.2 - * @deprecated The idea of wrapping two transaction managers without actual XA support is probably not such a good idea - * after all. AbstractPlatformTransactionManager is not designed for this usage. + * @deprecated The idea of wrapping two transaction managers without actual XA support is + * probably not such a good idea after all. AbstractPlatformTransactionManager is not + * designed for this usage. */ -public class ContextSourceAndDataSourceTransactionManager extends - DataSourceTransactionManager { +public class ContextSourceAndDataSourceTransactionManager extends DataSourceTransactionManager { private static final long serialVersionUID = 6832868697460384648L; @@ -51,7 +51,8 @@ public class ContextSourceAndDataSourceTransactionManager extends } /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#isExistingTransaction(java.lang.Object) + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager# + * isExistingTransaction(java.lang.Object) */ protected boolean isExistingTransaction(Object transaction) { // We don't support nested transactions here @@ -59,30 +60,30 @@ public class ContextSourceAndDataSourceTransactionManager extends } /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doGetTransaction() + * @see + * org.springframework.jdbc.datasource.DataSourceTransactionManager#doGetTransaction() */ protected Object doGetTransaction() { Object dataSourceTransactionObject = super.doGetTransaction(); - Object contextSourceTransactionObject = ldapManagerDelegate - .doGetTransaction(); + Object contextSourceTransactionObject = ldapManagerDelegate.doGetTransaction(); - return new ContextSourceAndDataSourceTransactionObject( - contextSourceTransactionObject, dataSourceTransactionObject); + return new ContextSourceAndDataSourceTransactionObject(contextSourceTransactionObject, + dataSourceTransactionObject); } /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin(java.lang.Object, - * org.springframework.transaction.TransactionDefinition) + * @see + * org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin(java.lang. + * Object, org.springframework.transaction.TransactionDefinition) */ protected void doBegin(Object transaction, TransactionDefinition definition) { ContextSourceAndDataSourceTransactionObject actualTransactionObject = (ContextSourceAndDataSourceTransactionObject) transaction; - super.doBegin(actualTransactionObject.getDataSourceTransactionObject(), - definition); + super.doBegin(actualTransactionObject.getDataSourceTransactionObject(), definition); try { - ldapManagerDelegate.doBegin(actualTransactionObject - .getLdapTransactionObject(), definition); - } catch (TransactionException e) { + ldapManagerDelegate.doBegin(actualTransactionObject.getLdapTransactionObject(), definition); + } + catch (TransactionException e) { // Failed to start LDAP transaction - make sure we clean up properly super.doCleanupAfterCompletion(actualTransactionObject.getDataSourceTransactionObject()); throw e; @@ -90,19 +91,19 @@ public class ContextSourceAndDataSourceTransactionManager extends } /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doCleanupAfterCompletion(java.lang.Object) + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager# + * doCleanupAfterCompletion(java.lang.Object) */ protected void doCleanupAfterCompletion(Object transaction) { ContextSourceAndDataSourceTransactionObject actualTransactionObject = (ContextSourceAndDataSourceTransactionObject) transaction; - super.doCleanupAfterCompletion(actualTransactionObject - .getDataSourceTransactionObject()); - ldapManagerDelegate.doCleanupAfterCompletion(actualTransactionObject - .getLdapTransactionObject()); + super.doCleanupAfterCompletion(actualTransactionObject.getDataSourceTransactionObject()); + ldapManagerDelegate.doCleanupAfterCompletion(actualTransactionObject.getLdapTransactionObject()); } /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doCommit(org.springframework.transaction.support.DefaultTransactionStatus) + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doCommit(org. + * springframework.transaction.support.DefaultTransactionStatus) */ protected void doCommit(DefaultTransactionStatus status) { @@ -110,47 +111,43 @@ public class ContextSourceAndDataSourceTransactionManager extends .getTransaction(); try { - super.doCommit(new DefaultTransactionStatus(actualTransactionObject - .getDataSourceTransactionObject(), status - .isNewTransaction(), status.isNewSynchronization(), status - .isReadOnly(), status.isDebug(), status - .getSuspendedResources())); - } catch (TransactionException ex) { + super.doCommit(new DefaultTransactionStatus(actualTransactionObject.getDataSourceTransactionObject(), + status.isNewTransaction(), status.isNewSynchronization(), status.isReadOnly(), status.isDebug(), + status.getSuspendedResources())); + } + catch (TransactionException ex) { if (isRollbackOnCommitFailure()) { logger.debug("Failed to commit db resource, rethrowing", ex); // If we are to rollback on commit failure, just rethrow the // exception - this will cause a rollback to be performed on // both resources. throw ex; - } else { - logger - .warn("Failed to commit and resource is rollbackOnCommit not set -" - + " proceeding to commit ldap resource."); + } + else { + logger.warn("Failed to commit and resource is rollbackOnCommit not set -" + + " proceeding to commit ldap resource."); } } - ldapManagerDelegate.doCommit(new DefaultTransactionStatus( - actualTransactionObject.getLdapTransactionObject(), status - .isNewTransaction(), status.isNewSynchronization(), - status.isReadOnly(), status.isDebug(), status - .getSuspendedResources())); + ldapManagerDelegate.doCommit(new DefaultTransactionStatus(actualTransactionObject.getLdapTransactionObject(), + status.isNewTransaction(), status.isNewSynchronization(), status.isReadOnly(), status.isDebug(), + status.getSuspendedResources())); } /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doRollback(org.springframework.transaction.support.DefaultTransactionStatus) + * @see + * org.springframework.jdbc.datasource.DataSourceTransactionManager#doRollback(org. + * springframework.transaction.support.DefaultTransactionStatus) */ protected void doRollback(DefaultTransactionStatus status) { ContextSourceAndDataSourceTransactionObject actualTransactionObject = (ContextSourceAndDataSourceTransactionObject) status .getTransaction(); - super.doRollback(new DefaultTransactionStatus(actualTransactionObject - .getDataSourceTransactionObject(), status.isNewTransaction(), - status.isNewSynchronization(), status.isReadOnly(), status - .isDebug(), status.getSuspendedResources())); - ldapManagerDelegate.doRollback(new DefaultTransactionStatus( - actualTransactionObject.getLdapTransactionObject(), status - .isNewTransaction(), status.isNewSynchronization(), - status.isReadOnly(), status.isDebug(), status - .getSuspendedResources())); + super.doRollback(new DefaultTransactionStatus(actualTransactionObject.getDataSourceTransactionObject(), + status.isNewTransaction(), status.isNewSynchronization(), status.isReadOnly(), status.isDebug(), + status.getSuspendedResources())); + ldapManagerDelegate.doRollback(new DefaultTransactionStatus(actualTransactionObject.getLdapTransactionObject(), + status.isNewTransaction(), status.isNewSynchronization(), status.isReadOnly(), status.isDebug(), + status.getSuspendedResources())); } public ContextSource getContextSource() { @@ -161,18 +158,18 @@ public class ContextSourceAndDataSourceTransactionManager extends ldapManagerDelegate.setContextSource(contextSource); } - public void setRenamingStrategy( - TempEntryRenamingStrategy renamingStrategy) { + public void setRenamingStrategy(TempEntryRenamingStrategy renamingStrategy) { ldapManagerDelegate.setRenamingStrategy(renamingStrategy); } private final static class ContextSourceAndDataSourceTransactionObject { + private Object ldapTransactionObject; private Object dataSourceTransactionObject; - public ContextSourceAndDataSourceTransactionObject( - Object ldapTransactionObject, Object dataSourceTransactionObject) { + public ContextSourceAndDataSourceTransactionObject(Object ldapTransactionObject, + Object dataSourceTransactionObject) { this.ldapTransactionObject = ldapTransactionObject; this.dataSourceTransactionObject = dataSourceTransactionObject; } @@ -184,29 +181,32 @@ public class ContextSourceAndDataSourceTransactionManager extends public Object getLdapTransactionObject() { return ldapTransactionObject; } + } /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doSuspend(java.lang.Object) + * @see + * org.springframework.jdbc.datasource.DataSourceTransactionManager#doSuspend(java. + * lang.Object) */ protected Object doSuspend(Object transaction) { throw new TransactionSuspensionNotSupportedException( - "Transaction manager [" + getClass().getName() - + "] does not support transaction suspension"); + "Transaction manager [" + getClass().getName() + "] does not support transaction suspension"); } /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doResume(java.lang.Object, - * java.lang.Object) + * @see + * org.springframework.jdbc.datasource.DataSourceTransactionManager#doResume(java.lang + * .Object, java.lang.Object) */ protected void doResume(Object transaction, Object suspendedResources) { throw new TransactionSuspensionNotSupportedException( - "Transaction manager [" + getClass().getName() - + "] does not support transaction suspension"); + "Transaction manager [" + getClass().getName() + "] does not support transaction suspension"); } public void afterPropertiesSet() { super.afterPropertiesSet(); ldapManagerDelegate.checkRenamingStrategy(); } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceAndHibernateTransactionManager.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceAndHibernateTransactionManager.java index 4db6cff3..9c5eccec 100755 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceAndHibernateTransactionManager.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceAndHibernateTransactionManager.java @@ -23,20 +23,23 @@ import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionException; import org.springframework.transaction.TransactionSuspensionNotSupportedException; import org.springframework.transaction.support.DefaultTransactionStatus; + /** * A Transaction Manager to manage LDAP and Hibernate 3 operations within the same - * transaction. Note that even though the same logical transaction is used, this - * is not a JTA XA transaction; no two-phase commit will be performed, - * and thus commit and rollback may yield unexpected results.
    + * transaction. Note that even though the same logical transaction is used, this is + * not a JTA XA transaction; no two-phase commit will be performed, and thus commit + * and rollback may yield unexpected results.
    * This Transaction Manager is as good as it gets when you are using in LDAP in - * combination with a Hibernate 3 and unable to use XA transactions because LDAP - * is not transactional by design to begin with.
    + * combination with a Hibernate 3 and unable to use XA transactions because LDAP is not + * transactional by design to begin with.
    * * Furthermore, this manager does not support nested transactions + * * @author Hans Westerbeek * @since 1.2.2 - * @deprecated The idea of wrapping two transaction managers without actual XA support is probably not such a good idea - * after all. AbstractPlatformTransactionManager is not designed for this usage. + * @deprecated The idea of wrapping two transaction managers without actual XA support is + * probably not such a good idea after all. AbstractPlatformTransactionManager is not + * designed for this usage. */ public class ContextSourceAndHibernateTransactionManager extends HibernateTransactionManager { @@ -47,41 +50,41 @@ public class ContextSourceAndHibernateTransactionManager extends HibernateTransa private ContextSourceTransactionManagerDelegate ldapManagerDelegate = new ContextSourceTransactionManagerDelegate(); - /* - * @see org.springframework.orm.hibernate5.HibernateTransactionManager#isExistingTransaction(java.lang.Object) + /* + * @see org.springframework.orm.hibernate5.HibernateTransactionManager# + * isExistingTransaction(java.lang.Object) */ protected boolean isExistingTransaction(Object transaction) { ContextSourceAndHibernateTransactionObject actualTransactionObject = (ContextSourceAndHibernateTransactionObject) transaction; - return super.isExistingTransaction(actualTransactionObject - .getHibernateTransactionObject()); + return super.isExistingTransaction(actualTransactionObject.getHibernateTransactionObject()); } /* - * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doGetTransaction() + * @see + * org.springframework.orm.hibernate5.HibernateTransactionManager#doGetTransaction() */ protected Object doGetTransaction() { Object dataSourceTransactionObject = super.doGetTransaction(); - Object contextSourceTransactionObject = ldapManagerDelegate - .doGetTransaction(); + Object contextSourceTransactionObject = ldapManagerDelegate.doGetTransaction(); - return new ContextSourceAndHibernateTransactionObject( - contextSourceTransactionObject, dataSourceTransactionObject); + return new ContextSourceAndHibernateTransactionObject(contextSourceTransactionObject, + dataSourceTransactionObject); } /* - * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doBegin(java.lang.Object, - * org.springframework.transaction.TransactionDefinition) + * @see + * org.springframework.orm.hibernate5.HibernateTransactionManager#doBegin(java.lang. + * Object, org.springframework.transaction.TransactionDefinition) */ protected void doBegin(Object transaction, TransactionDefinition definition) { ContextSourceAndHibernateTransactionObject actualTransactionObject = (ContextSourceAndHibernateTransactionObject) transaction; - super.doBegin(actualTransactionObject.getHibernateTransactionObject(), - definition); + super.doBegin(actualTransactionObject.getHibernateTransactionObject(), definition); try { - ldapManagerDelegate.doBegin(actualTransactionObject - .getLdapTransactionObject(), definition); - } catch (TransactionException e) { + ldapManagerDelegate.doBegin(actualTransactionObject.getLdapTransactionObject(), definition); + } + catch (TransactionException e) { // Failed to start LDAP transaction - make sure we clean up properly super.doCleanupAfterCompletion(actualTransactionObject.getHibernateTransactionObject()); throw e; @@ -89,19 +92,19 @@ public class ContextSourceAndHibernateTransactionManager extends HibernateTransa } /* - * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doCleanupAfterCompletion(java.lang.Object) + * @see org.springframework.orm.hibernate5.HibernateTransactionManager# + * doCleanupAfterCompletion(java.lang.Object) */ protected void doCleanupAfterCompletion(Object transaction) { ContextSourceAndHibernateTransactionObject actualTransactionObject = (ContextSourceAndHibernateTransactionObject) transaction; - super.doCleanupAfterCompletion(actualTransactionObject - .getHibernateTransactionObject()); - ldapManagerDelegate.doCleanupAfterCompletion(actualTransactionObject - .getLdapTransactionObject()); + super.doCleanupAfterCompletion(actualTransactionObject.getHibernateTransactionObject()); + ldapManagerDelegate.doCleanupAfterCompletion(actualTransactionObject.getLdapTransactionObject()); } /* - * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doCommit(org.springframework.transaction.support.DefaultTransactionStatus) + * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doCommit(org. + * springframework.transaction.support.DefaultTransactionStatus) */ protected void doCommit(DefaultTransactionStatus status) { @@ -109,47 +112,42 @@ public class ContextSourceAndHibernateTransactionManager extends HibernateTransa .getTransaction(); try { - super.doCommit(new DefaultTransactionStatus(actualTransactionObject - .getHibernateTransactionObject(), status - .isNewTransaction(), status.isNewSynchronization(), status - .isReadOnly(), status.isDebug(), status - .getSuspendedResources())); - } catch (TransactionException ex) { + super.doCommit(new DefaultTransactionStatus(actualTransactionObject.getHibernateTransactionObject(), + status.isNewTransaction(), status.isNewSynchronization(), status.isReadOnly(), status.isDebug(), + status.getSuspendedResources())); + } + catch (TransactionException ex) { if (isRollbackOnCommitFailure()) { logger.debug("Failed to commit db resource, rethrowing", ex); // If we are to rollback on commit failure, just rethrow the // exception - this will cause a rollback to be performed on // both resources. throw ex; - } else { - logger - .warn("Failed to commit and resource is rollbackOnCommit not set -" - + " proceeding to commit ldap resource."); + } + else { + logger.warn("Failed to commit and resource is rollbackOnCommit not set -" + + " proceeding to commit ldap resource."); } } - ldapManagerDelegate.doCommit(new DefaultTransactionStatus( - actualTransactionObject.getLdapTransactionObject(), status - .isNewTransaction(), status.isNewSynchronization(), - status.isReadOnly(), status.isDebug(), status - .getSuspendedResources())); + ldapManagerDelegate.doCommit(new DefaultTransactionStatus(actualTransactionObject.getLdapTransactionObject(), + status.isNewTransaction(), status.isNewSynchronization(), status.isReadOnly(), status.isDebug(), + status.getSuspendedResources())); } /* - * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doRollback(org.springframework.transaction.support.DefaultTransactionStatus) + * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doRollback(org. + * springframework.transaction.support.DefaultTransactionStatus) */ protected void doRollback(DefaultTransactionStatus status) { ContextSourceAndHibernateTransactionObject actualTransactionObject = (ContextSourceAndHibernateTransactionObject) status .getTransaction(); - super.doRollback(new DefaultTransactionStatus(actualTransactionObject - .getHibernateTransactionObject(), status.isNewTransaction(), - status.isNewSynchronization(), status.isReadOnly(), status - .isDebug(), status.getSuspendedResources())); - ldapManagerDelegate.doRollback(new DefaultTransactionStatus( - actualTransactionObject.getLdapTransactionObject(), status - .isNewTransaction(), status.isNewSynchronization(), - status.isReadOnly(), status.isDebug(), status - .getSuspendedResources())); + super.doRollback(new DefaultTransactionStatus(actualTransactionObject.getHibernateTransactionObject(), + status.isNewTransaction(), status.isNewSynchronization(), status.isReadOnly(), status.isDebug(), + status.getSuspendedResources())); + ldapManagerDelegate.doRollback(new DefaultTransactionStatus(actualTransactionObject.getLdapTransactionObject(), + status.isNewTransaction(), status.isNewSynchronization(), status.isReadOnly(), status.isDebug(), + status.getSuspendedResources())); } public ContextSource getContextSource() { @@ -160,18 +158,18 @@ public class ContextSourceAndHibernateTransactionManager extends HibernateTransa ldapManagerDelegate.setContextSource(contextSource); } - public void setRenamingStrategy( - TempEntryRenamingStrategy renamingStrategy) { + public void setRenamingStrategy(TempEntryRenamingStrategy renamingStrategy) { ldapManagerDelegate.setRenamingStrategy(renamingStrategy); } private static final class ContextSourceAndHibernateTransactionObject { + private Object ldapTransactionObject; private Object hibernateTransactionObject; - public ContextSourceAndHibernateTransactionObject( - Object ldapTransactionObject, Object hibernateTransactionObject) { + public ContextSourceAndHibernateTransactionObject(Object ldapTransactionObject, + Object hibernateTransactionObject) { this.ldapTransactionObject = ldapTransactionObject; this.hibernateTransactionObject = hibernateTransactionObject; } @@ -183,29 +181,32 @@ public class ContextSourceAndHibernateTransactionManager extends HibernateTransa public Object getLdapTransactionObject() { return ldapTransactionObject; } + } /* - * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doSuspend(java.lang.Object) + * @see + * org.springframework.orm.hibernate5.HibernateTransactionManager#doSuspend(java.lang. + * Object) */ protected Object doSuspend(Object transaction) { throw new TransactionSuspensionNotSupportedException( - "Transaction manager [" + getClass().getName() - + "] does not support transaction suspension"); + "Transaction manager [" + getClass().getName() + "] does not support transaction suspension"); } /* - * @see org.springframework.orm.hibernate5.HibernateTransactionManager#doResume(java.lang.Object, - * java.lang.Object) + * @see + * org.springframework.orm.hibernate5.HibernateTransactionManager#doResume(java.lang. + * Object, java.lang.Object) */ protected void doResume(Object transaction, Object suspendedResources) { throw new TransactionSuspensionNotSupportedException( - "Transaction manager [" + getClass().getName() - + "] does not support transaction suspension"); + "Transaction manager [" + getClass().getName() + "] does not support transaction suspension"); } public void afterPropertiesSet() { super.afterPropertiesSet(); ldapManagerDelegate.checkRenamingStrategy(); } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManager.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManager.java index e2dfafa5..845ca196 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManager.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManager.java @@ -31,76 +31,68 @@ import org.springframework.transaction.support.AbstractPlatformTransactionManage import org.springframework.transaction.support.DefaultTransactionStatus; /** - * TransactionManager for managing LDAP transactions. Since transactions are not - * supported in the LDAP protocol, this class and its collaborators aim to - * provide compensating transactions instead. Should a transaction - * need to be rolled back, this TransactionManager will try to restore the - * original state using information recorded prior to each operation. The - * operation where the original state is restored is called a compensating - * operation. + * TransactionManager for managing LDAP transactions. Since transactions are not supported + * in the LDAP protocol, this class and its collaborators aim to provide + * compensating transactions instead. Should a transaction need to be rolled + * back, this TransactionManager will try to restore the original state using information + * recorded prior to each operation. The operation where the original state is restored is + * called a compensating operation. *

    - * NOTE: The transactions provided by this TransactionManager are all - * client side and are by no means 'real' transactions, in the sense - * that we know them in the ordinary database world, e.g.: + * NOTE: The transactions provided by this TransactionManager are all client + * side and are by no means 'real' transactions, in the sense that we know them in the + * ordinary database world, e.g.: *

      - *
    • Should the transaction failure be caused by a network failure, there is - * no way whatsoever that this TransactionManager can restore the database - * state. In this case, all possibilities for rollback will be utterly lost.
    • - *
    • Transaction isolation is not provided, i.e. entries participating in a - * transaction for one client may very well participate in another transaction - * for another client at the same time. Should one of these transactions be - * rolled back, the outcome of this is undetermined, and may in the worst case - * result in total failure.
    • + *
    • Should the transaction failure be caused by a network failure, there is no way + * whatsoever that this TransactionManager can restore the database state. In this case, + * all possibilities for rollback will be utterly lost.
    • + *
    • Transaction isolation is not provided, i.e. entries participating in a transaction + * for one client may very well participate in another transaction for another client at + * the same time. Should one of these transactions be rolled back, the outcome of this is + * undetermined, and may in the worst case result in total failure.
    • *
    *

    - * While the points above should be noted and considered, the compensating - * transaction approach will be perfectly sufficient for all but the most - * unfortunate of circumstances. Considering that there currently is a total - * absence of server-side transaction support in the LDAP world, being able to - * mark operations as transactional in the same way as for relational database - * operations is surely a step forward. + * While the points above should be noted and considered, the compensating transaction + * approach will be perfectly sufficient for all but the most unfortunate of + * circumstances. Considering that there currently is a total absence of server-side + * transaction support in the LDAP world, being able to mark operations as transactional + * in the same way as for relational database operations is surely a step forward. *

    - * An LDAP transaction is tied to a {@link ContextSource}, to be supplied to - * the {@link #setContextSource(ContextSource)} method. While the actual - * ContextSource used by the target LdapTemplate instance needs to be of the - * type {@link TransactionAwareContextSourceProxy}, the ContextSource supplied - * to this class should be the actual target ContextSource. + * An LDAP transaction is tied to a {@link ContextSource}, to be supplied to the + * {@link #setContextSource(ContextSource)} method. While the actual ContextSource used by + * the target LdapTemplate instance needs to be of the type + * {@link TransactionAwareContextSourceProxy}, the ContextSource supplied to this class + * should be the actual target ContextSource. *

    - * Using this TransactionManager along with - * {@link TransactionAwareContextSourceProxy}, all modifying operations (bind, - * unbind, rebind, rename, modifyAttributes) in a transaction will be - * intercepted. Each modification has its corresponding - * {@link CompensatingTransactionOperationRecorder}, which collects the - * information necessary to perform a rollback and produces a - * {@link CompensatingTransactionOperationExecutor} which is then used to - * execute the actual operation and is later called for performing the commit or - * rollback. + * Using this TransactionManager along with {@link TransactionAwareContextSourceProxy}, + * all modifying operations (bind, unbind, rebind, rename, modifyAttributes) in a + * transaction will be intercepted. Each modification has its corresponding + * {@link CompensatingTransactionOperationRecorder}, which collects the information + * necessary to perform a rollback and produces a + * {@link CompensatingTransactionOperationExecutor} which is then used to execute the + * actual operation and is later called for performing the commit or rollback. *

    - * For several of the operations, performing a rollback is pretty - * straightforward. For example, in order to roll back a rename operation, it - * will only be required to rename the entry back to its original position. For - * other operations, however, it's a bit more complicated. An unbind operation - * is not possible to roll back by simply binding the entry back with the - * attributes retrieved from the original entry. It might not be possible to get - * all the information from the original entry. Consequently, the - * {@link UnbindOperationExecutor} will move the original entry to a temporary - * location in its performOperation() method. The commit() method will know that - * everything went well, so it will be OK to unbind the entry. The rollback - * operation will be to rename the entry back to its original location. The same - * behaviour is used for rebind() operations. The operation of calculating a - * temporary location for an entry is delegated to a - * {@link TempEntryRenamingStrategy} (default + * For several of the operations, performing a rollback is pretty straightforward. For + * example, in order to roll back a rename operation, it will only be required to rename + * the entry back to its original position. For other operations, however, it's a bit more + * complicated. An unbind operation is not possible to roll back by simply binding the + * entry back with the attributes retrieved from the original entry. It might not be + * possible to get all the information from the original entry. Consequently, the + * {@link UnbindOperationExecutor} will move the original entry to a temporary location in + * its performOperation() method. The commit() method will know that everything went well, + * so it will be OK to unbind the entry. The rollback operation will be to rename the + * entry back to its original location. The same behaviour is used for rebind() + * operations. The operation of calculating a temporary location for an entry is delegated + * to a {@link TempEntryRenamingStrategy} (default * {@link DefaultTempEntryRenamingStrategy}), specified in * {@link #setRenamingStrategy(TempEntryRenamingStrategy)}. *

    * The actual work of this Transaction Manager is delegated to a - * {@link ContextSourceTransactionManagerDelegate}. This is because the exact - * same logic needs to be used if we want to wrap a JDBC and LDAP transaction in - * the same logical transaction. + * {@link ContextSourceTransactionManagerDelegate}. This is because the exact same logic + * needs to be used if we want to wrap a JDBC and LDAP transaction in the same logical + * transaction. *

    * * @author Mattias Hellborg Arthursson - * * @see ContextSourceAndDataSourceTransactionManager * @see ContextSourceTransactionManagerDelegate * @see DefaultCompensatingTransactionOperationManager @@ -108,44 +100,49 @@ import org.springframework.transaction.support.DefaultTransactionStatus; * @see TransactionAwareContextSourceProxy * @since 1.2 */ -public class ContextSourceTransactionManager extends - AbstractPlatformTransactionManager implements InitializingBean { +public class ContextSourceTransactionManager extends AbstractPlatformTransactionManager implements InitializingBean { private static final long serialVersionUID = 7138208218687237856L; private ContextSourceTransactionManagerDelegate delegate = new ContextSourceTransactionManagerDelegate(); /* - * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#doBegin(java.lang.Object, - * org.springframework.transaction.TransactionDefinition) + * @see + * org.springframework.transaction.support.AbstractPlatformTransactionManager#doBegin( + * java.lang.Object, org.springframework.transaction.TransactionDefinition) */ protected void doBegin(Object transaction, TransactionDefinition definition) { delegate.doBegin(transaction, definition); } /* - * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#doCleanupAfterCompletion(java.lang.Object) + * @see org.springframework.transaction.support.AbstractPlatformTransactionManager# + * doCleanupAfterCompletion(java.lang.Object) */ protected void doCleanupAfterCompletion(Object transaction) { delegate.doCleanupAfterCompletion(transaction); } /* - * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#doCommit(org.springframework.transaction.support.DefaultTransactionStatus) + * @see + * org.springframework.transaction.support.AbstractPlatformTransactionManager#doCommit + * (org.springframework.transaction.support.DefaultTransactionStatus) */ protected void doCommit(DefaultTransactionStatus status) { delegate.doCommit(status); } /* - * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#doGetTransaction() + * @see org.springframework.transaction.support.AbstractPlatformTransactionManager# + * doGetTransaction() */ protected Object doGetTransaction() { return delegate.doGetTransaction(); } /* - * @see org.springframework.transaction.support.AbstractPlatformTransactionManager#doRollback(org.springframework.transaction.support.DefaultTransactionStatus) + * @see org.springframework.transaction.support.AbstractPlatformTransactionManager# + * doRollback(org.springframework.transaction.support.DefaultTransactionStatus) */ protected void doRollback(DefaultTransactionStatus status) { delegate.doRollback(status); @@ -153,7 +150,6 @@ public class ContextSourceTransactionManager extends /** * Get the ContextSource. - * * @return the contextSource. * @see ContextSourceTransactionManagerDelegate#getContextSource() */ @@ -163,9 +159,7 @@ public class ContextSourceTransactionManager extends /** * Set the ContextSource. - * - * @param contextSource - * the ContextSource. + * @param contextSource the ContextSource. * @see ContextSourceTransactionManagerDelegate#setContextSource(ContextSource) */ public void setContextSource(ContextSource contextSource) { @@ -174,9 +168,7 @@ public class ContextSourceTransactionManager extends /** * Set the {@link TempEntryRenamingStrategy}. - * - * @param renamingStrategy - * the Renaming Strategy. + * @param renamingStrategy the Renaming Strategy. * @see ContextSourceTransactionManagerDelegate#setRenamingStrategy(TempEntryRenamingStrategy) */ public void setRenamingStrategy(TempEntryRenamingStrategy renamingStrategy) { @@ -188,9 +180,9 @@ public class ContextSourceTransactionManager extends } @Override - protected boolean isExistingTransaction(Object transaction) - throws TransactionException { + protected boolean isExistingTransaction(Object transaction) throws TransactionException { CompensatingTransactionObject txObject = (CompensatingTransactionObject) transaction; return (txObject.getHolder() != null); } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerDelegate.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerDelegate.java index 0eef3629..e147176f 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerDelegate.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerDelegate.java @@ -32,18 +32,16 @@ import javax.naming.NamingException; import javax.naming.directory.DirContext; /** - * This delegate performs all the work for the - * {@link ContextSourceTransactionManager}. The work is delegated in order to - * be able to perform the exact same work for the LDAP part in - * {@link ContextSourceAndDataSourceTransactionManager}. - * + * This delegate performs all the work for the {@link ContextSourceTransactionManager}. + * The work is delegated in order to be able to perform the exact same work for the LDAP + * part in {@link ContextSourceAndDataSourceTransactionManager}. + * * @author Mattias Hellborg Arthursson * @see ContextSourceTransactionManager * @see ContextSourceAndDataSourceTransactionManager * @since 1.2 */ -public class ContextSourceTransactionManagerDelegate extends - AbstractCompensatingTransactionManagerDelegate { +public class ContextSourceTransactionManagerDelegate extends AbstractCompensatingTransactionManagerDelegate { private static final Logger LOG = LoggerFactory.getLogger(ContextSourceTransactionManagerDelegate.class); @@ -52,26 +50,24 @@ public class ContextSourceTransactionManagerDelegate extends private TempEntryRenamingStrategy renamingStrategy; /** - * Set the ContextSource to work on. Even though the actual ContextSource - * sent to the LdapTemplate instance should be a - * {@link TransactionAwareContextSourceProxy}, the one sent to this method - * should be the target of that proxy. If it is not, the target will be - * extracted and used instead. - * - * @param contextSource - * the ContextSource to work on. + * Set the ContextSource to work on. Even though the actual ContextSource sent to the + * LdapTemplate instance should be a {@link TransactionAwareContextSourceProxy}, the + * one sent to this method should be the target of that proxy. If it is not, the + * target will be extracted and used instead. + * @param contextSource the ContextSource to work on. */ public void setContextSource(ContextSource contextSource) { if (contextSource instanceof TransactionAwareContextSourceProxy) { TransactionAwareContextSourceProxy proxy = (TransactionAwareContextSourceProxy) contextSource; this.contextSource = proxy.getTarget(); - } else { + } + else { this.contextSource = contextSource; } if (contextSource instanceof AbstractContextSource) { AbstractContextSource abstractContextSource = (AbstractContextSource) contextSource; - if(abstractContextSource.isAnonymousReadOnly()) { + if (abstractContextSource.isAnonymousReadOnly()) { throw new IllegalArgumentException( "Compensating LDAP transactions cannot be used when context-source is anonymous-read-only"); } @@ -83,46 +79,47 @@ public class ContextSourceTransactionManagerDelegate extends } /* - * @see org.springframework.transaction.compensating.support.AbstractCompensatingTransactionManagerDelegate#getTransactionSynchronizationKey() + * @see org.springframework.transaction.compensating.support. + * AbstractCompensatingTransactionManagerDelegate#getTransactionSynchronizationKey() */ protected Object getTransactionSynchronizationKey() { return getContextSource(); } /* - * @see org.springframework.transaction.compensating.support.AbstractCompensatingTransactionManagerDelegate#getNewHolder() + * @see org.springframework.transaction.compensating.support. + * AbstractCompensatingTransactionManagerDelegate#getNewHolder() */ protected CompensatingTransactionHolderSupport getNewHolder() { DirContext newCtx = getContextSource().getReadWriteContext(); - return new DirContextHolder( - new DefaultCompensatingTransactionOperationManager( - new LdapCompensatingTransactionOperationFactory( - renamingStrategy)), newCtx); + return new DirContextHolder(new DefaultCompensatingTransactionOperationManager( + new LdapCompensatingTransactionOperationFactory(renamingStrategy)), newCtx); } /* - * @see org.springframework.transaction.compensating.support.AbstractCompensatingTransactionManagerDelegate#closeTargetResource(org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport) + * @see org.springframework.transaction.compensating.support. + * AbstractCompensatingTransactionManagerDelegate#closeTargetResource(org. + * springframework.transaction.compensating.support. + * CompensatingTransactionHolderSupport) */ - protected void closeTargetResource( - CompensatingTransactionHolderSupport transactionHolderSupport) { + protected void closeTargetResource(CompensatingTransactionHolderSupport transactionHolderSupport) { DirContextHolder contextHolder = (DirContextHolder) transactionHolderSupport; DirContext ctx = contextHolder.getCtx(); try { LOG.debug("Closing target context"); ctx.close(); - } catch (NamingException e) { + } + catch (NamingException e) { LOG.warn("Failed to close target context", e); } } /** - * Set the {@link TempEntryRenamingStrategy} to be used when renaming - * temporary entries in unbind and rebind operations. Default value is a + * Set the {@link TempEntryRenamingStrategy} to be used when renaming temporary + * entries in unbind and rebind operations. Default value is a * {@link DefaultTempEntryRenamingStrategy}. - * - * @param renamingStrategy - * the {@link TempEntryRenamingStrategy} to use. + * @param renamingStrategy the {@link TempEntryRenamingStrategy} to use. */ public void setRenamingStrategy(TempEntryRenamingStrategy renamingStrategy) { this.renamingStrategy = renamingStrategy; @@ -131,4 +128,5 @@ public class ContextSourceTransactionManagerDelegate extends void checkRenamingStrategy() { Assert.notNull(renamingStrategy, "RenamingStrategy must be specified"); } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/DirContextHolder.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/DirContextHolder.java index 4ab794cc..d9a566a8 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/DirContextHolder.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/DirContextHolder.java @@ -21,37 +21,31 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera import org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport; /** - * Keeps track of the transaction DirContext. The same DirContext instance will - * be reused throughout a transaction. Also keeps a - * {@link CompensatingTransactionOperationManager}, responsible for performing - * operations and keeping track of all changes and storing information necessary - * for commit or rollback. - * + * Keeps track of the transaction DirContext. The same DirContext instance will be reused + * throughout a transaction. Also keeps a {@link CompensatingTransactionOperationManager}, + * responsible for performing operations and keeping track of all changes and storing + * information necessary for commit or rollback. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ public class DirContextHolder extends CompensatingTransactionHolderSupport { + private DirContext ctx; /** * Constructor. - * - * @param manager - * The {@link CompensatingTransactionOperationManager}. - * @param ctx - * The DirContext associated with the current transaction. + * @param manager The {@link CompensatingTransactionOperationManager}. + * @param ctx The DirContext associated with the current transaction. */ - public DirContextHolder(CompensatingTransactionOperationManager manager, - DirContext ctx) { + public DirContextHolder(CompensatingTransactionOperationManager manager, DirContext ctx) { super(manager); this.ctx = ctx; } /** * Set the DirContext associated with the current transaction. - * - * @param ctx - * The DirContext associated with the current transaction. + * @param ctx The DirContext associated with the current transaction. */ public void setCtx(DirContext ctx) { this.ctx = ctx; @@ -65,9 +59,11 @@ public class DirContextHolder extends CompensatingTransactionHolderSupport { } /* - * @see org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport#getTransactedResource() + * @see org.springframework.transaction.compensating.support. + * CompensatingTransactionHolderSupport#getTransactedResource() */ protected Object getTransactedResource() { return ctx; } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxy.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxy.java index 908e806b..bbab7574 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxy.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxy.java @@ -25,27 +25,23 @@ import javax.naming.directory.DirContext; import java.lang.reflect.Proxy; /** - * A proxy for ContextSource to make sure that the returned DirContext objects - * are aware of the surrounding transactions. This makes sure that the - * DirContext is not closed during the transaction and that all modifying - * operations are recorded, keeping track of the corresponding rollback - * operations. All returned DirContext instances will be of the type - * {@link TransactionAwareDirContextInvocationHandler}. - * + * A proxy for ContextSource to make sure that the returned DirContext objects are aware + * of the surrounding transactions. This makes sure that the DirContext is not closed + * during the transaction and that all modifying operations are recorded, keeping track of + * the corresponding rollback operations. All returned DirContext instances will be of the + * type {@link TransactionAwareDirContextInvocationHandler}. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class TransactionAwareContextSourceProxy - extends DelegatingBaseLdapPathContextSourceSupport +public class TransactionAwareContextSourceProxy extends DelegatingBaseLdapPathContextSourceSupport implements ContextSource { private ContextSource target; /** * Constructor. - * - * @param target - * the target ContextSource. + * @param target the target ContextSource. */ public TransactionAwareContextSourceProxy(ContextSource target) { this.target = target; @@ -61,23 +57,16 @@ public class TransactionAwareContextSourceProxy return getReadWriteContext(); } - private DirContext getTransactionAwareDirContextProxy(DirContext context, - ContextSource target) { - return (DirContext) Proxy - .newProxyInstance(DirContextProxy.class.getClassLoader(), - new Class[] { - LdapUtils - .getActualTargetClass(context), - DirContextProxy.class }, - new TransactionAwareDirContextInvocationHandler( - context, target)); + private DirContext getTransactionAwareDirContextProxy(DirContext context, ContextSource target) { + return (DirContext) Proxy.newProxyInstance(DirContextProxy.class.getClassLoader(), + new Class[] { LdapUtils.getActualTargetClass(context), DirContextProxy.class }, + new TransactionAwareDirContextInvocationHandler(context, target)); } @Override public DirContext getReadWriteContext() { - DirContextHolder contextHolder = (DirContextHolder) TransactionSynchronizationManager - .getResource(target); + DirContextHolder contextHolder = (DirContextHolder) TransactionSynchronizationManager.getResource(target); DirContext ctx = null; if (contextHolder != null) { @@ -97,4 +86,5 @@ public class TransactionAwareContextSourceProxy public DirContext getContext(String principal, String credentials) { return target.getContext(principal, credentials); } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandler.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandler.java index 5cf2b726..e0efa939 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandler.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandler.java @@ -29,15 +29,14 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** - * Proxy implementation for DirContext, making sure that the instance is not - * closed during a transaction, and that all modifying operations are recorded, - * storing compensating rollback operations for them. - * + * Proxy implementation for DirContext, making sure that the instance is not closed during + * a transaction, and that all modifying operations are recorded, storing compensating + * rollback operations for them. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class TransactionAwareDirContextInvocationHandler implements - InvocationHandler { +public class TransactionAwareDirContextInvocationHandler implements InvocationHandler { private static Logger log = LoggerFactory.getLogger(TransactionAwareDirContextInvocationHandler.class); @@ -47,75 +46,71 @@ public class TransactionAwareDirContextInvocationHandler implements /** * Constructor. - * - * @param target - * The target DirContext. - * @param contextSource - * The transactional ContextSource, needed to get hold of the - * current transaction's {@link DirContextHolder}. + * @param target The target DirContext. + * @param contextSource The transactional ContextSource, needed to get hold of the + * current transaction's {@link DirContextHolder}. */ - public TransactionAwareDirContextInvocationHandler(DirContext target, - ContextSource contextSource) { + public TransactionAwareDirContextInvocationHandler(DirContext target, ContextSource contextSource) { this.target = target; this.contextSource = contextSource; } /* * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, - * java.lang.reflect.Method, java.lang.Object[]) + * java.lang.reflect.Method, java.lang.Object[]) */ - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); if (methodName.equals("getTargetContext")) { return target; - } else if (methodName.equals("equals")) { + } + else if (methodName.equals("equals")) { // Only consider equal when proxies are identical. return (proxy == args[0] ? Boolean.TRUE : Boolean.FALSE); - } else if (methodName.equals("hashCode")) { + } + else if (methodName.equals("hashCode")) { // Use hashCode of Connection proxy. return hashCode(); - } else if (methodName.equals("close")) { + } + else if (methodName.equals("close")) { doCloseConnection(target, contextSource); return null; - } else if (LdapTransactionUtils - .isSupportedWriteTransactionOperation(methodName)) { + } + else if (LdapTransactionUtils.isSupportedWriteTransactionOperation(methodName)) { // Store transaction data and allow operation to proceed. - CompensatingTransactionUtils.performOperation(contextSource, - target, method, args); + CompensatingTransactionUtils.performOperation(contextSource, target, method, args); return null; - } else { + } + else { try { return method.invoke(target, args); - } catch (InvocationTargetException e) { + } + catch (InvocationTargetException e) { throw e.getTargetException(); } } } /** - * Close the supplied context, but only if it is not associated with the - * current transaction. - * - * @param context - * the DirContext to close. - * @param contextSource - * the ContextSource bound to the transaction. + * Close the supplied context, but only if it is not associated with the current + * transaction. + * @param context the DirContext to close. + * @param contextSource the ContextSource bound to the transaction. * @throws NamingException */ - void doCloseConnection(DirContext context, ContextSource contextSource) - throws javax.naming.NamingException { + void doCloseConnection(DirContext context, ContextSource contextSource) throws javax.naming.NamingException { DirContextHolder transactionContextHolder = (DirContextHolder) TransactionSynchronizationManager .getResource(contextSource); - if (transactionContextHolder == null - || transactionContextHolder.getCtx() != context) { + if (transactionContextHolder == null || transactionContextHolder.getCtx() != context) { log.debug("Closing context"); // This is not the transactional context or the transaction is // no longer active - we should close it. context.close(); - } else { + } + else { log.debug("Leaving transactional context open"); } } + } diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategy.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategy.java index aceb057b..92ee21e2 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategy.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategy.java @@ -24,30 +24,28 @@ import javax.naming.ldap.LdapName; import javax.naming.ldap.Rdn; /** - * Default implementation of {@link TempEntryRenamingStrategy}. This - * implementation simply adds "_temp" to the leftmost (least significant part) - * of the name. For example: - * + * Default implementation of {@link TempEntryRenamingStrategy}. This implementation simply + * adds "_temp" to the leftmost (least significant part) of the name. For example: + * *

      * cn=john doe, ou=company1, c=SE
      * 
    - * + * * becomes: - * + * *
      * cn=john doe_temp, ou=company1, c=SE
      * 
    *

    - * Note that using this strategy means that the entry remains in virtually the - * same location as where it originally resided. This means that searches later - * in the same transaction might return references to the temporary entry even - * though it should have been removed or rebound. - * + * Note that using this strategy means that the entry remains in virtually the same + * location as where it originally resided. This means that searches later in the same + * transaction might return references to the temporary entry even though it should have + * been removed or rebound. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class DefaultTempEntryRenamingStrategy implements - TempEntryRenamingStrategy { +public class DefaultTempEntryRenamingStrategy implements TempEntryRenamingStrategy { /** * The default temp entry suffix, "_temp". @@ -57,7 +55,8 @@ public class DefaultTempEntryRenamingStrategy implements private String tempSuffix = DEFAULT_TEMP_SUFFIX; /* - * @see org.springframework.ldap.support.transaction.TempEntryRenamingStrategy#getTemporaryName(javax.naming.Name) + * @see org.springframework.ldap.support.transaction.TempEntryRenamingStrategy# + * getTemporaryName(javax.naming.Name) */ public Name getTemporaryName(Name originalName) { LdapName temporaryName = LdapUtils.newLdapName(originalName); @@ -65,8 +64,9 @@ public class DefaultTempEntryRenamingStrategy implements // Add tempSuffix to the leaf node name. try { String leafNode = (String) temporaryName.remove(temporaryName.size() - 1); - temporaryName.add(new Rdn(leafNode + tempSuffix)); - } catch (InvalidNameException e) { + temporaryName.add(new Rdn(leafNode + tempSuffix)); + } + catch (InvalidNameException e) { throw new org.springframework.ldap.InvalidNameException(e); } @@ -75,7 +75,6 @@ public class DefaultTempEntryRenamingStrategy implements /** * Get the suffix that will be used for renaming temporary entries. - * * @return the suffix. */ public String getTempSuffix() { @@ -85,9 +84,7 @@ public class DefaultTempEntryRenamingStrategy implements /** * Set the suffix to use for renaming temporary entries. Default value is * {@link #DEFAULT_TEMP_SUFFIX}. - * - * @param tempSuffix - * the suffix. + * @param tempSuffix the suffix. */ public void setTempSuffix(String tempSuffix) { this.tempSuffix = tempSuffix; diff --git a/core/src/main/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategy.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategy.java index ad8ac940..c1e8c9b7 100644 --- a/core/src/main/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategy.java +++ b/core/src/main/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategy.java @@ -25,27 +25,23 @@ import javax.naming.ldap.LdapName; import java.util.concurrent.atomic.AtomicInteger; /** - * A {@link TempEntryRenamingStrategy} that moves the entry to a different - * subtree than the original entry. The specified subtree needs to be present in - * the LDAP tree; it will not be created and operations using this strategy will - * fail if the destination is not in place. However, this strategy is preferable - * to {@link DefaultTempEntryRenamingStrategy}, as it makes searches have the - * expected result even though the temporary entry still exists during the - * transaction. + * A {@link TempEntryRenamingStrategy} that moves the entry to a different subtree than + * the original entry. The specified subtree needs to be present in the LDAP tree; it will + * not be created and operations using this strategy will fail if the destination is not + * in place. However, this strategy is preferable to + * {@link DefaultTempEntryRenamingStrategy}, as it makes searches have the expected result + * even though the temporary entry still exists during the transaction. *

    - * Example: If the specified subtreeNode is - * ou=tempEntries and the originalName is - * cn=john doe, ou=company1, c=SE, the result of - * {@link #getTemporaryName(Name)} will be - * cn=john doe1, ou=tempEntries. The "1" suffix is a - * sequence number needed to prevent potential collisions in the temporary - * storage. - * + * Example: If the specified subtreeNode is ou=tempEntries and + * the originalName is cn=john doe, ou=company1, c=SE, the + * result of {@link #getTemporaryName(Name)} will be + * cn=john doe1, ou=tempEntries. The "1" suffix is a sequence + * number needed to prevent potential collisions in the temporary storage. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class DifferentSubtreeTempEntryRenamingStrategy implements - TempEntryRenamingStrategy { +public class DifferentSubtreeTempEntryRenamingStrategy implements TempEntryRenamingStrategy { private Name subtreeNode; @@ -72,7 +68,8 @@ public class DifferentSubtreeTempEntryRenamingStrategy implements } /* - * @see org.springframework.ldap.support.transaction.TempEntryRenamingStrategy#getTemporaryName(javax.naming.Name) + * @see org.springframework.ldap.support.transaction.TempEntryRenamingStrategy# + * getTemporaryName(javax.naming.Name) */ public Name getTemporaryName(Name originalName) { int thisSequenceNo = NEXT_SEQUENCE_NO.getAndIncrement(); @@ -84,8 +81,10 @@ public class DifferentSubtreeTempEntryRenamingStrategy implements newName.add(leafNode); return newName; - } catch (InvalidNameException e) { + } + catch (InvalidNameException e) { throw new org.springframework.ldap.InvalidNameException(e); } } + } diff --git a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationExecutor.java b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationExecutor.java index 45cf3a5e..13533cd1 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationExecutor.java +++ b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationExecutor.java @@ -16,47 +16,45 @@ package org.springframework.transaction.compensating; /** - * Responsible for executing a single recorded operation as well as committing - * or rolling it back, depending on the transaction outcome. Instances of this - * interface are constructed by {@link CompensatingTransactionOperationRecorder} - * objects, supplying them with the information necessary for the respective - * operations. + * Responsible for executing a single recorded operation as well as committing or rolling + * it back, depending on the transaction outcome. Instances of this interface are + * constructed by {@link CompensatingTransactionOperationRecorder} objects, supplying them + * with the information necessary for the respective operations. *

    - * The actual operations performed by the respective methods of this class might - * not be what would originally be expected. E.g. one would expect that the - * {@link #performOperation()} method of a - * CompensatingTransactionOperationExecutor implementation would actually delete - * the entry, leaving it for the {@link #rollback()} method to recreate it using - * data from the original entry. However, this will not always be possible. In - * an LDAP system, for instance, it might not be possible to retrieve all the - * stored data from the original entry. In that case, the - * {@link #performOperation()} method will instead move the entry to a temporary - * location and leave it for the {@link #commit()} method to actually remove the - * entry. - * + * The actual operations performed by the respective methods of this class might not be + * what would originally be expected. E.g. one would expect that the + * {@link #performOperation()} method of a CompensatingTransactionOperationExecutor + * implementation would actually delete the entry, leaving it for the {@link #rollback()} + * method to recreate it using data from the original entry. However, this will not always + * be possible. In an LDAP system, for instance, it might not be possible to retrieve all + * the stored data from the original entry. In that case, the {@link #performOperation()} + * method will instead move the entry to a temporary location and leave it for the + * {@link #commit()} method to actually remove the entry. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ public interface CompensatingTransactionOperationExecutor { + /** - * Rollback the operation, restoring state of the target as it was before - * the operation was performed using the information supplied on creation of - * this instance. + * Rollback the operation, restoring state of the target as it was before the + * operation was performed using the information supplied on creation of this + * instance. */ void rollback(); /** - * Commit the operation. In many cases, this will not require any work at - * all to be performed. However, in some cases there will be interesting - * stuff to do. See class description for elaboration on this. + * Commit the operation. In many cases, this will not require any work at all to be + * performed. However, in some cases there will be interesting stuff to do. See class + * description for elaboration on this. */ void commit(); /** - * Perform the operation. This will most often require performing the - * recorded operation, but in some cases the actual operation performed by - * this method might be something else. See class description for - * elaboration on this. + * Perform the operation. This will most often require performing the recorded + * operation, but in some cases the actual operation performed by this method might be + * something else. See class description for elaboration on this. */ void performOperation(); + } diff --git a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationFactory.java b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationFactory.java index 05539226..d072cb66 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationFactory.java +++ b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationFactory.java @@ -18,27 +18,23 @@ package org.springframework.transaction.compensating; import org.springframework.transaction.compensating.support.DefaultCompensatingTransactionOperationManager; /** - * Factory interface for creating - * {@link CompensatingTransactionOperationRecorder} objects based on operation - * method names. - * + * Factory interface for creating {@link CompensatingTransactionOperationRecorder} objects + * based on operation method names. + * * @author Mattias Hellborg Arthursson * @see DefaultCompensatingTransactionOperationManager * @since 1.2 */ public interface CompensatingTransactionOperationFactory { + /** - * Create an appropriate {@link CompensatingTransactionOperationRecorder} - * instance corresponding to the supplied method name. - * - * @param resource - * The target transaction resource. - * @param method - * the method name to create a - * {@link CompensatingTransactionOperationRecorder} for. - * + * Create an appropriate {@link CompensatingTransactionOperationRecorder} instance + * corresponding to the supplied method name. + * @param resource The target transaction resource. + * @param method the method name to create a + * {@link CompensatingTransactionOperationRecorder} for. * @return a new {@link CompensatingTransactionOperationRecorder} instance. */ - CompensatingTransactionOperationRecorder createRecordingOperation( - Object resource, String method); + CompensatingTransactionOperationRecorder createRecordingOperation(Object resource, String method); + } diff --git a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationManager.java b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationManager.java index 1084d820..33fb81da 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationManager.java +++ b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationManager.java @@ -17,39 +17,35 @@ package org.springframework.transaction.compensating; /** * A CompensatingTransactionOperationManager implementation records and performs - * operations that are to be performed within a compensating transaction. It - * keeps track of compensating actions necessary for rolling back each - * individual operation. - * + * operations that are to be performed within a compensating transaction. It keeps track + * of compensating actions necessary for rolling back each individual operation. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ public interface CompensatingTransactionOperationManager { - /** - * Indicates that the supplied operation (method name) is to be performed. - * This method is responsible for recording the current state (prior to the - * operation), performing the operation, and storing the necessary - * information to roll back or commit the performed operation. - * - * @param resource - * the target resource to perform the operation on. - * @param operation - * The method to be invoked. - * @param args - * Arguments supplied to the method. - */ - void performOperation(Object resource, String operation, - Object[] args); /** - * Rollback all recorded operations by performing each of the recorded - * rollback operations. + * Indicates that the supplied operation (method name) is to be performed. This method + * is responsible for recording the current state (prior to the operation), performing + * the operation, and storing the necessary information to roll back or commit the + * performed operation. + * @param resource the target resource to perform the operation on. + * @param operation The method to be invoked. + * @param args Arguments supplied to the method. + */ + void performOperation(Object resource, String operation, Object[] args); + + /** + * Rollback all recorded operations by performing each of the recorded rollback + * operations. */ void rollback(); /** - * Commit all recorded operations. In many cases this means doing nothing, - * but in some cases some temporary data will need to be removed. + * Commit all recorded operations. In many cases this means doing nothing, but in some + * cases some temporary data will need to be removed. */ void commit(); + } diff --git a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationRecorder.java b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationRecorder.java index a8119ed1..b68a0757 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationRecorder.java +++ b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationRecorder.java @@ -16,26 +16,24 @@ package org.springframework.transaction.compensating; /** - * An implementation of this interface is responsible for recording data and - * supplying a {@link CompensatingTransactionOperationExecutor} to be invoked - * for execution and compensating transaction management of the operation. - * Recording of an operation should not fail (throwing an Exception), but - * instead log the result. - * + * An implementation of this interface is responsible for recording data and supplying a + * {@link CompensatingTransactionOperationExecutor} to be invoked for execution and + * compensating transaction management of the operation. Recording of an operation should + * not fail (throwing an Exception), but instead log the result. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ public interface CompensatingTransactionOperationRecorder { + /** - * Record information about the operation performed and return a - * corresponding {@link CompensatingTransactionOperationExecutor} to be used - * if the operation would need to be rolled back. - * - * @param args - * The arguments that have been sent to the operation. - * @return A {@link CompensatingTransactionOperationExecutor} to be used if - * the recorded operation should need to be rolled back. + * Record information about the operation performed and return a corresponding + * {@link CompensatingTransactionOperationExecutor} to be used if the operation would + * need to be rolled back. + * @param args The arguments that have been sent to the operation. + * @return A {@link CompensatingTransactionOperationExecutor} to be used if the + * recorded operation should need to be rolled back. */ - CompensatingTransactionOperationExecutor recordOperation( - Object[] args); + CompensatingTransactionOperationExecutor recordOperation(Object[] args); + } diff --git a/core/src/main/java/org/springframework/transaction/compensating/support/AbstractCompensatingTransactionManagerDelegate.java b/core/src/main/java/org/springframework/transaction/compensating/support/AbstractCompensatingTransactionManagerDelegate.java index 221c2a67..30c03de4 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/support/AbstractCompensatingTransactionManagerDelegate.java +++ b/core/src/main/java/org/springframework/transaction/compensating/support/AbstractCompensatingTransactionManagerDelegate.java @@ -25,9 +25,8 @@ import org.springframework.transaction.support.TransactionSynchronizationManager /** * Abstract superclass for Compensating TransactionManager delegates. The actual - * transaction work is extracted to a delegate to enable composite Transaction - * Managers. - * + * transaction work is extracted to a delegate to enable composite Transaction Managers. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ @@ -36,27 +35,23 @@ public abstract class AbstractCompensatingTransactionManagerDelegate { private static Logger log = LoggerFactory.getLogger(AbstractCompensatingTransactionManagerDelegate.class); /** - * Close the target resource - the implementation specific resource held in - * the specified {@link CompensatingTransactionHolderSupport}. - * - * @param transactionHolderSupport the - * {@link CompensatingTransactionHolderSupport} that holds the transaction - * specific target resource. + * Close the target resource - the implementation specific resource held in the + * specified {@link CompensatingTransactionHolderSupport}. + * @param transactionHolderSupport the {@link CompensatingTransactionHolderSupport} + * that holds the transaction specific target resource. */ protected abstract void closeTargetResource(CompensatingTransactionHolderSupport transactionHolderSupport); /** - * Get a new implementation specific - * {@link CompensatingTransactionHolderSupport} instance. - * + * Get a new implementation specific {@link CompensatingTransactionHolderSupport} + * instance. * @return a new {@link CompensatingTransactionHolderSupport} instance. */ protected abstract CompensatingTransactionHolderSupport getNewHolder(); /** - * Get the key (normally, a DataSource or similar) that should be used for - * transaction synchronization. - * + * Get the key (normally, a DataSource or similar) that should be used for transaction + * synchronization. * @return the transaction synchronization key */ protected abstract Object getTransactionSynchronizationKey(); @@ -72,8 +67,7 @@ public abstract class AbstractCompensatingTransactionManagerDelegate { } /* - * @see - * org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doBegin * (java.lang.Object, org.springframework.transaction.TransactionDefinition) */ public void doBegin(Object transaction, TransactionDefinition definition) throws TransactionException { @@ -92,8 +86,7 @@ public abstract class AbstractCompensatingTransactionManagerDelegate { } /* - * @see - * org.springframework.jdbc.datasource.DataSourceTransactionManager#doCommit + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doCommit * (org.springframework.transaction.support.DefaultTransactionStatus) */ public void doCommit(DefaultTransactionStatus status) throws TransactionException { @@ -103,8 +96,7 @@ public abstract class AbstractCompensatingTransactionManagerDelegate { } /* - * @see - * org.springframework.jdbc.datasource.DataSourceTransactionManager#doRollback + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doRollback * (org.springframework.transaction.support.DefaultTransactionStatus) */ public void doRollback(DefaultTransactionStatus status) throws TransactionException { @@ -127,4 +119,5 @@ public abstract class AbstractCompensatingTransactionManagerDelegate { txObject.getHolder().clear(); } + } diff --git a/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionHolderSupport.java b/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionHolderSupport.java index 6d299698..a4342752 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionHolderSupport.java +++ b/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionHolderSupport.java @@ -20,30 +20,25 @@ import org.springframework.transaction.support.ResourceHolderSupport; /** * Base class for compensating transaction resource holders. - * + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public abstract class CompensatingTransactionHolderSupport extends - ResourceHolderSupport { +public abstract class CompensatingTransactionHolderSupport extends ResourceHolderSupport { private CompensatingTransactionOperationManager transactionOperationManager; /** * Constructor. - * - * @param manager - * The {@link CompensatingTransactionOperationManager} to use for - * creating Compensating operations. + * @param manager The {@link CompensatingTransactionOperationManager} to use for + * creating Compensating operations. */ - public CompensatingTransactionHolderSupport( - CompensatingTransactionOperationManager manager) { + public CompensatingTransactionHolderSupport(CompensatingTransactionOperationManager manager) { this.transactionOperationManager = manager; } /** * Get the actual transacted resource. - * * @return the transaction's target resource */ protected abstract Object getTransactedResource(); @@ -57,9 +52,8 @@ public abstract class CompensatingTransactionHolderSupport extends } /** - * Get the CompensatingTransactionOperationManager to handle the data for - * the current transaction. - * + * Get the CompensatingTransactionOperationManager to handle the data for the current + * transaction. * @return the CompensatingTransactionOperationManager. */ public CompensatingTransactionOperationManager getTransactionOperationManager() { @@ -67,14 +61,12 @@ public abstract class CompensatingTransactionHolderSupport extends } /** - * Set the CompensatingTransactionOperationManager. For testing purposes - * only. - * - * @param transactionOperationManager - * the CompensatingTransactionOperationManager to use. + * Set the CompensatingTransactionOperationManager. For testing purposes only. + * @param transactionOperationManager the CompensatingTransactionOperationManager to + * use. */ - public void setTransactionOperationManager( - CompensatingTransactionOperationManager transactionOperationManager) { + public void setTransactionOperationManager(CompensatingTransactionOperationManager transactionOperationManager) { this.transactionOperationManager = transactionOperationManager; } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionObject.java b/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionObject.java index aa09e6fa..7bb8599d 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionObject.java +++ b/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionObject.java @@ -16,32 +16,28 @@ package org.springframework.transaction.compensating.support; /** - * Transaction object used by - * {@link AbstractCompensatingTransactionManagerDelegate}. Keeps a reference to - * the {@link CompensatingTransactionHolderSupport} associated with the current - * transaction. - * + * Transaction object used by {@link AbstractCompensatingTransactionManagerDelegate}. + * Keeps a reference to the {@link CompensatingTransactionHolderSupport} associated with + * the current transaction. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ public class CompensatingTransactionObject { + private CompensatingTransactionHolderSupport holder; /** * Constructor. - * - * @param holder - * the {@link CompensatingTransactionHolderSupport} associated - * with the current transaction. + * @param holder the {@link CompensatingTransactionHolderSupport} associated with the + * current transaction. */ - public CompensatingTransactionObject( - CompensatingTransactionHolderSupport holder) { + public CompensatingTransactionObject(CompensatingTransactionHolderSupport holder) { this.holder = holder; } /** * Get the DirContextHolder. - * * @return the DirContextHolder. */ public CompensatingTransactionHolderSupport getHolder() { @@ -49,14 +45,13 @@ public class CompensatingTransactionObject { } /** - * Set the {@link CompensatingTransactionHolderSupport} associated with the + * Set the {@link CompensatingTransactionHolderSupport} associated with the current + * transaction. + * @param holder the {@link CompensatingTransactionHolderSupport} associated with the * current transaction. - * - * @param holder - * the {@link CompensatingTransactionHolderSupport} associated - * with the current transaction. */ public void setHolder(CompensatingTransactionHolderSupport holder) { this.holder = holder; } + } \ No newline at end of file diff --git a/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionUtils.java b/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionUtils.java index 7ea26cb8..16389c17 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionUtils.java +++ b/core/src/main/java/org/springframework/transaction/compensating/support/CompensatingTransactionUtils.java @@ -24,7 +24,7 @@ import java.lang.reflect.Method; /** * Common methods for use with compensating transactions. - * + * * @author Mattias Hellborg Arthursson * @since 1.2 */ @@ -37,37 +37,33 @@ public final class CompensatingTransactionUtils { } /** - * Perform the specified operation, storing the state prior to the operation - * in order to enable commit/rollback later. If no transaction is currently - * active, proceed with the original call on the target. - * - * @param synchronizationKey - * the transaction synchronization key we are operating on - * (typically something similar to a DataSource). - * @param target - * the actual target resource that should be used for invoking - * the operation on should no transaction be active. - * @param method - * name of the method to be invoked. - * @param args - * arguments with which the operation is invoked. + * Perform the specified operation, storing the state prior to the operation in order + * to enable commit/rollback later. If no transaction is currently active, proceed + * with the original call on the target. + * @param synchronizationKey the transaction synchronization key we are operating on + * (typically something similar to a DataSource). + * @param target the actual target resource that should be used for invoking the + * operation on should no transaction be active. + * @param method name of the method to be invoked. + * @param args arguments with which the operation is invoked. */ - public static void performOperation(Object synchronizationKey, - Object target, Method method, Object[] args) throws Throwable { + public static void performOperation(Object synchronizationKey, Object target, Method method, Object[] args) + throws Throwable { CompensatingTransactionHolderSupport transactionResourceHolder = (CompensatingTransactionHolderSupport) TransactionSynchronizationManager .getResource(synchronizationKey); if (transactionResourceHolder != null) { CompensatingTransactionOperationManager transactionOperationManager = transactionResourceHolder .getTransactionOperationManager(); - transactionOperationManager.performOperation( - transactionResourceHolder.getTransactedResource(), method - .getName(), args); - } else { + transactionOperationManager.performOperation(transactionResourceHolder.getTransactedResource(), + method.getName(), args); + } + else { // Perform the target operation try { method.invoke(target, args); - } catch (InvocationTargetException e) { + } + catch (InvocationTargetException e) { throw e.getTargetException(); } } diff --git a/core/src/main/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManager.java b/core/src/main/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManager.java index 0383a0b1..e1e3a7b9 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManager.java +++ b/core/src/main/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManager.java @@ -26,44 +26,38 @@ import org.springframework.transaction.compensating.CompensatingTransactionOpera import java.util.Stack; /** - * Default implementation of {@link CompensatingTransactionOperationManager}. - * Manages a stack of {@link CompensatingTransactionOperationExecutor} objects - * and performs rollback of these in the reverse order. - * + * Default implementation of {@link CompensatingTransactionOperationManager}. Manages a + * stack of {@link CompensatingTransactionOperationExecutor} objects and performs rollback + * of these in the reverse order. + * * @author Mattias Hellborg Arthursson * @since 1.2 */ -public class DefaultCompensatingTransactionOperationManager implements - CompensatingTransactionOperationManager { +public class DefaultCompensatingTransactionOperationManager implements CompensatingTransactionOperationManager { private static Logger log = LoggerFactory.getLogger(DefaultCompensatingTransactionOperationManager.class); - private Stack operationExecutors = - new Stack(); + private Stack operationExecutors = new Stack(); private CompensatingTransactionOperationFactory operationFactory; /** * Set the {@link CompensatingTransactionOperationFactory} to use. - * - * @param operationFactory - * the {@link CompensatingTransactionOperationFactory}. + * @param operationFactory the {@link CompensatingTransactionOperationFactory}. */ - public DefaultCompensatingTransactionOperationManager( - CompensatingTransactionOperationFactory operationFactory) { + public DefaultCompensatingTransactionOperationManager(CompensatingTransactionOperationFactory operationFactory) { this.operationFactory = operationFactory; } /* - * @see org.springframework.transaction.compensating.CompensatingTransactionOperationManager#performOperation(java.lang.Object, - * java.lang.String, java.lang.Object[]) + * @see org.springframework.transaction.compensating. + * CompensatingTransactionOperationManager#performOperation(java.lang.Object, + * java.lang.String, java.lang.Object[]) */ - public void performOperation(Object resource, String operation, - Object[] args) { - CompensatingTransactionOperationRecorder recorder = operationFactory - .createRecordingOperation(resource, operation); - CompensatingTransactionOperationExecutor executor = recorder - .recordOperation(args); + public void performOperation(Object resource, String operation, Object[] args) { + CompensatingTransactionOperationRecorder recorder = operationFactory.createRecordingOperation(resource, + operation); + CompensatingTransactionOperationExecutor executor = recorder.recordOperation(args); executor.performOperation(); @@ -72,7 +66,8 @@ public class DefaultCompensatingTransactionOperationManager implements } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationManager#rollback() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationManager#rollback() */ public void rollback() { log.debug("Performing rollback"); @@ -80,16 +75,15 @@ public class DefaultCompensatingTransactionOperationManager implements CompensatingTransactionOperationExecutor rollbackOperation = operationExecutors.pop(); try { rollbackOperation.rollback(); - } catch (Exception e) { - throw new TransactionSystemException( - "Error occurred during rollback", e); + } + catch (Exception e) { + throw new TransactionSystemException("Error occurred during rollback", e); } } } /** * Get the rollback operations. Used for testing purposes. - * * @return the rollback operations. */ protected Stack getOperationExecutors() { @@ -97,28 +91,27 @@ public class DefaultCompensatingTransactionOperationManager implements } /** - * Set the rollback operations. Package protected - for testing purposes - * only. - * - * @param operationExecutors - * the rollback operations. + * Set the rollback operations. Package protected - for testing purposes only. + * @param operationExecutors the rollback operations. */ void setOperationExecutors(Stack operationExecutors) { this.operationExecutors = operationExecutors; } /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationManager#commit() + * @see org.springframework.ldap.support.transaction. + * CompensatingTransactionOperationManager#commit() */ public void commit() { log.debug("Performing commit"); for (CompensatingTransactionOperationExecutor operationExecutor : operationExecutors) { try { operationExecutor.commit(); - } catch (Exception e) { - throw new TransactionSystemException( - "Error occurred during commit", e); + } + catch (Exception e) { + throw new TransactionSystemException("Error occurred during commit", e); } } } + } diff --git a/core/src/test/java/org/springframework/ldap/NamingExceptionTest.java b/core/src/test/java/org/springframework/ldap/NamingExceptionTest.java index 0ee759e0..4af91715 100644 --- a/core/src/test/java/org/springframework/ldap/NamingExceptionTest.java +++ b/core/src/test/java/org/springframework/ldap/NamingExceptionTest.java @@ -29,38 +29,34 @@ import static org.junit.Assert.assertNull; /** * Unit tests for the NamingException class. - * + * * @author Ulrik Sandberg */ public class NamingExceptionTest { + private ByteArrayOutputStream byteArrayOutputStream; @Test - public void testNamingExceptionWithNonSerializableResolvedObj() - throws Exception { + public void testNamingExceptionWithNonSerializableResolvedObj() throws Exception { javax.naming.NameAlreadyBoundException wrappedException = new javax.naming.NameAlreadyBoundException( "some error"); wrappedException.setResolvedObj(new InitialDirContext()); - NamingException exception = new NameAlreadyBoundException( - wrappedException); + NamingException exception = new NameAlreadyBoundException(wrappedException); writeToStream(exception); NamingException deSerializedException = readFromStream(); - assertNotNull( - "Original exception resolvedObj after serialization should not be null", + assertNotNull("Original exception resolvedObj after serialization should not be null", exception.getResolvedObj()); - assertNull("De-serialized exception resolvedObj should be null", - deSerializedException.getResolvedObj()); + assertNull("De-serialized exception resolvedObj should be null", deSerializedException.getResolvedObj()); } - private NamingException readFromStream() throws IOException, - ClassNotFoundException { - ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( - byteArrayOutputStream.toByteArray()); + private NamingException readFromStream() throws IOException, ClassNotFoundException { + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream in = new ObjectInputStream(byteArrayInputStream); NamingException deSerializedException; try { deSerializedException = (NamingException) in.readObject(); - } finally { + } + finally { in.close(); } return deSerializedException; @@ -72,8 +68,10 @@ public class NamingExceptionTest { try { out.writeObject(exception); out.flush(); - } finally { + } + finally { out.close(); } } + } diff --git a/core/src/test/java/org/springframework/ldap/aot/hint/LdapCoreRuntimeHintsTests.java b/core/src/test/java/org/springframework/ldap/aot/hint/LdapCoreRuntimeHintsTests.java index 63a759f6..5756490e 100644 --- a/core/src/test/java/org/springframework/ldap/aot/hint/LdapCoreRuntimeHintsTests.java +++ b/core/src/test/java/org/springframework/ldap/aot/hint/LdapCoreRuntimeHintsTests.java @@ -36,44 +36,53 @@ public class LdapCoreRuntimeHintsTests { @Test public void ldapCtxFactoryHasHints() { - assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of("com.sun.jndi.ldap.LdapCtxFactory")).withMemberCategories(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) - .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of("com.sun.jndi.ldap.LdapCtxFactory")) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); } @Test public void abstractContextSourceHasHints() { - assertThat(RuntimeHintsPredicates.reflection().onType(AbstractContextSource.class).withMemberCategories(MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS)) - .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(AbstractContextSource.class) + .withMemberCategories(MemberCategory.INTROSPECT_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS)) + .accepts(this.hints); } @Test public void defaultDirObjectFactoryHasHints() { - assertThat(RuntimeHintsPredicates.reflection().onType(DefaultDirObjectFactory.class).withMemberCategories(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) - .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(DefaultDirObjectFactory.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); } @Test public void pagedResultsControlHasHints() { - assertThat(RuntimeHintsPredicates.reflection().onType(PagedResultsControl.class).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); - assertThat(RuntimeHintsPredicates.reflection().onType(com.sun.jndi.ldap.ctl.PagedResultsControl.class).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); - assertThat(RuntimeHintsPredicates.reflection().onType(PagedResultsResponseControl.class).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); - assertThat(RuntimeHintsPredicates.reflection().onType(com.sun.jndi.ldap.ctl.PagedResultsResponseControl.class).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(PagedResultsControl.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) + .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(com.sun.jndi.ldap.ctl.PagedResultsControl.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) + .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(PagedResultsResponseControl.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) + .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(com.sun.jndi.ldap.ctl.PagedResultsResponseControl.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) + .accepts(this.hints); } @Test public void sortControlHasHints() { - assertThat(RuntimeHintsPredicates.reflection().onType(SortControl.class).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); - assertThat(RuntimeHintsPredicates.reflection().onType(com.sun.jndi.ldap.ctl.SortControl.class).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); - assertThat(RuntimeHintsPredicates.reflection().onType(SortResponseControl.class).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); - assertThat(RuntimeHintsPredicates.reflection().onType(com.sun.jndi.ldap.ctl.SortResponseControl.class).withMemberCategories( - MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)).accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(SortControl.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) + .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(com.sun.jndi.ldap.ctl.SortControl.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) + .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(SortResponseControl.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) + .accepts(this.hints); + assertThat(RuntimeHintsPredicates.reflection().onType(com.sun.jndi.ldap.ctl.SortResponseControl.class) + .withMemberCategories(MemberCategory.INVOKE_PUBLIC_METHODS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)) + .accepts(this.hints); } @Test @@ -81,4 +90,5 @@ public class LdapCoreRuntimeHintsTests { assertThat(RuntimeHintsPredicates.reflection().onMethod(SSLSocketFactory.class.getDeclaredMethod("getDefault"))) .accepts(this.hints); } + } diff --git a/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java b/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java index 390855f3..19bf4fb3 100644 --- a/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java +++ b/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java @@ -86,7 +86,8 @@ public class DefaultValuesAuthenticationSourceDecoratorTest { try { tested.afterPropertiesSet(); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -97,7 +98,8 @@ public class DefaultValuesAuthenticationSourceDecoratorTest { try { tested.afterPropertiesSet(); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -108,8 +110,10 @@ public class DefaultValuesAuthenticationSourceDecoratorTest { try { tested.afterPropertiesSet(); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } + } diff --git a/core/src/test/java/org/springframework/ldap/config/DummyAuthenticationSource.java b/core/src/test/java/org/springframework/ldap/config/DummyAuthenticationSource.java index 06693280..849f0b36 100644 --- a/core/src/test/java/org/springframework/ldap/config/DummyAuthenticationSource.java +++ b/core/src/test/java/org/springframework/ldap/config/DummyAuthenticationSource.java @@ -22,6 +22,7 @@ import org.springframework.ldap.core.AuthenticationSource; * @author Mattias Hellborg Arthursson */ public class DummyAuthenticationSource implements AuthenticationSource { + @Override public String getPrincipal() { throw new UnsupportedOperationException(); @@ -31,4 +32,5 @@ public class DummyAuthenticationSource implements AuthenticationSource { public String getCredentials() { throw new UnsupportedOperationException(); } + } diff --git a/core/src/test/java/org/springframework/ldap/config/DummyAuthenticationStrategy.java b/core/src/test/java/org/springframework/ldap/config/DummyAuthenticationStrategy.java index dc7bf981..588c44aa 100644 --- a/core/src/test/java/org/springframework/ldap/config/DummyAuthenticationStrategy.java +++ b/core/src/test/java/org/springframework/ldap/config/DummyAuthenticationStrategy.java @@ -26,13 +26,16 @@ import java.util.Hashtable; * @author Mattias Hellborg Arthursson */ public class DummyAuthenticationStrategy implements DirContextAuthenticationStrategy { + @Override public void setupEnvironment(Hashtable env, String userDn, String password) throws NamingException { throw new UnsupportedOperationException(); } @Override - public DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) throws NamingException { + public DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) + throws NamingException { throw new UnsupportedOperationException(); } + } diff --git a/core/src/test/java/org/springframework/ldap/config/LdapTemplateNamespaceHandlerTest.java b/core/src/test/java/org/springframework/ldap/config/LdapTemplateNamespaceHandlerTest.java index 8c8f23d7..c880ea71 100644 --- a/core/src/test/java/org/springframework/ldap/config/LdapTemplateNamespaceHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/config/LdapTemplateNamespaceHandlerTest.java @@ -71,7 +71,8 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(LdapUtils.emptyLdapName()).isEqualTo(getInternalState(contextSource, "base")); assertThat("uid=admin").isEqualTo(getInternalState(contextSource, "userDn")); assertThat("apassword").isEqualTo(getInternalState(contextSource, "password")); - assertThat(new String[]{"ldap://localhost:389"}).isEqualTo((Object[]) getInternalState(contextSource, "urls")); + assertThat(new String[] { "ldap://localhost:389" }) + .isEqualTo((Object[]) getInternalState(contextSource, "urls")); assertThat(Boolean.FALSE).isEqualTo(getInternalState(contextSource, "pooled")); assertThat(Boolean.FALSE).isEqualTo(getInternalState(contextSource, "anonymousReadOnly")); assertThat((Object) getInternalState(contextSource, "referral")).isNull(); @@ -86,7 +87,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyThatAnonymousReadOnlyContextWillNotBeWrappedInProxy() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-anonymous-read-only.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-anonymous-read-only.xml"); ContextSource contextSource = ctx.getBean(ContextSource.class); assertThat(contextSource).isNotNull(); @@ -111,7 +113,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyReferences() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-references.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-references.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); AuthenticationSource authenticationSource = ctx.getBean(AuthenticationSource.class); DirContextAuthenticationStrategy authenticationStrategy = ctx.getBean(DirContextAuthenticationStrategy.class); @@ -143,7 +146,8 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(LdapUtils.newLdapName("dc=261consulting,dc=com")).isEqualTo(getInternalState(contextSource, "base")); assertThat("uid=admin").isEqualTo(getInternalState(contextSource, "userDn")); assertThat("apassword").isEqualTo(getInternalState(contextSource, "password")); - assertThat(new String[]{"ldap://localhost:389"}).isEqualTo((Object[]) getInternalState(contextSource, "urls")); + assertThat(new String[] { "ldap://localhost:389" }) + .isEqualTo((Object[]) getInternalState(contextSource, "urls")); assertThat(Boolean.TRUE).isEqualTo(getInternalState(contextSource, "pooled")); assertThat(Boolean.FALSE).isEqualTo(getInternalState(contextSource, "anonymousReadOnly")); assertThat("follow").isEqualTo(getInternalState(contextSource, "referral")); @@ -170,13 +174,15 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(LdapUtils.newLdapName("dc=261consulting,dc=com")).isEqualTo(getInternalState(contextSource, "base")); assertThat("uid=admin").isEqualTo(getInternalState(contextSource, "userDn")); assertThat("apassword").isEqualTo(getInternalState(contextSource, "password")); - assertThat(new String[]{"ldap://localhost:389"}).isEqualTo((Object[]) getInternalState(contextSource, "urls")); + assertThat(new String[] { "ldap://localhost:389" }) + .isEqualTo((Object[]) getInternalState(contextSource, "urls")); } @Test public void supportsSpelMultiUrls() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-spel-multiurls.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-spel-multiurls.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); @@ -184,7 +190,7 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(outerContextSource instanceof TransactionAwareContextSourceProxy).isTrue(); ContextSource contextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget(); - assertArrayEquals(new String[] { "ldap://a.localhost:389", "ldap://b.localhost:389" }, + assertArrayEquals(new String[] { "ldap://a.localhost:389", "ldap://b.localhost:389" }, (Object[]) getInternalState(contextSource, "urls")); } @@ -206,7 +212,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParseWithDefaultTransactions() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-transactional-defaults.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-transactional-defaults.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); PlatformTransactionManager transactionManager = ctx.getBean(PlatformTransactionManager.class); @@ -221,8 +228,8 @@ public class LdapTemplateNamespaceHandlerTest { Object delegate = getInternalState(transactionManager, "delegate"); assertThat(contextSource).isSameAs(getInternalState(delegate, "contextSource")); - TempEntryRenamingStrategy renamingStrategy = - (TempEntryRenamingStrategy) getInternalState(delegate, "renamingStrategy"); + TempEntryRenamingStrategy renamingStrategy = (TempEntryRenamingStrategy) getInternalState(delegate, + "renamingStrategy"); assertThat(renamingStrategy instanceof DefaultTempEntryRenamingStrategy).isTrue(); assertThat("_temp").isEqualTo(getInternalState(renamingStrategy, "tempSuffix")); @@ -230,7 +237,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParseTransactionWithDataSource() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-transactional-datasource.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-transactional-datasource.xml"); PlatformTransactionManager transactionManager = ctx.getBean(PlatformTransactionManager.class); assertThat(transactionManager instanceof ContextSourceAndDataSourceTransactionManager).isTrue(); @@ -238,7 +246,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParseTransactionsWithDefaultStrategyAndSuffix() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-transactional-defaults-with-suffix.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-transactional-defaults-with-suffix.xml"); PlatformTransactionManager transactionManager = ctx.getBean(PlatformTransactionManager.class); @@ -246,8 +255,8 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(transactionManager instanceof ContextSourceTransactionManager).isTrue(); Object delegate = getInternalState(transactionManager, "delegate"); - TempEntryRenamingStrategy renamingStrategy = - (TempEntryRenamingStrategy) getInternalState(delegate, "renamingStrategy"); + TempEntryRenamingStrategy renamingStrategy = (TempEntryRenamingStrategy) getInternalState(delegate, + "renamingStrategy"); assertThat(renamingStrategy instanceof DefaultTempEntryRenamingStrategy).isTrue(); assertThat("_thisisthesuffix").isEqualTo(getInternalState(renamingStrategy, "tempSuffix")); @@ -255,7 +264,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParseTransactionsWithDifferentSubtreeStrategy() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-transactional-different-subtree.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-transactional-different-subtree.xml"); PlatformTransactionManager transactionManager = ctx.getBean(PlatformTransactionManager.class); @@ -263,8 +273,8 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(transactionManager instanceof ContextSourceTransactionManager).isTrue(); Object delegate = getInternalState(transactionManager, "delegate"); - TempEntryRenamingStrategy renamingStrategy = - (TempEntryRenamingStrategy) getInternalState(delegate, "renamingStrategy"); + TempEntryRenamingStrategy renamingStrategy = (TempEntryRenamingStrategy) getInternalState(delegate, + "renamingStrategy"); assertThat(renamingStrategy instanceof DifferentSubtreeTempEntryRenamingStrategy).isTrue(); assertThat(LdapUtils.newLdapName("ou=temp")).isEqualTo(getInternalState(renamingStrategy, "subtreeNode")); @@ -273,7 +283,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test @SuppressWarnings("unchecked") public void verifyParsePoolingDefaults() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling-defaults.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-pooling-defaults.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); @@ -286,23 +297,25 @@ public class LdapTemplateNamespaceHandlerTest { Object objectFactory = getInternalState(pooledContextSource, "dirContextPoolableObjectFactory"); assertThat((Object) getInternalState(objectFactory, "contextSource")).isNotNull(); assertThat((Object) getInternalState(objectFactory, "dirContextValidator")).isNull(); - Set> nonTransientExceptions = - (Set>) getInternalState(objectFactory, "nonTransientExceptions"); + Set> nonTransientExceptions = (Set>) getInternalState( + objectFactory, "nonTransientExceptions"); assertThat(nonTransientExceptions).hasSize(1); assertThat(nonTransientExceptions.contains(CommunicationException.class)).isTrue(); - GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool"); + GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, + "keyedObjectPool"); assertThat(objectPool.getMaxActive()).isEqualTo(8); assertThat(objectPool.getMaxTotal()).isEqualTo(-1); assertThat(objectPool.getMaxIdle()).isEqualTo(8); assertThat(objectPool.getMaxWait()).isEqualTo(-1); assertThat(objectPool.getMinIdle()).isEqualTo(0); - assertThat(objectPool.getWhenExhaustedAction()).isEqualTo((byte)1); + assertThat(objectPool.getWhenExhaustedAction()).isEqualTo((byte) 1); } @Test public void verifyParsePoolingSizeSet() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling-configured-poolsize.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-pooling-configured-poolsize.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); @@ -310,19 +323,21 @@ public class LdapTemplateNamespaceHandlerTest { ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget(); assertThat(pooledContextSource).isNotNull(); - GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool"); + GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, + "keyedObjectPool"); assertThat(objectPool.getMaxActive()).isEqualTo(10); assertThat(objectPool.getMaxTotal()).isEqualTo(12); assertThat(objectPool.getMaxIdle()).isEqualTo(11); assertThat(objectPool.getMaxWait()).isEqualTo(13); assertThat(objectPool.getMinIdle()).isEqualTo(14); - assertThat(objectPool.getWhenExhaustedAction()).isEqualTo((byte)0); + assertThat(objectPool.getWhenExhaustedAction()).isEqualTo((byte) 0); } @Test @SuppressWarnings("unchecked") public void verifyParsePoolingValidationSet() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling-test-specified.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-pooling-test-specified.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); @@ -330,13 +345,15 @@ public class LdapTemplateNamespaceHandlerTest { ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget(); assertThat(pooledContextSource).isNotNull(); - GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool"); + GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, + "keyedObjectPool"); assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(123); assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(321); assertThat(objectPool.getNumTestsPerEvictionRun()).isEqualTo(22); Object objectFactory = getInternalState(pooledContextSource, "dirContextPoolableObjectFactory"); - DefaultDirContextValidator validator = (DefaultDirContextValidator) getInternalState(objectFactory, "dirContextValidator"); + DefaultDirContextValidator validator = (DefaultDirContextValidator) getInternalState(objectFactory, + "dirContextValidator"); assertThat(validator.getBase()).isEqualTo("ou=test"); assertThat(validator.getFilter()).isEqualTo("objectclass=person"); @@ -344,8 +361,8 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(validator.getFilter()).isEqualTo("objectclass=person"); assertThat(validator.getSearchControls()).isSameAs(searchControls); - Set> nonTransientExceptions = - (Set>) getInternalState(objectFactory, "nonTransientExceptions"); + Set> nonTransientExceptions = (Set>) getInternalState( + objectFactory, "nonTransientExceptions"); assertThat(nonTransientExceptions).hasSize(2); assertThat(nonTransientExceptions.contains(CommunicationException.class)).isTrue(); assertThat(nonTransientExceptions.contains(CannotProceedException.class)).isTrue(); @@ -358,7 +375,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParsePooling2Defaults() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling2-defaults.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-pooling2-defaults.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); @@ -372,19 +390,20 @@ public class LdapTemplateNamespaceHandlerTest { Object objectFactory = getInternalState(pooledContextSource, "dirContextPooledObjectFactory"); assertThat((Object) getInternalState(objectFactory, "contextSource")).isNotNull(); assertThat((Object) getInternalState(objectFactory, "dirContextValidator")).isNull(); - Set> nonTransientExceptions = - (Set>) getInternalState(objectFactory, "nonTransientExceptions"); + Set> nonTransientExceptions = (Set>) getInternalState( + objectFactory, "nonTransientExceptions"); assertThat(nonTransientExceptions).hasSize(1); assertThat(nonTransientExceptions.contains(CommunicationException.class)).isTrue(); - org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = - (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool"); + org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState( + pooledContextSource, "keyedObjectPool"); assertThat(objectPool.getMaxIdlePerKey()).isEqualTo(8); assertThat(objectPool.getMaxTotal()).isEqualTo(-1); assertThat(objectPool.getMaxTotalPerKey()).isEqualTo(8); assertThat(objectPool.getMinIdlePerKey()).isEqualTo(0); assertThat(objectPool.getBlockWhenExhausted()).isEqualTo(true); - assertThat(objectPool.getEvictionPolicyClassName()).isEqualTo(GenericKeyedObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME); + assertThat(objectPool.getEvictionPolicyClassName()) + .isEqualTo(GenericKeyedObjectPoolConfig.DEFAULT_EVICTION_POLICY_CLASS_NAME); assertThat(objectPool.getFairness()).isEqualTo(false); // ensures the pool is registered @@ -395,7 +414,7 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(objectPool.getLifo()).isEqualTo(true); assertThat(objectPool.getMaxWaitMillis()).isEqualTo(-1L); - assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(1000L*60L*30L); + assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(1000L * 60L * 30L); assertThat(objectPool.getNumTestsPerEvictionRun()).isEqualTo(3); assertThat(objectPool.getSoftMinEvictableIdleTimeMillis()).isEqualTo(-1L); assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(-1L); @@ -407,7 +426,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParsePool2SizeSet() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pool2-configured-poolsize.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-pool2-configured-poolsize.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); @@ -415,15 +435,16 @@ public class LdapTemplateNamespaceHandlerTest { ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget(); assertThat(pooledContextSource).isNotNull(); - org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = - (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool"); + org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState( + pooledContextSource, "keyedObjectPool"); assertThat(objectPool.getMaxTotal()).isEqualTo(12); assertThat(objectPool.getMaxIdlePerKey()).isEqualTo(20); assertThat(objectPool.getMaxTotalPerKey()).isEqualTo(10); assertThat(objectPool.getMaxWaitMillis()).isEqualTo(13); assertThat(objectPool.getMinIdlePerKey()).isEqualTo(14); assertThat(objectPool.getBlockWhenExhausted()).isEqualTo(true); - assertThat(objectPool.getEvictionPolicyClassName()).isEqualTo("org.springframework.ldap.pool2.DummyEvictionPolicy"); + assertThat(objectPool.getEvictionPolicyClassName()) + .isEqualTo("org.springframework.ldap.pool2.DummyEvictionPolicy"); assertThat(objectPool.getFairness()).isEqualTo(true); assertThat(objectPool.getLifo()).isEqualTo(false); @@ -437,7 +458,8 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParsePool2ValidationSet() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pool2-test-specified.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-pool2-test-specified.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); @@ -445,8 +467,8 @@ public class LdapTemplateNamespaceHandlerTest { ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget(); assertThat(pooledContextSource).isNotNull(); - org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = - (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool"); + org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState( + pooledContextSource, "keyedObjectPool"); assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(123); assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(321); assertThat(objectPool.getNumTestsPerEvictionRun()).isEqualTo(22); @@ -458,8 +480,8 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(objectPool.getTestWhileIdle()).isEqualTo(true); Object objectFactory = getInternalState(pooledContextSource, "dirContextPooledObjectFactory"); - org.springframework.ldap.pool2.validation.DefaultDirContextValidator validator = - (org.springframework.ldap.pool2.validation.DefaultDirContextValidator) getInternalState(objectFactory, "dirContextValidator"); + org.springframework.ldap.pool2.validation.DefaultDirContextValidator validator = (org.springframework.ldap.pool2.validation.DefaultDirContextValidator) getInternalState( + objectFactory, "dirContextValidator"); assertThat(validator.getBase()).isEqualTo("ou=test"); assertThat(validator.getFilter()).isEqualTo("objectclass=person"); @@ -467,8 +489,8 @@ public class LdapTemplateNamespaceHandlerTest { assertThat(validator.getFilter()).isEqualTo("objectclass=person"); assertThat(validator.getSearchControls()).isSameAs(searchControls); - Set> nonTransientExceptions = - (Set>) getInternalState(objectFactory, "nonTransientExceptions"); + Set> nonTransientExceptions = (Set>) getInternalState( + objectFactory, "nonTransientExceptions"); assertThat(nonTransientExceptions).hasSize(2); assertThat(nonTransientExceptions.contains(CommunicationException.class)).isTrue(); assertThat(nonTransientExceptions.contains(CannotProceedException.class)).isTrue(); @@ -486,14 +508,16 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParsePoolWithPlaceholders() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling-config-with-placeholders.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-pooling-config-with-placeholders.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget(); assertThat(pooledContextSource).isNotNull(); - GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool"); + GenericKeyedObjectPool objectPool = (GenericKeyedObjectPool) getInternalState(pooledContextSource, + "keyedObjectPool"); assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(10); assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(20); assertThat(objectPool.getMaxWait()).isEqualTo(10); @@ -506,15 +530,16 @@ public class LdapTemplateNamespaceHandlerTest { @Test public void verifyParsePool2WithPlaceholders() { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/ldap-namespace-config-pooling2-config-with-placeholders.xml"); + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/ldap-namespace-config-pooling2-config-with-placeholders.xml"); ContextSource outerContextSource = ctx.getBean(ContextSource.class); assertThat(outerContextSource).isNotNull(); ContextSource pooledContextSource = ((TransactionAwareContextSourceProxy) outerContextSource).getTarget(); assertThat(pooledContextSource).isNotNull(); - org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = - (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState(pooledContextSource, "keyedObjectPool"); + org.apache.commons.pool2.impl.GenericKeyedObjectPool objectPool = (org.apache.commons.pool2.impl.GenericKeyedObjectPool) getInternalState( + pooledContextSource, "keyedObjectPool"); assertThat(objectPool.getTimeBetweenEvictionRunsMillis()).isEqualTo(10); assertThat(objectPool.getMinEvictableIdleTimeMillis()).isEqualTo(20); assertThat(objectPool.getMaxWaitMillis()).isEqualTo(10); @@ -530,4 +555,5 @@ public class LdapTemplateNamespaceHandlerTest { field.setAccessible(true); return (T) ReflectionUtils.getField(field, target); } + } diff --git a/core/src/test/java/org/springframework/ldap/config/MockFactoryBean.java b/core/src/test/java/org/springframework/ldap/config/MockFactoryBean.java index 3237ce40..8d5e9e23 100644 --- a/core/src/test/java/org/springframework/ldap/config/MockFactoryBean.java +++ b/core/src/test/java/org/springframework/ldap/config/MockFactoryBean.java @@ -24,6 +24,7 @@ import static org.mockito.Mockito.mock; * @author Mattias Hellborg Arthursson */ public class MockFactoryBean extends AbstractFactoryBean { + private final Class clazz; public MockFactoryBean(Class clazz) { @@ -39,4 +40,5 @@ public class MockFactoryBean extends AbstractFactoryBean { protected Object createInstance() throws Exception { return mock(clazz); } + } diff --git a/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java b/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java index 3634fea1..998ec233 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java @@ -23,13 +23,13 @@ import java.util.LinkedList; import java.util.List; /** - * Unit tests for the PagedResult class. - * {@link PagedResultsControl} - * + * Unit tests for the PagedResult class. {@link PagedResultsControl} + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ public class PagedResultTest { + @Test public void testEquals() throws Exception { List expectedList = new LinkedList(); @@ -37,18 +37,14 @@ public class PagedResultTest { List otherList = new LinkedList(); otherList.add("different"); - PagedResult originalObject = new PagedResult(expectedList, - new PagedResultsCookie(null)); - PagedResult identicalObject = new PagedResult(expectedList, - new PagedResultsCookie(null)); - PagedResult differentObject = new PagedResult(otherList, - new PagedResultsCookie(null)); - PagedResult subclassObject = new PagedResult(expectedList, - new PagedResultsCookie(null)) { + PagedResult originalObject = new PagedResult(expectedList, new PagedResultsCookie(null)); + PagedResult identicalObject = new PagedResult(expectedList, new PagedResultsCookie(null)); + PagedResult differentObject = new PagedResult(otherList, new PagedResultsCookie(null)); + PagedResult subclassObject = new PagedResult(expectedList, new PagedResultsCookie(null)) { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java b/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java index 63c931d0..b969f39c 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java @@ -20,23 +20,20 @@ import com.gargoylesoftware.base.testing.EqualsTester; import org.junit.Test; public class PagedResultsCookieTest { + @Test public void testEquals() { byte[] expectedCookie = new byte[] { 1, 2 }; byte[] differentCookie = new byte[] { 2, 3 }; - PagedResultsCookie originalObject = new PagedResultsCookie( - expectedCookie); - PagedResultsCookie identicalObject = new PagedResultsCookie( - expectedCookie); - PagedResultsCookie differentObject = new PagedResultsCookie( - differentCookie); - PagedResultsCookie subclassObject = new PagedResultsCookie( - expectedCookie) { + PagedResultsCookie originalObject = new PagedResultsCookie(expectedCookie); + PagedResultsCookie identicalObject = new PagedResultsCookie(expectedCookie); + PagedResultsCookie differentObject = new PagedResultsCookie(differentCookie); + PagedResultsCookie subclassObject = new PagedResultsCookie(expectedCookie) { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java b/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java index 4ff7dca6..ab5ac339 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java @@ -57,19 +57,16 @@ public class PagedResultsDirContextProcessorTest { @Test public void testCreateRequestControl() throws Exception { - PagedResultsControl control = (PagedResultsControl) tested - .createRequestControl(); + PagedResultsControl control = (PagedResultsControl) tested.createRequestControl(); assertThat(control).isNotNull(); } @Test public void testCreateRequestControl_CookieSet() throws Exception { PagedResultsCookie cookie = new PagedResultsCookie(new byte[0]); - PagedResultsDirContextProcessor tested = new PagedResultsDirContextProcessor(20, - cookie); + PagedResultsDirContextProcessor tested = new PagedResultsDirContextProcessor(20, cookie); - PagedResultsControl control = (PagedResultsControl) tested - .createRequestControl(); + PagedResultsControl control = (PagedResultsControl) tested.createRequestControl(); assertThat(control).isNotNull(); } @@ -81,14 +78,13 @@ public class PagedResultsDirContextProcessorTest { byte[] value = new byte[1]; value[0] = pageSize; byte[] cookie = encodeValue(resultSize, value); - PagedResultsResponseControl control = new PagedResultsResponseControl( - "dummy", true, cookie); + PagedResultsResponseControl control = new PagedResultsResponseControl("dummy", true, cookie); when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); tested.postProcess(ldapContextMock); PagedResultsCookie returnedCookie = tested.getCookie(); - assertThat(returnedCookie.getCookie()[0]).isEqualTo((byte)8); + assertThat(returnedCookie.getCookie()[0]).isEqualTo((byte) 8); assertThat(tested.getPageSize()).isEqualTo(20); assertThat(tested.getResultSize()).isEqualTo(50); } @@ -103,11 +99,9 @@ public class PagedResultsDirContextProcessorTest { byte[] cookie = encodeDirSyncValue(resultSize, value); // Using another response control to verify that it is ignored - DirSyncResponseControl control = new DirSyncResponseControl( - "dummy", true, cookie); + DirSyncResponseControl control = new DirSyncResponseControl("dummy", true, cookie); - - when(ldapContextMock.getResponseControls()).thenReturn(new Control[]{control}); + when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); tested.postProcess(ldapContextMock); assertThat(tested.getCookie()).isNull(); @@ -146,8 +140,7 @@ public class PagedResultsDirContextProcessorTest { } } - private byte[] encodeValue(int pageSize, byte[] cookie) - throws IOException { + private byte[] encodeValue(int pageSize, byte[] cookie) throws IOException { // build the ASN.1 encoding BerEncoder ber = new BerEncoder(10 + cookie.length); @@ -163,8 +156,7 @@ public class PagedResultsDirContextProcessorTest { /** * Encode a value suitable for the DirSyncResponseControl used in a test. */ - private byte[] encodeDirSyncValue(int pageSize, byte[] cookie) - throws IOException { + private byte[] encodeDirSyncValue(int pageSize, byte[] cookie) throws IOException { // build the ASN.1 encoding BerEncoder ber = new BerEncoder(10 + cookie.length); @@ -177,4 +169,5 @@ public class PagedResultsDirContextProcessorTest { return ber.getTrimmedBuf(); } + } diff --git a/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java b/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java index 6f969624..9b21d6b9 100644 --- a/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java @@ -79,7 +79,7 @@ public class RequestControlDirContextProcessorTest { @Test public void testPreProcessWithExistingControlOfDifferentClassShouldAdd() throws Exception { SortControl existingControl = new SortControl(new String[] { "cn" }, true); - when(ldapContextMock.getRequestControls()).thenReturn(new Control[]{existingControl}); + when(ldapContextMock.getRequestControls()).thenReturn(new Control[] { existingControl }); tested.preProcess(ldapContextMock); @@ -88,7 +88,7 @@ public class RequestControlDirContextProcessorTest { @Test public void testPreProcessWithExistingControlOfSameClassShouldReplace() throws Exception { - when(ldapContextMock.getRequestControls()).thenReturn(new Control[]{requestControl2Mock}); + when(ldapContextMock.getRequestControls()).thenReturn(new Control[] { requestControl2Mock }); tested.preProcess(ldapContextMock); @@ -102,7 +102,7 @@ public class RequestControlDirContextProcessorTest { tested.setReplaceSameControlEnabled(false); tested.preProcess(ldapContextMock); - verify(ldapContextMock).setRequestControls(new Control[]{requestControl2Mock, requestControlMock}); + verify(ldapContextMock).setRequestControls(new Control[] { requestControl2Mock, requestControlMock }); } @Test @@ -111,7 +111,7 @@ public class RequestControlDirContextProcessorTest { tested.preProcess(ldapContextMock); - verify(ldapContextMock).setRequestControls(new Control[]{requestControlMock}); + verify(ldapContextMock).setRequestControls(new Control[] { requestControlMock }); } @Test @@ -127,4 +127,5 @@ public class RequestControlDirContextProcessorTest { public void testPreProcessWhenNotLdapContextShouldFail() throws Exception { tested.preProcess(dirContextMock); } + } diff --git a/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java b/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java index 0ed185d1..a9bee451 100644 --- a/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java @@ -64,10 +64,9 @@ public class SortControlDirContextProcessorTest { byte sortResult = 0; // success byte[] value = encodeValue(sortResult); - SortResponseControl control = new SortResponseControl( - "dummy", true, value); + SortResponseControl control = new SortResponseControl("dummy", true, value); - when(ldapContextMock.getResponseControls()).thenReturn( new Control[]{control}); + when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); tested.postProcess(ldapContextMock); @@ -80,8 +79,7 @@ public class SortControlDirContextProcessorTest { byte sortResult = 1; byte[] value = encodeValue(sortResult); - SortResponseControl control = new SortResponseControl( - "dummy", true, value); + SortResponseControl control = new SortResponseControl("dummy", true, value); when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); @@ -101,8 +99,7 @@ public class SortControlDirContextProcessorTest { byte[] cookie = encodeDirSyncValue(resultSize, value); // Using another response control to verify that it is ignored - DirSyncResponseControl control = new DirSyncResponseControl("dummy", - true, cookie); + DirSyncResponseControl control = new DirSyncResponseControl("dummy", true, cookie); when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); @@ -139,8 +136,7 @@ public class SortControlDirContextProcessorTest { /** * Encode a value suitable for the DirSyncResponseControl used in a test. */ - private byte[] encodeDirSyncValue(int pageSize, byte[] cookie) - throws IOException { + private byte[] encodeDirSyncValue(int pageSize, byte[] cookie) throws IOException { // build the ASN.1 encoding BerEncoder ber = new BerEncoder(10 + cookie.length); @@ -153,4 +149,5 @@ public class SortControlDirContextProcessorTest { return ber.getTrimmedBuf(); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/ContextMapperCallbackHandlerTest.java b/core/src/test/java/org/springframework/ldap/core/ContextMapperCallbackHandlerTest.java index 0236359c..9ab871c5 100644 --- a/core/src/test/java/org/springframework/ldap/core/ContextMapperCallbackHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/core/ContextMapperCallbackHandlerTest.java @@ -49,8 +49,7 @@ public class ContextMapperCallbackHandlerTest { Binding expectedBinding = new Binding("some name", expectedObject); when(mapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - Object actualResult = tested - .getObjectFromNameClassPair(expectedBinding); + Object actualResult = tested.getObjectFromNameClassPair(expectedBinding); assertThat(actualResult).isEqualTo(expectedResult); } @@ -59,4 +58,5 @@ public class ContextMapperCallbackHandlerTest { Binding expectedBinding = new Binding("some name", null); tested.getObjectFromNameClassPair(expectedBinding); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientListTest.java b/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientListTest.java index dd99b1b7..f663d2ee 100644 --- a/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientListTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientListTest.java @@ -43,7 +43,7 @@ import static org.mockito.Mockito.when; /** * Unit tests for the list operations in {@link LdapTemplate}. - * + * * @author Ulrik Sandberg */ public class DefaultLdapClientListTest { @@ -84,22 +84,19 @@ public class DefaultLdapClientListTest { when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); } - private void setupListAndNamingEnumeration(NameClassPair listResult) - throws NamingException { + private void setupListAndNamingEnumeration(NameClassPair listResult) throws NamingException { when(dirContextMock.list(nameMock)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } - private void setupListBindingsAndNamingEnumeration(NameClassPair listResult) - throws NamingException { + private void setupListBindingsAndNamingEnumeration(NameClassPair listResult) throws NamingException { when(dirContextMock.listBindings(nameMock)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } - private void setupNamingEnumeration(NameClassPair listResult) - throws NamingException { + private void setupNamingEnumeration(NameClassPair listResult) throws NamingException { when(namingEnumerationMock.hasMore()).thenReturn(true, false); when(namingEnumerationMock.next()).thenReturn(listResult); } @@ -122,7 +119,6 @@ public class DefaultLdapClientListTest { assertThat(list.get(0)).isSameAs(NAME); } - @Test public void testList_String() throws NamingException { expectGetReadOnlyContext(); @@ -147,8 +143,8 @@ public class DefaultLdapClientListTest { javax.naming.PartialResultException pre = new javax.naming.PartialResultException(); when(dirContextMock.list(nameMock)).thenThrow(pre); - assertThatExceptionOfType(PartialResultException.class).isThrownBy(() -> - tested.list(NAME).toList(NameClassPair::getName)); + assertThatExceptionOfType(PartialResultException.class) + .isThrownBy(() -> tested.list(NAME).toList(NameClassPair::getName)); verify(dirContextMock).close(); } @@ -159,8 +155,8 @@ public class DefaultLdapClientListTest { javax.naming.PartialResultException pre = new javax.naming.PartialResultException(); when(dirContextMock.list(nameMock)).thenThrow(pre); - assertThatExceptionOfType(PartialResultException.class).isThrownBy(() -> - tested.list(NAME).toStream(NameClassPair::getName).collect(Collectors.toList())); + assertThatExceptionOfType(PartialResultException.class) + .isThrownBy(() -> tested.list(NAME).toStream(NameClassPair::getName).collect(Collectors.toList())); verify(dirContextMock).close(); } @@ -205,8 +201,8 @@ public class DefaultLdapClientListTest { expectGetReadOnlyContext(); javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); when(dirContextMock.list(nameMock)).thenThrow(ne); - assertThatExceptionOfType(LimitExceededException.class).isThrownBy(() -> - tested.list(NAME).toList(NameClassPair::getName)); + assertThatExceptionOfType(LimitExceededException.class) + .isThrownBy(() -> tested.list(NAME).toList(NameClassPair::getName)); verify(dirContextMock).close(); } @@ -215,8 +211,8 @@ public class DefaultLdapClientListTest { expectGetReadOnlyContext(); javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); when(dirContextMock.list(nameMock)).thenThrow(ne); - assertThatExceptionOfType(LimitExceededException.class).isThrownBy(() -> - tested.list(NAME).toStream(NameClassPair::getName).collect(Collectors.toList())); + assertThatExceptionOfType(LimitExceededException.class) + .isThrownBy(() -> tested.list(NAME).toStream(NameClassPair::getName).collect(Collectors.toList())); verify(dirContextMock).close(); } @@ -385,4 +381,5 @@ public class DefaultLdapClientListTest { verify(dirContextMock).close(); verify(namingEnumerationMock).close(); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientLookupTest.java b/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientLookupTest.java index 9183999f..559d031a 100644 --- a/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientLookupTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientLookupTest.java @@ -100,8 +100,7 @@ public class DefaultLdapClientLookupTest { javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); whenSearching(name).thenThrow(ne); - assertThatExceptionOfType(NameNotFoundException.class) - .describedAs("NameNotFoundException expected") + assertThatExceptionOfType(NameNotFoundException.class).describedAs("NameNotFoundException expected") .isThrownBy(() -> tested.search().name(name).toEntry()); verify(dirContextMock).close(); } @@ -142,8 +141,7 @@ public class DefaultLdapClientLookupTest { whenSearching(name).thenThrow(ne); AttributesMapper mapper = (attributes) -> attributes; - assertThatExceptionOfType(NameNotFoundException.class) - .describedAs("NameNotFoundException expected") + assertThatExceptionOfType(NameNotFoundException.class).describedAs("NameNotFoundException expected") .isThrownBy(() -> tested.search().name(name).toObject(mapper)); verify(dirContextMock).close(); } @@ -186,8 +184,7 @@ public class DefaultLdapClientLookupTest { whenSearching(name).thenThrow(ne); ContextMapper mapper = (ctx) -> ctx; - assertThatExceptionOfType(NameNotFoundException.class) - .describedAs("NameNotFoundException expected") + assertThatExceptionOfType(NameNotFoundException.class).describedAs("NameNotFoundException expected") .isThrownBy(() -> tested.search().name(name).toObject(mapper)); verify(dirContextMock).close(); } @@ -205,6 +202,7 @@ public class DefaultLdapClientLookupTest { } private static class NamingEnumeration implements javax.naming.NamingEnumeration { + private final Iterator names; public NamingEnumeration(SearchResult... results) { @@ -235,5 +233,7 @@ public class DefaultLdapClientLookupTest { public SearchResult nextElement() { return this.names.next(); } + } + } diff --git a/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientRenameTest.java b/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientRenameTest.java index 09040e8c..7e6e8c61 100644 --- a/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientRenameTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientRenameTest.java @@ -36,7 +36,7 @@ import static org.mockito.Mockito.when; /** * Unit tests for the rename operations in the LdapTemplate class. - * + * * @author Josh Cummings */ public class DefaultLdapClientRenameTest { @@ -86,7 +86,8 @@ public class DefaultLdapClientRenameTest { try { tested.modify(oldName).name(newName).execute(); fail("NameAlreadyBoundException expected"); - } catch (NameAlreadyBoundException expected) { + } + catch (NameAlreadyBoundException expected) { assertThat(true).isTrue(); } @@ -104,7 +105,8 @@ public class DefaultLdapClientRenameTest { try { tested.modify(oldName).name(newName).execute(); fail("UncategorizedLdapException expected"); - } catch (UncategorizedLdapException expected) { + } + catch (UncategorizedLdapException expected) { assertThat(true).isTrue(); } @@ -121,4 +123,5 @@ public class DefaultLdapClientRenameTest { LdapUtils.newLdapName("o=somethingelse.com")); verify(dirContextMock).close(); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientTest.java b/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientTest.java index 150c9d8a..8f5e35d0 100644 --- a/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DefaultLdapClientTest.java @@ -61,7 +61,7 @@ import static org.mockito.Mockito.when; /** * Unit tests for {@link LdapClient} - * + * * @author Josh Cummings */ public class DefaultLdapClientTest { @@ -95,9 +95,11 @@ public class DefaultLdapClientTest { private DirContext authenticatedContextMock; private AuthenticatedLdapEntryContextCallback entryContextCallbackMock; + private ObjectDirectoryMapper odmMock; private LdapQuery query; + private AuthenticatedLdapEntryContextMapper authContextMapperMock; @Before @@ -144,9 +146,9 @@ public class DefaultLdapClientTest { singleSearchResult(searchControlsOneLevel(), searchResult); - tested.search().query((builder) -> builder.base(nameMock) - .searchScope(SearchScope.ONELEVEL) - .filter("(ou=somevalue)")).toObject(contextMapperMock); + tested.search() + .query((builder) -> builder.base(nameMock).searchScope(SearchScope.ONELEVEL).filter("(ou=somevalue)")) + .toObject(contextMapperMock); verify(contextMapperMock).mapFromContext(any()); verify(dirContextMock).close(); @@ -162,8 +164,7 @@ public class DefaultLdapClientTest { singleSearchResultWithStringBase(controls, searchResult); - tested.search().query((builder) -> builder.base(DEFAULT_BASE.toString()) - .searchScope(SearchScope.ONELEVEL) + tested.search().query((builder) -> builder.base(DEFAULT_BASE.toString()).searchScope(SearchScope.ONELEVEL) .filter("(ou=somevalue)")).toObject(contextMapperMock); verify(contextMapperMock).mapFromContext(any()); @@ -181,9 +182,9 @@ public class DefaultLdapClientTest { singleSearchResult(controls, searchResult); - tested.search().query((builder) -> builder.base(nameMock) - .searchScope(SearchScope.SUBTREE) - .filter("(ou=somevalue)")).toObject(attributesMapperMock); + tested.search() + .query((builder) -> builder.base(nameMock).searchScope(SearchScope.SUBTREE).filter("(ou=somevalue)")) + .toObject(attributesMapperMock); verify(attributesMapperMock).mapFromAttributes(any()); verify(dirContextMock).close(); @@ -200,8 +201,7 @@ public class DefaultLdapClientTest { singleSearchResultWithStringBase(controls, searchResult); - tested.search().query((builder) -> builder.base(DEFAULT_BASE.toString()) - .searchScope(SearchScope.SUBTREE) + tested.search().query((builder) -> builder.base(DEFAULT_BASE.toString()).searchScope(SearchScope.SUBTREE) .filter("(ou=somevalue)")).toObject(attributesMapperMock); verify(attributesMapperMock).mapFromAttributes(any()); @@ -216,15 +216,13 @@ public class DefaultLdapClientTest { controls.setReturningObjFlag(false); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException("some text"); - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenThrow(ne); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenThrow(ne); try { - tested.search().query((builder) -> builder.base(nameMock) - .searchScope(SearchScope.SUBTREE) - .filter("(ou=somevalue)")).toObject(attributesMapperMock); + tested.search().query( + (builder) -> builder.base(nameMock).searchScope(SearchScope.SUBTREE).filter("(ou=somevalue)")) + .toObject(attributesMapperMock); fail("NameNotFoundException expected"); } catch (NameNotFoundException expected) { @@ -241,14 +239,12 @@ public class DefaultLdapClientTest { controls.setReturningObjFlag(false); javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenThrow(ne); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenThrow(ne); try { - tested.search().query((builder) -> builder.base(nameMock) - .filter("(ou=somevalue)")).toObject(attributesMapperMock); + tested.search().query((builder) -> builder.base(nameMock).filter("(ou=somevalue)")) + .toObject(attributesMapperMock); fail("LimitExceededException expected"); } catch (LimitExceededException expected) { @@ -262,9 +258,8 @@ public class DefaultLdapClientTest { public void verifyThatDefaultSearchControlParametersAreAutomaticallyAppliedInSearch() throws Exception { Supplier defaults = mock(Supplier.class); when(defaults.get()).thenReturn(new SearchControls()); - LdapClient tested = LdapClient.builder() - .contextSource(contextSourceMock) - .defaultSearchControls(defaults).build(); + LdapClient tested = LdapClient.builder().contextSource(contextSourceMock).defaultSearchControls(defaults) + .build(); expectGetReadOnlyContext(); @@ -380,7 +375,6 @@ public class DefaultLdapClientTest { verify(dirContextMock).close(); } - @Test public void testRebindWithContext() throws Exception { expectGetReadWriteContext(); @@ -401,8 +395,7 @@ public class DefaultLdapClientTest { Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - tested.bind(nameMock).object(expectedObject).attributes(expectedAttributes) - .replaceExisting(true).execute(); + tested.bind(nameMock).object(expectedObject).attributes(expectedAttributes).replaceExisting(true).execute(); verify(dirContextMock).rebind(nameMock, expectedObject, expectedAttributes); verify(dirContextMock).close(); @@ -415,8 +408,8 @@ public class DefaultLdapClientTest { Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - tested.bind(DEFAULT_BASE.toString()).object(expectedObject).attributes(expectedAttributes) - .replaceExisting(true).execute(); + tested.bind(DEFAULT_BASE.toString()).object(expectedObject).attributes(expectedAttributes).replaceExisting(true) + .execute(); verify(dirContextMock).rebind(DEFAULT_BASE, expectedObject, expectedAttributes); verify(dirContextMock).close(); @@ -522,13 +515,13 @@ public class DefaultLdapClientTest { @Test public void testSearch_PartialResult_IgnoreSet() throws Exception { - LdapClient tested = LdapClient.builder() - .contextSource(contextSourceMock) - .ignorePartialResultException(true).build(); + LdapClient tested = LdapClient.builder().contextSource(contextSourceMock).ignorePartialResultException(true) + .build(); expectGetReadOnlyContext(); - when(dirContextMock.search(eq(nameMock), anyString(), any())).thenThrow(javax.naming.PartialResultException.class); + when(dirContextMock.search(eq(nameMock), anyString(), any())) + .thenThrow(javax.naming.PartialResultException.class); tested.search().name(nameMock).toEntryStream(); @@ -537,7 +530,8 @@ public class DefaultLdapClientTest { @Test public void testAuthenticateWithSingleUserFoundShouldBeSuccessful() throws Exception { - AuthenticatedLdapEntryContextMapper entryContextMapper = mock(AuthenticatedLdapEntryContextMapper.class); + AuthenticatedLdapEntryContextMapper entryContextMapper = mock( + AuthenticatedLdapEntryContextMapper.class); when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); @@ -588,8 +582,8 @@ public class DefaultLdapClientTest { noSearchResults(searchControlsRecursive()); LdapQuery query = LdapQueryBuilder.query().base(nameMock).filter("(ou=somevalue)"); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> - tested.authenticate().query(query).password("password").execute()); + assertThatExceptionOfType(EmptyResultDataAccessException.class) + .isThrownBy(() -> tested.authenticate().query(query).password("password").execute()); verify(dirContextMock).close(); } @@ -602,8 +596,8 @@ public class DefaultLdapClientTest { noSearchResults(searchControlsRecursive()); LdapQuery query = LdapQueryBuilder.query().base(nameMock).filter("(ou=somevalue)"); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> - tested.authenticate().query(query).password("password").execute((ctx, entry) -> new Object())); + assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy( + () -> tested.authenticate().query(query).password("password").execute((ctx, entry) -> new Object())); verify(dirContextMock).close(); } @@ -622,16 +616,14 @@ public class DefaultLdapClientTest { .thenThrow(new UncategorizedLdapException("Authentication failed")); LdapQuery query = LdapQueryBuilder.query().base(nameMock).filter("(ou=somevalue)"); - assertThatExceptionOfType(UncategorizedLdapException.class).isThrownBy(() -> - tested.authenticate().query(query).password("password").execute()); + assertThatExceptionOfType(UncategorizedLdapException.class) + .isThrownBy(() -> tested.authenticate().query(query).password("password").execute()); verify(dirContextMock).close(); } private void noSearchResults(SearchControls controls) throws Exception { - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenReturn(namingEnumerationMock); when(namingEnumerationMock.hasMore()).thenReturn(false); } @@ -641,27 +633,24 @@ public class DefaultLdapClientTest { } private void setupSearchResults(SearchControls controls, SearchResult... searchResults) throws Exception { - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenReturn(namingEnumerationMock); - if(searchResults.length == 1) { + if (searchResults.length == 1) { when(namingEnumerationMock.hasMore()).thenReturn(true, false); when(namingEnumerationMock.next()).thenReturn(searchResults[0]); - } else if(searchResults.length ==2) { + } + else if (searchResults.length == 2) { when(namingEnumerationMock.hasMore()).thenReturn(true, true, false); when(namingEnumerationMock.next()).thenReturn(searchResults[0], searchResults[1]); - } else { + } + else { throw new IllegalArgumentException("Cannot handle " + searchResults.length + " search results"); } } - private void singleSearchResultWithStringBase(SearchControls controls, SearchResult searchResult) - throws Exception { - when(dirContextMock.search( - eq(DEFAULT_BASE), - eq("(ou=somevalue)"), + private void singleSearchResultWithStringBase(SearchControls controls, SearchResult searchResult) throws Exception { + when(dirContextMock.search(eq(DEFAULT_BASE), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); when(namingEnumerationMock.hasMore()).thenReturn(true, false); @@ -683,6 +672,7 @@ public class DefaultLdapClientTest { } private static class SearchControlsMatcher implements ArgumentMatcher { + private final SearchControls controls; public SearchControlsMatcher(SearchControls controls) { @@ -705,5 +695,7 @@ public class DefaultLdapClientTest { throw new IllegalArgumentException(); } } + } + } diff --git a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java index 24c27462..7132f844 100644 --- a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java @@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests that serve as regression tests for bugs that have been fixed. - * + * * @author Luke Taylor */ public class DirContextAdapterBugTest { @@ -58,11 +58,11 @@ public class DirContextAdapterBugTest { } /** - * This test starts with an array with a null value in it (because that's - * how BasicAttributes will do it), changes to [a], and then - * changes to null. The current code interprets this as a - * change and will replace the original array with an empty array. - * + * This test starts with an array with a null value in it (because that's how + * BasicAttributes will do it), changes to [a], and then changes to + * null. The current code interprets this as a change and will replace + * the original array with an empty array. + * * TODO Is this correct behaviour? */ @Test @@ -88,9 +88,12 @@ public class DirContextAdapterBugTest { } private static class UpdateAdapter extends DirContextAdapter { + public UpdateAdapter(Attributes attrs, Name dn) { super(attrs, dn); setUpdateMode(true); } + } + } diff --git a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterTest.java b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterTest.java index 4e98b897..554c71a1 100644 --- a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterTest.java @@ -44,10 +44,10 @@ import static org.assertj.core.api.Assertions.fail; * @author Ulrik Sandberg */ public class DirContextAdapterTest { + private static final LdapName BASE_NAME = LdapUtils.newLdapName("dc=jayway,dc=se"); - private static final LdapName DUMMY_NAME = LdapUtils.newLdapName( - "c=SE,dc=jayway,dc=se"); + private static final LdapName DUMMY_NAME = LdapUtils.newLdapName("c=SE,dc=jayway,dc=se"); private DirContextAdapter tested; @@ -92,9 +92,11 @@ public class DirContextAdapterTest { final Attributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("abc")); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(attrs, null); } + } tested = new TestableDirContextAdapter(); String s = tested.getStringAttribute("abc"); @@ -106,9 +108,11 @@ public class DirContextAdapterTest { final Attributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("abc")); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(attrs, null); } + } tested = new TestableDirContextAdapter(); boolean result = tested.attributeExists("abc"); @@ -126,9 +130,11 @@ public class DirContextAdapterTest { final Attributes attrs = new BasicAttributes(); attrs.put(new BasicAttribute("abc", "def")); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(attrs, null); } + } tested = new TestableDirContextAdapter(); String s = tested.getStringAttribute("abc"); @@ -143,9 +149,11 @@ public class DirContextAdapterTest { multi.add("234"); attrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(attrs, null); } + } tested = new TestableDirContextAdapter(); String s[] = tested.getStringAttributes("abc"); @@ -161,9 +169,11 @@ public class DirContextAdapterTest { multi.add(new Object()); attrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(attrs, null); } + } tested = new TestableDirContextAdapter(); try { @@ -181,9 +191,11 @@ public class DirContextAdapterTest { Attribute multi = new BasicAttribute("abc"); attrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(attrs, null); } + } tested = new TestableDirContextAdapter(); String s[] = tested.getStringAttributes("abc"); @@ -205,9 +217,11 @@ public class DirContextAdapterTest { multi.add("234"); attrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(attrs, null); } + } tested = new TestableDirContextAdapter(); SortedSet s = tested.getAttributeSortedStringSet("abc"); @@ -222,9 +236,11 @@ public class DirContextAdapterTest { public void testGetAttributesSortedStringSetNotExists() throws Exception { final Attributes attrs = new BasicAttributes(); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(attrs, null); } + } tested = new TestableDirContextAdapter(); SortedSet s = tested.getAttributeSortedStringSet("abc"); @@ -242,8 +258,7 @@ public class DirContextAdapterTest { } @Test - public void testAddAttributeValueAttributeWithOtherValueExists() - throws NamingException { + public void testAddAttributeValueAttributeWithOtherValueExists() throws NamingException { tested.setAttribute(new BasicAttribute("abc", "321")); // Perform test @@ -256,8 +271,7 @@ public class DirContextAdapterTest { } @Test - public void testAddAttributeValueAttributeWithSameValueExists() - throws NamingException { + public void testAddAttributeValueAttributeWithSameValueExists() throws NamingException { tested.setAttribute(new BasicAttribute("abc", "123")); // Perform test @@ -286,8 +300,7 @@ public class DirContextAdapterTest { } @Test - public void testAddAttributeValueInUpdateModeAttributeWhenOtherValueExistsInOrigAttrs() - throws NamingException { + public void testAddAttributeValueInUpdateModeAttributeWhenOtherValueExistsInOrigAttrs() throws NamingException { tested.setAttribute(new BasicAttribute("abc", "321")); tested.setUpdateMode(true); @@ -324,8 +337,7 @@ public class DirContextAdapterTest { } @Test - public void testAddAttributeValueInUpdateModeAttributeWithOtherValueExistsInUpdAttrs() - throws NamingException { + public void testAddAttributeValueInUpdateModeAttributeWithOtherValueExistsInUpdAttrs() throws NamingException { tested.setUpdateMode(true); tested.setAttributeValue("abc", "321"); @@ -344,8 +356,7 @@ public class DirContextAdapterTest { } @Test - public void testAddAttributeValueInUpdateModeAttributeWithSameValueExistsInUpdAttrs() - throws NamingException { + public void testAddAttributeValueInUpdateModeAttributeWithSameValueExistsInUpdAttrs() throws NamingException { tested.setUpdateMode(true); tested.setAttributeValue("abc", "123"); @@ -393,8 +404,7 @@ public class DirContextAdapterTest { } @Test - public void testRemoveAttributeValueAttributeWithOtherValueExists() - throws NamingException { + public void testRemoveAttributeValueAttributeWithOtherValueExists() throws NamingException { tested.setAttribute(new BasicAttribute("abc", "321")); // Perform test @@ -420,8 +430,7 @@ public class DirContextAdapterTest { } @Test - public void testRemoveAttributeValueAttributeWithOtherAndSameValueExists() - throws NamingException { + public void testRemoveAttributeValueAttributeWithOtherAndSameValueExists() throws NamingException { BasicAttribute basicAttribute = new BasicAttribute("abc"); basicAttribute.add("123"); basicAttribute.add("321"); @@ -465,8 +474,7 @@ public class DirContextAdapterTest { } @Test - public void testRemoveAttributeValueInUpdateModeOtherValueExistsInUpdatedAttrs() - throws NamingException { + public void testRemoveAttributeValueInUpdateModeOtherValueExistsInUpdatedAttrs() throws NamingException { tested.setUpdateMode(true); tested.setAttributeValue("abc", "321"); @@ -484,8 +492,7 @@ public class DirContextAdapterTest { } @Test - public void testRemoveAttributeValueInUpdateModeOtherAndSameValueExistsInUpdatedAttrs() - throws NamingException { + public void testRemoveAttributeValueInUpdateModeOtherAndSameValueExistsInUpdatedAttrs() throws NamingException { tested.setUpdateMode(true); tested.setAttributeValues("abc", new String[] { "321", "123" }); @@ -518,8 +525,7 @@ public class DirContextAdapterTest { } @Test - public void testRemoveAttributeValueInUpdateModeSameAndOtherValueExistsInOrigAttrs() - throws NamingException { + public void testRemoveAttributeValueInUpdateModeSameAndOtherValueExistsInOrigAttrs() throws NamingException { BasicAttribute basicAttribute = new BasicAttribute("abc"); basicAttribute.add("123"); basicAttribute.add("321"); @@ -606,8 +612,7 @@ public class DirContextAdapterTest { @Test public void testGetDn_BasePath() { - DirContextAdapter tested = new DirContextAdapter(null, DUMMY_NAME, - BASE_NAME); + DirContextAdapter tested = new DirContextAdapter(null, DUMMY_NAME, BASE_NAME); Name result = tested.getDn(); assertThat(result).isEqualTo(DUMMY_NAME); } @@ -621,8 +626,7 @@ public class DirContextAdapterTest { @Test public void testGetNameInNamespace_BasePath() { - DirContextAdapter tested = new DirContextAdapter(null, - LdapUtils.newLdapName("c=SE"), BASE_NAME); + DirContextAdapter tested = new DirContextAdapter(null, LdapUtils.newLdapName("c=SE"), BASE_NAME); String result = tested.getNameInNamespace(); assertThat(result).isEqualTo(DUMMY_NAME.toString()); } @@ -663,10 +667,12 @@ public class DirContextAdapterTest { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); @@ -704,10 +710,12 @@ public class DirContextAdapterTest { abc.add("456"); fixtureAttrs.put(abc); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); @@ -727,10 +735,12 @@ public class DirContextAdapterTest { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); tested.setAttributeValue("abc", "234"); // change @@ -748,10 +758,12 @@ public class DirContextAdapterTest { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -769,10 +781,12 @@ public class DirContextAdapterTest { multi.add("qwe"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -792,10 +806,12 @@ public class DirContextAdapterTest { multi.add("qwe"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); tested.setAttributeValues("abc", new String[] { "qwe", "123" }); @@ -814,10 +830,12 @@ public class DirContextAdapterTest { multi.add("qwe"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -837,23 +855,23 @@ public class DirContextAdapterTest { * https://jira.springframework.org/browse/LDAP-96 */ @Test - public void testChangeMultiAttributeOrderDoesMatterLDAP96() - throws Exception { + public void testChangeMultiAttributeOrderDoesMatterLDAP96() throws Exception { final Attributes fixtureAttrs = new BasicAttributes(); Attribute multi = new BasicAttribute("title"); multi.add("Juergen"); multi.add("George"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); - tested.setAttributeValues("title", new String[] { "Jim", "George", - "Juergen" }, true); + tested.setAttributeValues("title", new String[] { "Jim", "George", "Juergen" }, true); // change ModificationItem[] mods = tested.getModificationItems(); @@ -873,16 +891,16 @@ public class DirContextAdapterTest { multi.add("qwe"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); - tested - .setAttributeValues("abc", - new String[] { "123", "qwe", "klytt" }); + tested.setAttributeValues("abc", new String[] { "123", "qwe", "klytt" }); ModificationItem[] modificationItems = tested.getModificationItems(); assertThat(modificationItems.length).isEqualTo(1); @@ -898,10 +916,12 @@ public class DirContextAdapterTest { multi.add("qwe"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -922,10 +942,12 @@ public class DirContextAdapterTest { multi.add("rty"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -946,10 +968,12 @@ public class DirContextAdapterTest { multi.add("qwe"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -968,10 +992,12 @@ public class DirContextAdapterTest { multi.add("qwe"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -991,15 +1017,16 @@ public class DirContextAdapterTest { multi.add("uio"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); - tested.setAttributeValues("abc", new String[] { "123", "qwe", "klytt", - "kalle" }); + tested.setAttributeValues("abc", new String[] { "123", "qwe", "klytt", "kalle" }); ModificationItem[] modificationItems = tested.getModificationItems(); assertThat(modificationItems.length).isEqualTo(2); @@ -1027,10 +1054,12 @@ public class DirContextAdapterTest { multi.add("qwe"); fixtureAttrs.put(multi); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -1046,10 +1075,12 @@ public class DirContextAdapterTest { final Attributes fixtureAttrs = new BasicAttributes(); fixtureAttrs.put(new BasicAttribute("abc", "123")); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -1080,10 +1111,12 @@ public class DirContextAdapterTest { fixtureAttrs.put(new BasicAttribute("abc", "123")); fixtureAttrs.put(new BasicAttribute("qwe", "42")); class TestableDirContextAdapter extends DirContextAdapter { + public TestableDirContextAdapter() { super(fixtureAttrs, null); setUpdateMode(true); } + } tested = new TestableDirContextAdapter(); assertThat(tested.isUpdateMode()).isTrue(); @@ -1100,8 +1133,7 @@ public class DirContextAdapterTest { String[] modNames = tested.getNamesOfModifiedAttributes(); assertThat(modNames.length).isEqualTo(3); - ModificationItem mod = getModificationItem(mods, - DirContext.REPLACE_ATTRIBUTE); + ModificationItem mod = getModificationItem(mods, DirContext.REPLACE_ATTRIBUTE); assertThat(mod).isNotNull(); attr = mod.getAttribute(); assertThat((String) attr.getID()).isEqualTo("abc"); @@ -1132,9 +1164,8 @@ public class DirContextAdapterTest { } /** - * Test for LDAP-15: DirContextAdapter.setAttribute(). Verifies that setting - * an Attribute should modify updatedAttrs if in update mode. - * + * Test for LDAP-15: DirContextAdapter.setAttribute(). Verifies that setting an + * Attribute should modify updatedAttrs if in update mode. * @throws NamingException */ @Test @@ -1173,8 +1204,7 @@ public class DirContextAdapterTest { assertThat(result).isNull(); } - private ModificationItem getModificationItem(ModificationItem[] mods, - int operation) { + private ModificationItem getModificationItem(ModificationItem[] mods, int operation) { for (int i = 0; i < mods.length; i++) { if (mods[i].getModificationOp() == operation) return mods[i]; @@ -1183,8 +1213,7 @@ public class DirContextAdapterTest { } @Test - public void testModifyMultiValueAttributeModificationOrder() - throws NamingException { + public void testModifyMultiValueAttributeModificationOrder() throws NamingException { BasicAttribute attribute = new BasicAttribute("abc"); attribute.add("Some Person"); attribute.add("Some Other Person"); @@ -1192,8 +1221,7 @@ public class DirContextAdapterTest { tested.setAttribute(attribute); tested.setUpdateMode(true); - tested.setAttributeValues("abc", new String[] { "some person", - "Some Other Person" }); + tested.setAttributeValues("abc", new String[] { "some person", "Some Other Person" }); // Perform test ModificationItem[] modificationItems = tested.getModificationItems(); @@ -1223,12 +1251,11 @@ public class DirContextAdapterTest { } /** - * Test for LDAP-109, since also DirContextAdapter may get an invalid - * CompositeName sent to it. + * Test for LDAP-109, since also DirContextAdapter may get an invalid CompositeName + * sent to it. */ @Test - public void testConstructorUsingCompositeNameWithBackslashes() - throws Exception { + public void testConstructorUsingCompositeNameWithBackslashes() throws Exception { CompositeName compositeName = new CompositeName(); compositeName.add("cn=Some\\\\Person6,ou=company1,c=Sweden"); DirContextAdapter adapter = new DirContextAdapter(compositeName); @@ -1246,7 +1273,8 @@ public class DirContextAdapterTest { BasicAttributes attributes = new BasicAttributes(); attributes.put("uniqueMember", "cn=john doe, ou=company"); - DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups")); + DirContextAdapter tested = new DirContextAdapter(attributes, + LdapUtils.newLdapName("cn=administrators, ou=groups")); tested.setUpdateMode(true); tested.addAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company")); @@ -1259,7 +1287,8 @@ public class DirContextAdapterTest { BasicAttributes attributes = new BasicAttributes(); attributes.put("uniqueMember", "cn=john doe,OU=company"); - DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups")); + DirContextAdapter tested = new DirContextAdapter(attributes, + LdapUtils.newLdapName("cn=administrators, ou=groups")); tested.setUpdateMode(true); tested.addAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company")); @@ -1272,7 +1301,8 @@ public class DirContextAdapterTest { BasicAttributes attributes = new BasicAttributes(); attributes.put("uniqueMember", "cn=john doe,OU=company"); - DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups")); + DirContextAdapter tested = new DirContextAdapter(attributes, + LdapUtils.newLdapName("cn=administrators, ou=groups")); tested.setUpdateMode(true); tested.removeAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company")); @@ -1291,7 +1321,8 @@ public class DirContextAdapterTest { attribute.add("cn=jane doe, ou=company"); attributes.put(attribute); - DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups")); + DirContextAdapter tested = new DirContextAdapter(attributes, + LdapUtils.newLdapName("cn=administrators, ou=groups")); tested.setUpdateMode(true); tested.removeAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company")); @@ -1309,7 +1340,8 @@ public class DirContextAdapterTest { BasicAttributes attributes = new BasicAttributes(); attributes.put("uniqueMember", "cn=john doe, ou=company"); - DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups")); + DirContextAdapter tested = new DirContextAdapter(attributes, + LdapUtils.newLdapName("cn=administrators, ou=groups")); tested.setUpdateMode(true); tested.addAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=jane doe, ou=company")); @@ -1327,7 +1359,8 @@ public class DirContextAdapterTest { BasicAttributes attributes = new BasicAttributes(); attributes.put("uniqueMember", "cn=john doe, ou=company"); - DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups")); + DirContextAdapter tested = new DirContextAdapter(attributes, + LdapUtils.newLdapName("cn=administrators, ou=groups")); tested.setUpdateMode(true); tested.setAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=john doe, ou=company")); @@ -1340,10 +1373,11 @@ public class DirContextAdapterTest { BasicAttributes attributes = new BasicAttributes(); attributes.put("uniqueMember", "cn=john doe, ou=company"); - DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups")); + DirContextAdapter tested = new DirContextAdapter(attributes, + LdapUtils.newLdapName("cn=administrators, ou=groups")); tested.setUpdateMode(true); - tested.setAttributeValues("uniqueMember", new Object[]{LdapUtils.newLdapName("cn=john doe, ou=company")}); + tested.setAttributeValues("uniqueMember", new Object[] { LdapUtils.newLdapName("cn=john doe, ou=company") }); ModificationItem[] modificationItems = tested.getModificationItems(); assertThat(modificationItems.length).isEqualTo(0); } @@ -1353,13 +1387,12 @@ public class DirContextAdapterTest { BasicAttributes attributes = new BasicAttributes(); attributes.put("uniqueMember", "cn=john doe, ou=company"); - DirContextAdapter tested = new DirContextAdapter(attributes, LdapUtils.newLdapName("cn=administrators, ou=groups")); + DirContextAdapter tested = new DirContextAdapter(attributes, + LdapUtils.newLdapName("cn=administrators, ou=groups")); tested.setUpdateMode(true); - tested.setAttributeValues("uniqueMember", new Object[]{ - LdapUtils.newLdapName("cn=john doe, ou=company"), - LdapUtils.newLdapName("cn=jane doe, ou=company") - }); + tested.setAttributeValues("uniqueMember", new Object[] { LdapUtils.newLdapName("cn=john doe, ou=company"), + LdapUtils.newLdapName("cn=jane doe, ou=company") }); ModificationItem[] modificationItems = tested.getModificationItems(); assertThat(modificationItems.length).isEqualTo(1); @@ -1369,4 +1402,5 @@ public class DirContextAdapterTest { assertThat(modificationItem.getAttribute().getID()).isEqualTo("uniqueMember"); assertThat(modificationItem.getAttribute().get()).isEqualTo("cn=jane doe, ou=company"); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java index 2d8b6d60..7eee79ca 100644 --- a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java @@ -23,7 +23,7 @@ import static org.assertj.core.api.Assertions.fail; /** * Unit tests for {@link DistinguishedNameEditor}. - * + * * @author Mattias Hellborg Arthursson */ public class DistinguishedNameEditorTest { @@ -73,4 +73,5 @@ public class DistinguishedNameEditorTest { String text = tested.getAsText(); assertThat(text).isNull(); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java index c2881246..659b7302 100644 --- a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.fail; /** * Unit tests for the {@link DistinguishedName} class. - * + * * @author Adam Skogman * @author Mattias Hellborg Arthursson */ @@ -57,8 +57,8 @@ public class DistinguishedNameTest { } /** - * CompositeName screws up distinguished names when there are double qoutes, as described in Ldap237. - * + * CompositeName screws up distinguished names when there are double qoutes, as + * described in Ldap237. * @throws InvalidNameException */ @Test @@ -180,6 +180,7 @@ public class DistinguishedNameTest { // a subclass with the same values as the original final Object subclassObject = new DistinguishedName("cn=john.doe, OU=Users,OU=Some company,C=SE") { private static final long serialVersionUID = 1L; + }; new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); @@ -615,7 +616,7 @@ public class DistinguishedNameTest { try { String dnString = "ou=foo,Ou=bar,oU=baz,OU=bim"; DistinguishedName name = new DistinguishedName(dnString); - + // First check the default assertThat(name.toString()).isEqualTo("ou=foo,ou=bar,ou=baz,ou=bim"); @@ -638,7 +639,7 @@ public class DistinguishedNameTest { // First check the default assertThat(name.toString()).isEqualTo("ou=foo,ou=bar,ou=baz,ou=bim"); - + System.setProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY, DistinguishedName.KEY_CASE_FOLD_UPPER); name = new DistinguishedName(dnString); System.out.println(dnString + " folded as \"" + DistinguishedName.KEY_CASE_FOLD_UPPER + "\": " + name); @@ -658,7 +659,7 @@ public class DistinguishedNameTest { // First check the default assertThat(name.toString()).isEqualTo("ou=foo,ou=bar,ou=baz,ou=bim"); - + System.setProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY, DistinguishedName.KEY_CASE_FOLD_LOWER); name = new DistinguishedName(dnString); System.out.println(dnString + " folded as \"" + DistinguishedName.KEY_CASE_FOLD_LOWER + "\": " + name); @@ -678,7 +679,7 @@ public class DistinguishedNameTest { // First check the default assertThat(name.toString()).isEqualTo("ou=foo,ou=bar,ou=baz,ou=bim"); - + System.setProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY, "whatever"); name = new DistinguishedName(dnString); System.out.println(dnString + " folded as \"whatever\": " + name); @@ -692,19 +693,17 @@ public class DistinguishedNameTest { @Test public void testHashSignLdap229() { - assertThat(new DistinguishedName("cn=Foo\\#Bar")).isEqualTo( - new DistinguishedName("cn=Foo#Bar")); + assertThat(new DistinguishedName("cn=Foo\\#Bar")).isEqualTo(new DistinguishedName("cn=Foo#Bar")); } @Test public void testEqualsSignLdap229() { - assertThat(new DistinguishedName("cn=Foo\\=Bar")).isEqualTo( - new DistinguishedName("cn=Foo=Bar")); + assertThat(new DistinguishedName("cn=Foo\\=Bar")).isEqualTo(new DistinguishedName("cn=Foo=Bar")); } @Test public void testSpaceSignLdap229() { - assertThat(new DistinguishedName("cn=Foo\\ Bar")).isEqualTo( - new DistinguishedName("cn=Foo Bar")); + assertThat(new DistinguishedName("cn=Foo\\ Bar")).isEqualTo(new DistinguishedName("cn=Foo Bar")); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java b/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java index 6013dcf9..8ad21545 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java @@ -21,7 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for LdapRdnComponent. - * + * * @author Mattias Hellborg Arthursson */ public class LdapRdnComponentTest { diff --git a/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java b/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java index 32e4585d..ccff7c74 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java @@ -24,7 +24,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Unit test for the LdapRdn class. - * + * * @author Adam Skogman */ public class LdapRdnTest { @@ -172,10 +172,10 @@ public class LdapRdnTest { // a subclass with the same values as the original final Object subclassObject = new LdapRdn("cn", "john.doe") { private static final long serialVersionUID = 1L; + }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } @Test @@ -256,4 +256,5 @@ public class LdapRdnTest { int result = rdn1.compareTo(rdn2); assertThat(result > 0).isTrue(); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java index c467b62a..a5425411 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java @@ -38,7 +38,7 @@ import static org.mockito.Mockito.when; /** * Unit tests for the list operations in {@link LdapTemplate}. - * + * * @author Ulrik Sandberg */ public class LdapTemplateListTest { @@ -87,36 +87,31 @@ public class LdapTemplateListTest { when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); } - private void setupStringListAndNamingEnumeration(NameClassPair listResult) - throws NamingException { + private void setupStringListAndNamingEnumeration(NameClassPair listResult) throws NamingException { when(dirContextMock.list(NAME)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } - private void setupListAndNamingEnumeration(NameClassPair listResult) - throws NamingException { + private void setupListAndNamingEnumeration(NameClassPair listResult) throws NamingException { when(dirContextMock.list(nameMock)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } - private void setupStringListBindingsAndNamingEnumeration( - NameClassPair listResult) throws NamingException { + private void setupStringListBindingsAndNamingEnumeration(NameClassPair listResult) throws NamingException { when(dirContextMock.listBindings(NAME)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } - private void setupListBindingsAndNamingEnumeration(NameClassPair listResult) - throws NamingException { + private void setupListBindingsAndNamingEnumeration(NameClassPair listResult) throws NamingException { when(dirContextMock.listBindings(nameMock)).thenReturn(namingEnumerationMock); setupNamingEnumeration(listResult); } - private void setupNamingEnumeration(NameClassPair listResult) - throws NamingException { + private void setupNamingEnumeration(NameClassPair listResult) throws NamingException { when(namingEnumerationMock.hasMore()).thenReturn(true, false); when(namingEnumerationMock.next()).thenReturn(listResult); } @@ -197,7 +192,8 @@ public class LdapTemplateListTest { try { tested.list(NAME); fail("PartialResultException expected"); - } catch (PartialResultException expected) { + } + catch (PartialResultException expected) { assertThat(true).isTrue(); } @@ -231,7 +227,8 @@ public class LdapTemplateListTest { try { tested.list(NAME); fail("LimitExceededException expected"); - } catch (LimitExceededException expected) { + } + catch (LimitExceededException expected) { assertThat(true).isTrue(); } @@ -319,4 +316,5 @@ public class LdapTemplateListTest { assertThat(list).hasSize(1); assertThat(list.get(0)).isSameAs(expectedResult); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java index 03c31cc8..b8891c46 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java @@ -52,6 +52,7 @@ public class LdapTemplateLookupTest { private ContextMapper contextMapperMock; private LdapTemplate tested; + private ObjectDirectoryMapper odmMock; @Before @@ -116,7 +117,8 @@ public class LdapTemplateLookupTest { try { tested.lookup(nameMock); fail("NameNotFoundException expected"); - } catch (NameNotFoundException expected) { + } + catch (NameNotFoundException expected) { assertThat(true).isTrue(); } @@ -152,8 +154,7 @@ public class LdapTemplateLookupTest { Object expected = new Object(); when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); - Object actual = tested - .lookup(DEFAULT_BASE_STRING, attributesMapperMock); + Object actual = tested.lookup(DEFAULT_BASE_STRING, attributesMapperMock); verify(dirContextMock).close(); @@ -170,7 +171,8 @@ public class LdapTemplateLookupTest { try { tested.lookup(nameMock, attributesMapperMock); fail("NameNotFoundException expected"); - } catch (NameNotFoundException expected) { + } + catch (NameNotFoundException expected) { assertThat(true).isTrue(); } @@ -207,7 +209,7 @@ public class LdapTemplateLookupTest { when(dirContextMock.lookup(nameMock)).thenReturn(expectedContext); when(odmMock.mapFromLdapDataEntry(expectedContext, expectedClass)).thenReturn(transformed); - when(nameMock.getAll()).thenReturn(Collections. enumeration(Collections. emptyList())); + when(nameMock.getAll()).thenReturn(Collections.enumeration(Collections.emptyList())); // Perform test Object result = tested.findByDn(nameMock, expectedClass); assertThat(result).isSameAs(transformed); @@ -215,8 +217,6 @@ public class LdapTemplateLookupTest { verify(odmMock).manageClass(expectedClass); } - - @Test public void testLookup_String_ContextMapper() throws Exception { expectGetReadOnlyContext(); @@ -244,7 +244,8 @@ public class LdapTemplateLookupTest { try { tested.lookup(nameMock, contextMapperMock); fail("NameNotFoundException expected"); - } catch (NameNotFoundException expected) { + } + catch (NameNotFoundException expected) { assertThat(true).isTrue(); } @@ -267,8 +268,7 @@ public class LdapTemplateLookupTest { Object expected = new Object(); when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); - Object actual = tested.lookup(nameMock, attributeNames, - attributesMapperMock); + Object actual = tested.lookup(nameMock, attributeNames, attributesMapperMock); verify(dirContextMock).close(); @@ -276,8 +276,7 @@ public class LdapTemplateLookupTest { } @Test - public void testLookup_String_ReturnAttributes_AttributesMapper() - throws Exception { + public void testLookup_String_ReturnAttributes_AttributesMapper() throws Exception { expectGetReadOnlyContext(); String[] attributeNames = new String[] { "cn" }; @@ -290,8 +289,7 @@ public class LdapTemplateLookupTest { Object expected = new Object(); when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); - Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, - attributesMapperMock); + Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, attributesMapperMock); verify(dirContextMock).close(); @@ -310,10 +308,9 @@ public class LdapTemplateLookupTest { expectedAttributes.put("cn", "Some Name"); LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING); - DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, - name); + DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, name); - when(dirContextMock.getAttributes(name,attributeNames)).thenReturn(expectedAttributes); + when(dirContextMock.getAttributes(name, attributeNames)).thenReturn(expectedAttributes); Object transformed = new Object(); when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed); @@ -326,8 +323,7 @@ public class LdapTemplateLookupTest { } @Test - public void testLookup_String_ReturnAttributes_ContextMapper() - throws Exception { + public void testLookup_String_ReturnAttributes_ContextMapper() throws Exception { expectGetReadOnlyContext(); String[] attributeNames = new String[] { "cn" }; @@ -338,17 +334,16 @@ public class LdapTemplateLookupTest { when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING); - DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, - name); + DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, name); Object transformed = new Object(); when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed); - Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, - contextMapperMock); + Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, contextMapperMock); verify(dirContextMock).close(); assertThat(actual).isSameAs(transformed); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateOdmTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateOdmTest.java index ad9a18a0..aae7a1ca 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateOdmTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateOdmTest.java @@ -14,6 +14,7 @@ import static org.mockito.Mockito.mock; public class LdapTemplateOdmTest { private LdapTemplate tested; + private ObjectDirectoryMapper odmMock; @Before @@ -26,9 +27,9 @@ public class LdapTemplateOdmTest { tested.setObjectDirectoryMapper(odmMock); } - @Test public void testFindByDn() { } + } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java index c4dc5044..0e2bf27b 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java @@ -34,7 +34,7 @@ import static org.mockito.Mockito.when; /** * Unit tests for the rename operations in the LdapTemplate class. - * + * * @author Ulrik Sandberg */ public class LdapTemplateRenameTest { @@ -90,7 +90,8 @@ public class LdapTemplateRenameTest { try { tested.rename(oldNameMock, newNameMock); fail("NameAlreadyBoundException expected"); - } catch (NameAlreadyBoundException expected) { + } + catch (NameAlreadyBoundException expected) { assertThat(true).isTrue(); } @@ -108,7 +109,8 @@ public class LdapTemplateRenameTest { try { tested.rename(oldNameMock, newNameMock); fail("UncategorizedLdapException expected"); - } catch (UncategorizedLdapException expected) { + } + catch (UncategorizedLdapException expected) { assertThat(true).isTrue(); } @@ -124,4 +126,5 @@ public class LdapTemplateRenameTest { verify(dirContextMock).rename("o=example.com", "o=somethingelse.com"); verify(dirContextMock).close(); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java b/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java index 1cc9f1cb..cab77562 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java @@ -66,7 +66,7 @@ import static org.springframework.ldap.query.LdapQueryBuilder.query; /** * Unit tests for the LdapTemplate class. - * + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ @@ -101,9 +101,11 @@ public class LdapTemplateTest { private DirContext authenticatedContextMock; private AuthenticatedLdapEntryContextCallback entryContextCallbackMock; + private ObjectDirectoryMapper odmMock; private LdapQuery query; + private AuthenticatedLdapEntryContextMapper authContextMapperMock; @Before @@ -215,10 +217,8 @@ public class LdapTemplateTest { controls.setReturningObjFlag(false); javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException("some text"); - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenThrow(ne); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenThrow(ne); try { tested.search(nameMock, "(ou=somevalue)", handlerMock); @@ -238,10 +238,8 @@ public class LdapTemplateTest { controls.setReturningObjFlag(false); javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenThrow(ne); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenThrow(ne); try { tested.search(nameMock, "(ou=somevalue)", handlerMock); @@ -616,8 +614,8 @@ public class LdapTemplateTest { Class expectedClass = Object.class; when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(odmMock.filterFor(expectedClass, - new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue")); + when(odmMock.filterFor(expectedClass, new EqualsFilter("ou", "somevalue"))) + .thenReturn(new EqualsFilter("ou", "somevalue")); DirContextAdapter expectedObject = new DirContextAdapter(); SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); @@ -626,8 +624,7 @@ public class LdapTemplateTest { Object expectedResult = expectedObject; when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult); - Object result = tested.findOne(query() - .where("ou").is("somevalue"), expectedClass); + Object result = tested.findOne(query().where("ou").is("somevalue"), expectedClass); verify(namingEnumerationMock).close(); verify(dirContextMock).close(); @@ -640,15 +637,16 @@ public class LdapTemplateTest { Class expectedClass = Object.class; when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(odmMock.filterFor(expectedClass, - new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue")); + when(odmMock.filterFor(expectedClass, new EqualsFilter("ou", "somevalue"))) + .thenReturn(new EqualsFilter("ou", "somevalue")); noSearchResults(searchControlsRecursive()); try { tested.findOne(query().where("ou").is("somevalue"), expectedClass); fail("EmptyResultDataAccessException expected"); - } catch (EmptyResultDataAccessException expected) { + } + catch (EmptyResultDataAccessException expected) { assertThat(true).isTrue(); } @@ -662,13 +660,13 @@ public class LdapTemplateTest { Class expectedClass = Object.class; when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(odmMock.filterFor(expectedClass, - new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue")); + when(odmMock.filterFor(expectedClass, new EqualsFilter("ou", "somevalue"))) + .thenReturn(new EqualsFilter("ou", "somevalue")); DirContextAdapter expectedObject = new DirContextAdapter(); SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - setupSearchResults(searchControlsRecursive(), new SearchResult[]{searchResult, searchResult}); + setupSearchResults(searchControlsRecursive(), new SearchResult[] { searchResult, searchResult }); Object expectedResult = expectedObject; when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult); @@ -676,7 +674,8 @@ public class LdapTemplateTest { try { tested.findOne(query().where("ou").is("somevalue"), expectedClass); fail("EmptyResultDataAccessException expected"); - } catch (IncorrectResultSizeDataAccessException expected) { + } + catch (IncorrectResultSizeDataAccessException expected) { assertThat(true).isTrue(); } @@ -685,7 +684,8 @@ public class LdapTemplateTest { } @Test - public void findWhenSearchControlsReturningAttributesSpecifiedThenOverridesOdmReturningAttributes() throws Exception { + public void findWhenSearchControlsReturningAttributesSpecifiedThenOverridesOdmReturningAttributes() + throws Exception { Class expectedClass = Object.class; Filter filter = new EqualsFilter("ou", "somevalue"); @@ -708,7 +708,8 @@ public class LdapTemplateTest { } @Test - public void findWhenSearchControlsReturningAttributesUnspecifiedThenOdmReturningAttributesOverrides() throws Exception { + public void findWhenSearchControlsReturningAttributesUnspecifiedThenOdmReturningAttributesOverrides() + throws Exception { Class expectedClass = Object.class; String[] expectedReturningAttributes = new String[] { "odmattribute" }; SearchControls expectedControls = new SearchControls(); @@ -802,7 +803,6 @@ public class LdapTemplateTest { Object expectedResult = expectedObject; when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, contextMapperMock); verify(namingEnumerationMock).close(); @@ -1136,7 +1136,8 @@ public class LdapTemplateTest { try { tested.create(expectedObject); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -1670,10 +1671,8 @@ public class LdapTemplateTest { Object expectedObject = new Object(); SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenReturn(namingEnumerationMock); when(namingEnumerationMock.hasMore()).thenReturn(true, true, false); when(namingEnumerationMock.next()).thenReturn(searchResult, searchResult); @@ -1775,17 +1774,17 @@ public class LdapTemplateTest { when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(dirContextMock.search( - any(Name.class), - any(String.class), - any(SearchControls.class))).thenReturn(namingEnumerationMock); + when(dirContextMock.search(any(Name.class), any(String.class), any(SearchControls.class))) + .thenReturn(namingEnumerationMock); - when(namingEnumerationMock.hasMore()).thenReturn(false); + when(namingEnumerationMock.hasMore()).thenReturn(false); try { tested.authenticate(query, "", authContextMapperMock); fail("Expected Exception"); - }catch(EmptyResultDataAccessException success) {} + } + catch (EmptyResultDataAccessException success) { + } verify(dirContextMock).close(); } @@ -1795,17 +1794,17 @@ public class LdapTemplateTest { when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(dirContextMock.search( - any(Name.class), - any(String.class), - any(SearchControls.class))).thenReturn(namingEnumerationMock); + when(dirContextMock.search(any(Name.class), any(String.class), any(SearchControls.class))) + .thenReturn(namingEnumerationMock); - when(namingEnumerationMock.hasMore()).thenReturn(false); + when(namingEnumerationMock.hasMore()).thenReturn(false); try { tested.authenticate(query, ""); fail("Expected Exception"); - }catch(EmptyResultDataAccessException success) {} + } + catch (EmptyResultDataAccessException success) { + } verify(dirContextMock).close(); } @@ -1842,9 +1841,8 @@ public class LdapTemplateTest { when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password")) .thenReturn(authenticatedContextMock); doThrow(new UncategorizedLdapException("Authentication failed")).when(entryContextCallbackMock) - .executeWithContext(authenticatedContextMock, - new LdapEntryIdentification( - LdapUtils.newLdapName("cn=john doe,dc=jayway,dc=se"), LdapUtils.newLdapName("cn=john doe"))); + .executeWithContext(authenticatedContextMock, new LdapEntryIdentification( + LdapUtils.newLdapName("cn=john doe,dc=jayway,dc=se"), LdapUtils.newLdapName("cn=john doe"))); boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); @@ -1855,10 +1853,8 @@ public class LdapTemplateTest { } private void noSearchResults(SearchControls controls) throws Exception { - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenReturn(namingEnumerationMock); when(namingEnumerationMock.hasMore()).thenReturn(false); } @@ -1868,27 +1864,24 @@ public class LdapTemplateTest { } private void setupSearchResults(SearchControls controls, SearchResult... searchResults) throws Exception { - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + when(dirContextMock.search(eq(nameMock), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))) + .thenReturn(namingEnumerationMock); - if(searchResults.length == 1) { + if (searchResults.length == 1) { when(namingEnumerationMock.hasMore()).thenReturn(true, false); when(namingEnumerationMock.next()).thenReturn(searchResults[0]); - } else if(searchResults.length ==2) { + } + else if (searchResults.length == 2) { when(namingEnumerationMock.hasMore()).thenReturn(true, true, false); when(namingEnumerationMock.next()).thenReturn(searchResults[0], searchResults[1]); - } else { + } + else { throw new IllegalArgumentException("Cannot handle " + searchResults.length + " search results"); } } - private void singleSearchResultWithStringBase(SearchControls controls, SearchResult searchResult) - throws Exception { - when(dirContextMock.search( - eq(DEFAULT_BASE_STRING), - eq("(ou=somevalue)"), + private void singleSearchResultWithStringBase(SearchControls controls, SearchResult searchResult) throws Exception { + when(dirContextMock.search(eq(DEFAULT_BASE_STRING), eq("(ou=somevalue)"), argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); when(namingEnumerationMock.hasMore()).thenReturn(true, false); @@ -1910,6 +1903,7 @@ public class LdapTemplateTest { } private static class SearchControlsMatcher implements ArgumentMatcher { + private final SearchControls controls; public SearchControlsMatcher(SearchControls controls) { @@ -1932,5 +1926,7 @@ public class LdapTemplateTest { throw new IllegalArgumentException(); } } + } + } diff --git a/core/src/test/java/org/springframework/ldap/core/NameAwareAttributeTest.java b/core/src/test/java/org/springframework/ldap/core/NameAwareAttributeTest.java index d7d50653..44840031 100644 --- a/core/src/test/java/org/springframework/ldap/core/NameAwareAttributeTest.java +++ b/core/src/test/java/org/springframework/ldap/core/NameAwareAttributeTest.java @@ -31,6 +31,7 @@ import static org.junit.Assert.assertTrue; * @author Mattias Hellborg Arthursson */ public class NameAwareAttributeTest { + @Test public void testEqualsWithIdNotSame() { NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute"); @@ -66,13 +67,13 @@ public class NameAwareAttributeTest { @Test public void testEqualsUnorderedWithIdenticalArrayAttributes() { NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute"); - attr1.add(new byte[]{1, 2, 3}); - attr1.add(new byte[]{3, 2, 1}); - attr1.add(new byte[]{1}); + attr1.add(new byte[] { 1, 2, 3 }); + attr1.add(new byte[] { 3, 2, 1 }); + attr1.add(new byte[] { 1 }); NameAwareAttribute attr2 = new NameAwareAttribute("someAttribute"); - attr2.add(new byte[]{1, 2, 3}); - attr2.add(new byte[]{3, 2, 1}); - attr2.add(new byte[]{1}); + attr2.add(new byte[] { 1, 2, 3 }); + attr2.add(new byte[] { 3, 2, 1 }); + attr2.add(new byte[] { 1 }); assertThat(attr1.equals(attr2)).isTrue(); assertThat(attr2.hashCode()).isEqualTo(attr1.hashCode()); @@ -81,13 +82,13 @@ public class NameAwareAttributeTest { @Test public void testEqualsUnorderedWithDifferentOrderArrayAttributes() { NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute"); - attr1.add(new byte[]{1, 2, 3}); - attr1.add(new byte[]{3, 2, 1}); - attr1.add(new byte[]{1}); + attr1.add(new byte[] { 1, 2, 3 }); + attr1.add(new byte[] { 3, 2, 1 }); + attr1.add(new byte[] { 1 }); NameAwareAttribute attr2 = new NameAwareAttribute("someAttribute"); - attr2.add(new byte[]{3, 2, 1}); - attr2.add(new byte[]{1}); - attr2.add(new byte[]{1, 2, 3}); + attr2.add(new byte[] { 3, 2, 1 }); + attr2.add(new byte[] { 1 }); + attr2.add(new byte[] { 1, 2, 3 }); assertThat(attr1.equals(attr2)).isTrue(); assertThat(attr2.hashCode()).isEqualTo(attr1.hashCode()); @@ -96,13 +97,13 @@ public class NameAwareAttributeTest { @Test public void testEqualsUnorderedWithDifferentArrayAttributes() { NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute"); - attr1.add(new byte[]{1, 2, 3}); - attr1.add(new byte[]{3, 2, 2}); - attr1.add(new byte[]{1}); + attr1.add(new byte[] { 1, 2, 3 }); + attr1.add(new byte[] { 3, 2, 2 }); + attr1.add(new byte[] { 1 }); NameAwareAttribute attr2 = new NameAwareAttribute("someAttribute"); - attr2.add(new byte[]{1, 2, 3}); - attr2.add(new byte[]{3, 2, 1}); - attr2.add(new byte[]{1}); + attr2.add(new byte[] { 1, 2, 3 }); + attr2.add(new byte[] { 3, 2, 1 }); + attr2.add(new byte[] { 1 }); assertThat(attr1.equals(attr2)).isFalse(); } @@ -110,12 +111,12 @@ public class NameAwareAttributeTest { @Test public void testEqualsUnorderedWithDifferentNumberOfArrayAttributes() { NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute"); - attr1.add(new byte[]{1, 2, 3}); - attr1.add(new byte[]{3, 2, 1}); - attr1.add(new byte[]{1}); + attr1.add(new byte[] { 1, 2, 3 }); + attr1.add(new byte[] { 3, 2, 1 }); + attr1.add(new byte[] { 1 }); NameAwareAttribute attr2 = new NameAwareAttribute("someAttribute"); - attr2.add(new byte[]{1, 2, 3}); - attr2.add(new byte[]{1}); + attr2.add(new byte[] { 1, 2, 3 }); + attr2.add(new byte[] { 1 }); assertThat(attr1.equals(attr2)).isFalse(); } @@ -123,13 +124,13 @@ public class NameAwareAttributeTest { @Test public void testEqualsOrderedWithIdenticalArrayAttributes() { NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute", true); - attr1.add(new byte[]{1, 2, 3}); - attr1.add(new byte[]{3, 2, 1}); - attr1.add(new byte[]{1}); + attr1.add(new byte[] { 1, 2, 3 }); + attr1.add(new byte[] { 3, 2, 1 }); + attr1.add(new byte[] { 1 }); NameAwareAttribute attr2 = new NameAwareAttribute("someAttribute", true); - attr2.add(new byte[]{1, 2, 3}); - attr2.add(new byte[]{3, 2, 1}); - attr2.add(new byte[]{1}); + attr2.add(new byte[] { 1, 2, 3 }); + attr2.add(new byte[] { 3, 2, 1 }); + attr2.add(new byte[] { 1 }); assertThat(attr1.equals(attr2)).isTrue(); assertThat(attr2.hashCode()).isEqualTo(attr1.hashCode()); @@ -138,13 +139,13 @@ public class NameAwareAttributeTest { @Test public void testEqualsOrderedWithArrayAttributes() { NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute", true); - attr1.add(new byte[]{1, 2, 3}); - attr1.add(new byte[]{3, 2, 1}); - attr1.add(new byte[]{1}); + attr1.add(new byte[] { 1, 2, 3 }); + attr1.add(new byte[] { 3, 2, 1 }); + attr1.add(new byte[] { 1 }); NameAwareAttribute attr2 = new NameAwareAttribute("someAttribute", true); - attr2.add(new byte[]{1, 2, 3}); - attr2.add(new byte[]{3, 2, 1}); - attr2.add(new byte[]{1}); + attr2.add(new byte[] { 1, 2, 3 }); + attr2.add(new byte[] { 3, 2, 1 }); + attr2.add(new byte[] { 1 }); assertThat(attr1.equals(attr2)).isTrue(); assertThat(attr2.hashCode()).isEqualTo(attr1.hashCode()); @@ -153,13 +154,13 @@ public class NameAwareAttributeTest { @Test public void testEqualsOrderedWithDifferentOrderArrayAttributes() { NameAwareAttribute attr1 = new NameAwareAttribute("someAttribute", true); - attr1.add(new byte[]{1, 2, 3}); - attr1.add(new byte[]{3, 2, 1}); - attr1.add(new byte[]{1}); + attr1.add(new byte[] { 1, 2, 3 }); + attr1.add(new byte[] { 3, 2, 1 }); + attr1.add(new byte[] { 1 }); NameAwareAttribute attr2 = new NameAwareAttribute("someAttribute", true); - attr2.add(new byte[]{3, 2, 1}); - attr2.add(new byte[]{1}); - attr2.add(new byte[]{1, 2, 3}); + attr2.add(new byte[] { 3, 2, 1 }); + attr2.add(new byte[] { 1 }); + attr2.add(new byte[] { 1, 2, 3 }); assertThat(attr1.equals(attr2)).isFalse(); } @@ -181,7 +182,8 @@ public class NameAwareAttributeTest { @Test public void testEqualDistinguishedNameValue() throws NamingException { - // The names here are syntactically equal, but differ in exact string representation + // The names here are syntactically equal, but differ in exact string + // representation String expectedName1 = "cn=John Doe, OU=People"; String expectedName2 = "cn=John Doe,ou=People"; @@ -198,7 +200,8 @@ public class NameAwareAttributeTest { @Test public void testEqualDistinguishedNameValueUninitialized() throws NamingException { - // The names here are syntactically equal, but differ in exact string representation + // The names here are syntactically equal, but differ in exact string + // representation String expectedName1 = "cn=John Doe, OU=People"; String expectedName2 = "cn=John Doe,ou=People"; @@ -214,7 +217,8 @@ public class NameAwareAttributeTest { @Test public void testEqualDistinguishedNameValueManuallyInitialized() throws NamingException { - // The names here are syntactically equal, but differ in exact string representation + // The names here are syntactically equal, but differ in exact string + // representation String expectedName1 = "cn=John Doe, OU=People"; String expectedName2 = "cn=John Doe,ou=People"; @@ -233,7 +237,8 @@ public class NameAwareAttributeTest { @Test public void testUnequalDistinguishedNameValue() throws NamingException { - // The names here are syntactically equal, but differ in exact string representation + // The names here are syntactically equal, but differ in exact string + // representation String expectedName1 = "cn=Jane Doe,ou=People"; String expectedName2 = "cn=John Doe,ou=People"; @@ -249,7 +254,8 @@ public class NameAwareAttributeTest { @Test public void testComparingWDistinguishedNameValueWithInvalidName() throws NamingException { - // The names here are syntactically equal, but differ in exact string representation + // The names here are syntactically equal, but differ in exact string + // representation String expectedName1 = "cn=Jane Doe,ou=People"; String expectedValue2 = "thisisnotavaliddn"; @@ -279,4 +285,5 @@ public class NameAwareAttributeTest { assertTrue(attribute.equals(expectedAttribute)); assertTrue(attribute.hashCode() == expectedAttribute.hashCode()); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/NameAwareAttributesTest.java b/core/src/test/java/org/springframework/ldap/core/NameAwareAttributesTest.java index 686917fb..7f8cb3cc 100644 --- a/core/src/test/java/org/springframework/ldap/core/NameAwareAttributesTest.java +++ b/core/src/test/java/org/springframework/ldap/core/NameAwareAttributesTest.java @@ -5,6 +5,7 @@ import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class NameAwareAttributesTest { + // gh-548 @Test public void removeWhenDifferentCaseThenRemoves() { @@ -22,4 +23,5 @@ public class NameAwareAttributesTest { attributes.remove("myOtherID"); assertThat(attributes.size()).isEqualTo(0); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/AbstractContextSourceTest.java b/core/src/test/java/org/springframework/ldap/core/support/AbstractContextSourceTest.java index b186b54f..dc00e2d9 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/AbstractContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/AbstractContextSourceTest.java @@ -59,4 +59,5 @@ public class AbstractContextSourceTest { String result = AbstractContextSource.formatForUrl(ldapName); assertThat(result).isEqualTo(""); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/AggregateDirContextProcessorTest.java b/core/src/test/java/org/springframework/ldap/core/support/AggregateDirContextProcessorTest.java index 5be8596a..1bca269e 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/AggregateDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/AggregateDirContextProcessorTest.java @@ -24,7 +24,7 @@ import javax.naming.NamingException; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; -public class AggregateDirContextProcessorTest { +public class AggregateDirContextProcessorTest { private DirContextProcessor processor1Mock; @@ -49,7 +49,7 @@ public class AggregateDirContextProcessorTest { @Test public void testPreProcess() throws NamingException { tested.preProcess(null); - + verify(processor1Mock).preProcess(null); verify(processor2Mock).preProcess(null); } diff --git a/core/src/test/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessorTest.java b/core/src/test/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessorTest.java index 26355738..85b03980 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/BaseLdapPathBeanPostProcessorTest.java @@ -31,14 +31,17 @@ import static org.mockito.Mockito.when; /** * Unit tests for {@link BaseLdapPathBeanPostProcessor}. - * + * * @author Mattias Hellborg Arthursson */ public class BaseLdapPathBeanPostProcessorTest { private BaseLdapPathBeanPostProcessor tested; + private BaseLdapPathAware ldapPathAwareMock; + private ApplicationContext applicationContextMock; + private BaseLdapNameAware ldapNameAwareMock; @Before @@ -77,7 +80,6 @@ public class BaseLdapPathBeanPostProcessorTest { assertThat(result).isSameAs(ldapNameAwareMock); } - @Test public void testPostProcessBeforeInitializationWithLdapPathAwareNoBasePathSet() throws Exception { final LdapContextSource expectedContextSource = new LdapContextSource(); @@ -119,12 +121,14 @@ public class BaseLdapPathBeanPostProcessorTest { @Test public void testGetAbstractContextSourceFromApplicationContext() throws Exception { when(applicationContextMock.getBeanNamesForType(BaseLdapPathSource.class)) - .thenReturn(new String[]{"contextSource"}); + .thenReturn(new String[] { "contextSource" }); final LdapContextSource expectedContextSource = new LdapContextSource(); - HashMap expectedBeans = new HashMap() {{ - put("dummy", expectedContextSource); - }}; + HashMap expectedBeans = new HashMap() { + { + put("dummy", expectedContextSource); + } + }; when(applicationContextMock.getBeansOfType(BaseLdapPathSource.class)).thenReturn(expectedBeans); BaseLdapPathSource result = tested.getBaseLdapPathSourceFromApplicationContext(); @@ -134,16 +138,14 @@ public class BaseLdapPathBeanPostProcessorTest { @Test(expected = NoSuchBeanDefinitionException.class) public void testGetAbstractContextSourceFromApplicationContextNoContextSource() throws Exception { - when(applicationContextMock.getBeanNamesForType(BaseLdapPathSource.class)) - .thenReturn(new String[0]); + when(applicationContextMock.getBeanNamesForType(BaseLdapPathSource.class)).thenReturn(new String[0]); tested.getBaseLdapPathSourceFromApplicationContext(); } @Test(expected = NoSuchBeanDefinitionException.class) public void testGetAbstractContextSourceFromApplicationContextTwoContextSources() throws Exception { - when(applicationContextMock - .getBeanNamesForType(BaseLdapPathSource.class)).thenReturn(new String[2]); + when(applicationContextMock.getBeanNamesForType(BaseLdapPathSource.class)).thenReturn(new String[2]); tested.getBaseLdapPathSourceFromApplicationContext(); } @@ -157,4 +159,5 @@ public class BaseLdapPathBeanPostProcessorTest { tested.getBaseLdapPathSourceFromApplicationContext(); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/ContextMapperCallbackHandlerWithControlsTest.java b/core/src/test/java/org/springframework/ldap/core/support/ContextMapperCallbackHandlerWithControlsTest.java index bc47cbbd..b69e09a5 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/ContextMapperCallbackHandlerWithControlsTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/ContextMapperCallbackHandlerWithControlsTest.java @@ -34,11 +34,13 @@ import static org.mockito.Mockito.when; * @author Mattias Hellborg Arthursson */ public class ContextMapperCallbackHandlerWithControlsTest { + private ContextMapperWithControls mapperMock; private ContextMapperCallbackHandlerWithControls tested; private static class MyBindingThatHasControls extends Binding implements HasControls { + private static final long serialVersionUID = 1L; public MyBindingThatHasControls(String name, Object obj) { @@ -48,6 +50,7 @@ public class ContextMapperCallbackHandlerWithControlsTest { public Control[] getControls() throws NamingException { return null; } + } @SuppressWarnings("unchecked") diff --git a/core/src/test/java/org/springframework/ldap/core/support/CountNameClassPairResultCallbackHandlerTest.java b/core/src/test/java/org/springframework/ldap/core/support/CountNameClassPairResultCallbackHandlerTest.java index da86541f..e5e72366 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/CountNameClassPairResultCallbackHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/CountNameClassPairResultCallbackHandlerTest.java @@ -37,8 +37,8 @@ public class CountNameClassPairResultCallbackHandlerTest { tested.handleNameClassPair(dummy); tested.handleNameClassPair(dummy); tested.handleNameClassPair(dummy); - + assertThat(tested.getNoOfRows()).isEqualTo(3); } - + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/DefaultDirObjectFactoryTest.java b/core/src/test/java/org/springframework/ldap/core/support/DefaultDirObjectFactoryTest.java index 37de116c..213095fe 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/DefaultDirObjectFactoryTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/DefaultDirObjectFactoryTest.java @@ -59,8 +59,8 @@ public class DefaultDirObjectFactoryTest { Attributes expectedAttributes = new NameAwareAttributes(); expectedAttributes.put("someAttribute", "someValue"); - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, DN, null, - new Hashtable(), expectedAttributes); + DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, DN, null, new Hashtable(), + expectedAttributes); verify(contextMock).close(); @@ -75,7 +75,7 @@ public class DefaultDirObjectFactoryTest { CompositeName name = new CompositeName(); name.add(DN_STRING); - + DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, name, null, new Hashtable(), expectedAttributes); @@ -111,7 +111,6 @@ public class DefaultDirObjectFactoryTest { /** * Make sure that the base suffix is stripped off from the DN. - * * @throws Exception */ @Test @@ -121,8 +120,8 @@ public class DefaultDirObjectFactoryTest { when(contextMock2.getNameInNamespace()).thenReturn("dc=jayway, dc=se"); - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, LdapUtils.newLdapName( - "ou=some unit"), contextMock2, new Hashtable(), expectedAttributes); + DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, + LdapUtils.newLdapName("ou=some unit"), contextMock2, new Hashtable(), expectedAttributes); verify(contextMock).close(); @@ -174,4 +173,5 @@ public class DefaultDirObjectFactoryTest { assertThat(result.getDn().toString()).isEqualTo(""); assertThat(result.getReferralUrl().toString()).isEqualTo("ldap://localhost:389"); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapperTest.java b/core/src/test/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapperTest.java index 19c53cbc..b78c926f 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapperTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/DefaultIncrementalAttributesMapperTest.java @@ -33,6 +33,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Mattias Hellborg Arthursson */ public class DefaultIncrementalAttributesMapperTest { + private DefaultIncrementalAttributesMapper tested; @Before @@ -57,7 +58,7 @@ public class DefaultIncrementalAttributesMapperTest { @Test public void testGetAttributesArrayWithTwoAttributes() { - tested = new DefaultIncrementalAttributesMapper(20, new String[]{"member", "cn"}); + tested = new DefaultIncrementalAttributesMapper(20, new String[] { "member", "cn" }); String[] attributes = tested.getAttributesForLookup(); assertThat(attributes.length).isEqualTo(2); @@ -147,7 +148,7 @@ public class DefaultIncrementalAttributesMapperTest { @Test public void testLoopWithTwoRangedAttributesLoopOnOneAttribute() throws Exception { - tested = new DefaultIncrementalAttributesMapper(10, new String[]{"member", "cn"}); + tested = new DefaultIncrementalAttributesMapper(10, new String[] { "member", "cn" }); Attributes attributes = createAttributes("member", new RangeOption(0, 5)); attributes.put(createRangeAttribute("cn", new RangeOption(0, 10), 10)); @@ -188,4 +189,5 @@ public class DefaultIncrementalAttributesMapperTest { } return attribute; } + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategyTests.java b/core/src/test/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategyTests.java index 4e0e61a3..a5b7910b 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategyTests.java +++ b/core/src/test/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategyTests.java @@ -15,6 +15,7 @@ import static org.mockito.Mockito.verify; */ @RunWith(MockitoJUnitRunner.class) public class DefaultTlsDirContextAuthenticationStrategyTests { + @Mock private LdapContext context; @@ -27,4 +28,5 @@ public class DefaultTlsDirContextAuthenticationStrategyTests { verify(this.context).lookup(""); } + } \ No newline at end of file diff --git a/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java b/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java index 45d41dff..11792e14 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java @@ -70,7 +70,8 @@ public class LdapContextSourceTest { assertThat(env.get(Context.SECURITY_CREDENTIALS)).isNull(); // check that base was added to environment - assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)).isEqualTo(LdapUtils.newLdapName("dc=some example,dc=se")); + assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)) + .isEqualTo(LdapUtils.newLdapName("dc=some example,dc=se")); // Verify that changing values does not change the environment values. tested.setBase("dc=other,dc=se"); @@ -83,7 +84,8 @@ public class LdapContextSourceTest { assertThat(env.get(Context.SECURITY_PRINCIPAL)).isNull(); assertThat(env.get(Context.SECURITY_CREDENTIALS)).isNull(); - assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)).isEqualTo(LdapUtils.newLdapName("dc=some example,dc=se")); + assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)) + .isEqualTo(LdapUtils.newLdapName("dc=some example,dc=se")); } @Test @@ -150,7 +152,8 @@ public class LdapContextSourceTest { assertThat(env.get(Context.SECURITY_CREDENTIALS)).isEqualTo("secret"); // check that base was added to environment - assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)).isEqualTo(LdapUtils.newLdapName("dc=example,dc=se")); + assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)) + .isEqualTo(LdapUtils.newLdapName("dc=example,dc=se")); } @Test @@ -172,4 +175,5 @@ public class LdapContextSourceTest { env = tested.getAnonymousEnv(); assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap2.example.com:389/dc=example,dc=se"); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/RangeOptionTest.java b/core/src/test/java/org/springframework/ldap/core/support/RangeOptionTest.java index 9b6ebb2a..fede4a7c 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/RangeOptionTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/RangeOptionTest.java @@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.fail; * * @author Marius Scurtescu */ -public class RangeOptionTest { +public class RangeOptionTest { @Test public void testConstructorInvalid() { @@ -34,7 +34,8 @@ public class RangeOptionTest { new RangeOption(101, 100); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -42,7 +43,8 @@ public class RangeOptionTest { new RangeOption(-1, 100); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -50,7 +52,8 @@ public class RangeOptionTest { new RangeOption(-10, 100); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -58,7 +61,8 @@ public class RangeOptionTest { new RangeOption(0, -3); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -146,7 +150,8 @@ public class RangeOptionTest { assertThat(range1.compareTo(range2) == 0).isTrue(); fail("IllegalStateException expected"); - } catch (IllegalStateException expected) { + } + catch (IllegalStateException expected) { assertThat(true).isTrue(); } @@ -157,7 +162,8 @@ public class RangeOptionTest { assertThat(range1.compareTo(range2) == 0).isTrue(); fail("IllegalStateException expected"); - } catch (IllegalStateException expected) { + } + catch (IllegalStateException expected) { assertThat(true).isTrue(); } @@ -168,7 +174,8 @@ public class RangeOptionTest { assertThat(range1.compareTo(range2) == 0).isTrue(); fail("IllegalStateException expected"); - } catch (IllegalStateException expected) { + } + catch (IllegalStateException expected) { assertThat(true).isTrue(); } } @@ -189,4 +196,5 @@ public class RangeOptionTest { assertThat(range.getInitial()).isEqualTo(211); assertThat(range.getTerminal()).isEqualTo(RangeOption.TERMINAL_END_OF_RANGE); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java b/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java index 8a9b334c..17ab5aca 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java @@ -24,6 +24,7 @@ import java.util.Hashtable; import static org.assertj.core.api.Assertions.assertThat; public class SimpleDirContextAuthenticationStrategyTest { + private SimpleDirContextAuthenticationStrategy tested; @Before @@ -49,5 +50,4 @@ public class SimpleDirContextAuthenticationStrategyTest { assertThat(env.isEmpty()).isTrue(); } - } diff --git a/core/src/test/java/org/springframework/ldap/core/support/SingleContextSourceTest.java b/core/src/test/java/org/springframework/ldap/core/support/SingleContextSourceTest.java index d615ad70..288d6496 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/SingleContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/core/support/SingleContextSourceTest.java @@ -40,6 +40,7 @@ import static org.mockito.Mockito.when; public class SingleContextSourceTest { private ContextSource contextSourceMock; + private DirContext dirContextMock; @Before @@ -65,7 +66,8 @@ public class SingleContextSourceTest { } }); - // Second operation will have retrieved new DirContext from the SingleContextSource. + // Second operation will have retrieved new DirContext from the + // SingleContextSource. // It should be the same instance. operations.executeReadOnly(new ContextExecutor() { @Override @@ -86,4 +88,5 @@ public class SingleContextSourceTest { field.setAccessible(true); return (T) ReflectionUtils.getField(field, target); } + } diff --git a/core/src/test/java/org/springframework/ldap/core/support/ldap294/Ldap294Tests.java b/core/src/test/java/org/springframework/ldap/core/support/ldap294/Ldap294Tests.java index 484bc37e..803ccfa9 100644 --- a/core/src/test/java/org/springframework/ldap/core/support/ldap294/Ldap294Tests.java +++ b/core/src/test/java/org/springframework/ldap/core/support/ldap294/Ldap294Tests.java @@ -25,20 +25,20 @@ import org.springframework.ldap.core.support.AbstractContextSource; /** * These tests just ensure that the subclass compiles - * + * * @author Rob Winch * */ public class Ldap294Tests { @Test - public void concerteContextSourceCanAccessPasswordAndUserDn() {} + public void concerteContextSourceCanAccessPasswordAndUserDn() { + } static class ConcerteContextSource extends AbstractContextSource { @Override - protected DirContext getDirContextInstance( - Hashtable environment) throws NamingException { + protected DirContext getDirContextInstance(Hashtable environment) throws NamingException { // Verify a subclass outside of package scope can access password // and userDn since Spring Security needs to be able to access these // properties. @@ -46,6 +46,7 @@ public class Ldap294Tests { String userDn = super.getUserDn(); return null; } - + } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java index 59e35c29..5a2491d1 100644 --- a/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java @@ -42,16 +42,15 @@ public class AndFilterTest { @Test public void testTwo() { - AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")).and( - new EqualsFilter("c", "d")); + AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")).and(new EqualsFilter("c", "d")); assertThat(aq.encode()).isEqualTo("(&(a=b)(c=d))"); } @Test public void testThree() { - AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")).and( - new EqualsFilter("c", "d")).and(new EqualsFilter("e", "f")); + AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")).and(new EqualsFilter("c", "d")) + .and(new EqualsFilter("e", "f")); assertThat(aq.encode()).isEqualTo("(&(a=b)(c=d)(e=f))"); } @@ -65,7 +64,7 @@ public class AndFilterTest { AndFilter subclassObject = new AndFilter() { }.and(filter); - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java index 28cd31c9..b18c322a 100644 --- a/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java @@ -58,7 +58,7 @@ public class EqualsFilterTest { EqualsFilter subclassObject = new EqualsFilter("a", "b") { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java index 8875811b..7313def0 100644 --- a/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java @@ -29,8 +29,7 @@ public class GreaterThanOrEqualsFilterTest { @Test public void testEncode() { - GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", - "*bar(fie)"); + GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", "*bar(fie)"); StringBuffer buff = new StringBuffer(); eqq.encode(buff); @@ -42,8 +41,7 @@ public class GreaterThanOrEqualsFilterTest { @Test public void testEncodeInt() { - GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", - 456); + GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", 456); StringBuffer buff = new StringBuffer(); eqq.encode(buff); @@ -64,4 +62,5 @@ public class GreaterThanOrEqualsFilterTest { new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java index a909b926..cee8aab8 100644 --- a/core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/HardcodedFilterTest.java @@ -55,7 +55,7 @@ public class HardcodedFilterTest { HardcodedFilter subclassObject = new HardcodedFilter(attribute) { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java index 51b587b9..816e3f9e 100644 --- a/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java @@ -29,8 +29,7 @@ public class LessThanOrEqualsFilterTest { @Test public void testEncode() { - LessThanOrEqualsFilter eqq = new LessThanOrEqualsFilter("foo", - "*bar(fie)"); + LessThanOrEqualsFilter eqq = new LessThanOrEqualsFilter("foo", "*bar(fie)"); StringBuffer buff = new StringBuffer(); eqq.encode(buff); @@ -61,7 +60,7 @@ public class LessThanOrEqualsFilterTest { LessThanOrEqualsFilter subclassObject = new LessThanOrEqualsFilter(attribute, value) { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java index 3ba9b288..ac630586 100644 --- a/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java @@ -36,16 +36,13 @@ public class LikeFilterTest { public void testEncodeValue_normal() { assertThat("foo").isEqualTo(new LikeFilter("", "foo").getEncodedValue()); assertThat("foo*bar").isEqualTo(new LikeFilter("", "foo*bar").getEncodedValue()); - assertThat("*foo*bar*").isEqualTo(new LikeFilter("", "*foo*bar*") - .getEncodedValue()); - assertThat("**foo**bar**").isEqualTo(new LikeFilter("", "**foo**bar**") - .getEncodedValue()); + assertThat("*foo*bar*").isEqualTo(new LikeFilter("", "*foo*bar*").getEncodedValue()); + assertThat("**foo**bar**").isEqualTo(new LikeFilter("", "**foo**bar**").getEncodedValue()); } @Test public void testEncodeValue_escape() { - assertThat("*\\28*\\29*").isEqualTo(new LikeFilter("", "*(*)*") - .getEncodedValue()); + assertThat("*\\28*\\29*").isEqualTo(new LikeFilter("", "*(*)*").getEncodedValue()); assertThat("*\\5c2a*").isEqualTo(new LikeFilter("", "*\\2a*").getEncodedValue()); } @@ -59,7 +56,7 @@ public class LikeFilterTest { LikeFilter subclassObject = new LikeFilter(attribute, value) { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java index 8cfc16ea..f3035a0c 100644 --- a/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java @@ -23,7 +23,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the NotFilter class. - * + * * @author Mattias Hellborg Arthursson */ public class NotFilterTest { @@ -45,7 +45,7 @@ public class NotFilterTest { NotFilter subclassObject = new NotFilter(filter) { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/NotPresentFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/NotPresentFilterTest.java index e5a60268..491f4e33 100644 --- a/core/src/test/java/org/springframework/ldap/filter/NotPresentFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/NotPresentFilterTest.java @@ -55,7 +55,7 @@ public class NotPresentFilterTest { NotPresentFilter subclassObject = new NotPresentFilter(attribute) { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java index 7cac5406..2734e0bf 100644 --- a/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java @@ -22,7 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the OrFilter class. - * + * * @author Adam Skogman */ public class OrFilterTest { @@ -43,16 +43,15 @@ public class OrFilterTest { @Test public void testTwo() { - OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")).or( - new EqualsFilter("c", "d")); + OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")).or(new EqualsFilter("c", "d")); assertThat(of.encode()).isEqualTo("(|(a=b)(c=d))"); } @Test public void testThree() { - OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")).or( - new EqualsFilter("c", "d")).or(new EqualsFilter("e", "f")); + OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")).or(new EqualsFilter("c", "d")) + .or(new EqualsFilter("e", "f")); assertThat(of.encode()).isEqualTo("(|(a=b)(c=d)(e=f))"); } diff --git a/core/src/test/java/org/springframework/ldap/filter/PresentFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/PresentFilterTest.java index eb336968..6230d913 100644 --- a/core/src/test/java/org/springframework/ldap/filter/PresentFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/PresentFilterTest.java @@ -55,7 +55,7 @@ public class PresentFilterTest { PresentFilter subclassObject = new PresentFilter(attribute) { }; - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); + new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); } + } diff --git a/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java index b0d3f6eb..6c14c5ff 100644 --- a/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java @@ -22,7 +22,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for the WhitespaceWildcardsFilter class. - * + * * @author Adam Skogman */ public class WhitespaceWildcardsFilterTest { @@ -31,39 +31,29 @@ public class WhitespaceWildcardsFilterTest { public void testEncodeValue_blank() { // blank - assertThat("*").isEqualTo(new WhitespaceWildcardsFilter("", null) - .getEncodedValue()); - assertThat("*").isEqualTo(new WhitespaceWildcardsFilter("", " ") - .getEncodedValue()); - assertThat("*").isEqualTo(new WhitespaceWildcardsFilter("", " ") - .getEncodedValue()); - assertThat("*").isEqualTo(new WhitespaceWildcardsFilter("", "\t") - .getEncodedValue()); + assertThat("*").isEqualTo(new WhitespaceWildcardsFilter("", null).getEncodedValue()); + assertThat("*").isEqualTo(new WhitespaceWildcardsFilter("", " ").getEncodedValue()); + assertThat("*").isEqualTo(new WhitespaceWildcardsFilter("", " ").getEncodedValue()); + assertThat("*").isEqualTo(new WhitespaceWildcardsFilter("", "\t").getEncodedValue()); } @Test public void testEncodeValue_normal() { - assertThat("*foo*").isEqualTo(new WhitespaceWildcardsFilter("", "foo") - .getEncodedValue()); - assertThat("*foo*bar*").isEqualTo(new WhitespaceWildcardsFilter("", "foo bar") - .getEncodedValue()); - assertThat(new WhitespaceWildcardsFilter("", " foo bar ") - .getEncodedValue()).isEqualTo("*foo*bar*"); - assertThat(new WhitespaceWildcardsFilter("", - " \t foo \n bar \r ").getEncodedValue()).isEqualTo("*foo*bar*"); + assertThat("*foo*").isEqualTo(new WhitespaceWildcardsFilter("", "foo").getEncodedValue()); + assertThat("*foo*bar*").isEqualTo(new WhitespaceWildcardsFilter("", "foo bar").getEncodedValue()); + assertThat(new WhitespaceWildcardsFilter("", " foo bar ").getEncodedValue()).isEqualTo("*foo*bar*"); + assertThat(new WhitespaceWildcardsFilter("", " \t foo \n bar \r ").getEncodedValue()).isEqualTo("*foo*bar*"); } @Test public void testEncodeValue_escape() { - assertThat("*\\28\\2a\\29*").isEqualTo(new WhitespaceWildcardsFilter("", "(*)") - .getEncodedValue()); - assertThat("*\\2a*").isEqualTo(new WhitespaceWildcardsFilter("", "*") - .getEncodedValue()); - assertThat("*\\5c*").isEqualTo(new WhitespaceWildcardsFilter("", " \\ ") - .getEncodedValue()); + assertThat("*\\28\\2a\\29*").isEqualTo(new WhitespaceWildcardsFilter("", "(*)").getEncodedValue()); + assertThat("*\\2a*").isEqualTo(new WhitespaceWildcardsFilter("", "*").getEncodedValue()); + assertThat("*\\5c*").isEqualTo(new WhitespaceWildcardsFilter("", " \\ ").getEncodedValue()); } + } diff --git a/core/src/test/java/org/springframework/ldap/odm/core/impl/BaseUnitTestPerson.java b/core/src/test/java/org/springframework/ldap/odm/core/impl/BaseUnitTestPerson.java index 920f2953..a563659e 100644 --- a/core/src/test/java/org/springframework/ldap/odm/core/impl/BaseUnitTestPerson.java +++ b/core/src/test/java/org/springframework/ldap/odm/core/impl/BaseUnitTestPerson.java @@ -23,30 +23,31 @@ import java.util.List; /** * @author Rob Winch */ -@Entry(base="ou=someOu", objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top"}) +@Entry(base = "ou=someOu", objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }) public class BaseUnitTestPerson { - @Id - private Name dn; - @Attribute(name = "cn") - @DnAttribute("cn") - private String fullName; + @Id + private Name dn; - @Attribute(name = "sn") - private String lastName; + @Attribute(name = "cn") + @DnAttribute("cn") + private String fullName; - @Attribute(name = "description") - private List description; + @Attribute(name = "sn") + private String lastName; - @Transient - @DnAttribute("c") - private String country; + @Attribute(name = "description") + private List description; - @Transient - @DnAttribute("ou") - private String company; + @Transient + @DnAttribute("c") + private String country; - // This should be automatically found - private String telephoneNumber; + @Transient + @DnAttribute("ou") + private String company; + + // This should be automatically found + private String telephoneNumber; } diff --git a/core/src/test/java/org/springframework/ldap/odm/core/impl/DefaultObjectDirectoryMapperTest.java b/core/src/test/java/org/springframework/ldap/odm/core/impl/DefaultObjectDirectoryMapperTest.java index 332cd36a..98678f74 100644 --- a/core/src/test/java/org/springframework/ldap/odm/core/impl/DefaultObjectDirectoryMapperTest.java +++ b/core/src/test/java/org/springframework/ldap/odm/core/impl/DefaultObjectDirectoryMapperTest.java @@ -39,24 +39,20 @@ public class DefaultObjectDirectoryMapperTest { version.when(SpringVersion::getVersion).thenReturn(null); DefaultObjectDirectoryMapper mapper = new DefaultObjectDirectoryMapper(); // LDAP-300 - assertThat((Object) getInternalState(mapper,"converterManager")).isNotNull(); + assertThat((Object) getInternalState(mapper, "converterManager")).isNotNull(); } } @Test public void testMapping() { - assertThat(tested.manageClass(UnitTestPerson.class)) - .containsOnlyElementsOf(Arrays.asList("dn", "cn", "sn", "description", "telephoneNumber", "entryUUID", "objectclass")); + assertThat(tested.manageClass(UnitTestPerson.class)).containsOnlyElementsOf( + Arrays.asList("dn", "cn", "sn", "description", "telephoneNumber", "entryUUID", "objectclass")); DefaultObjectDirectoryMapper.EntityData entityData = tested.getMetaDataMap().get(UnitTestPerson.class); assertThat(entityData).isNotNull(); - assertThat(entityData.ocFilter).isEqualTo(query(). - where("objectclass").is("inetOrgPerson") - .and("objectclass").is("organizationalPerson") - .and("objectclass").is("person") - .and("objectclass").is("top") - .filter()); + assertThat(entityData.ocFilter).isEqualTo(query().where("objectclass").is("inetOrgPerson").and("objectclass") + .is("organizationalPerson").and("objectclass").is("person").and("objectclass").is("top").filter()); assertThat(entityData.metaData).hasSize(8); @@ -81,7 +77,8 @@ public class DefaultObjectDirectoryMapperTest { public void testInvalidType() { try { tested.manageClass(UnitTestPersonWithInvalidFieldType.class); - } catch (InvalidEntryException expected) { + } + catch (InvalidEntryException expected) { assertThat(expected.getMessage()).contains("Missing converter from"); } } @@ -95,7 +92,6 @@ public class DefaultObjectDirectoryMapperTest { testPerson.setCompany("Some Company"); testPerson.setCountry("Sweden"); - Name calculatedId = tested.getCalculatedId(testPerson); assertThat(calculatedId).isEqualTo(LdapUtils.newLdapName("cn=Some Person, ou=Some Company, c=Sweden")); } @@ -105,28 +101,25 @@ public class DefaultObjectDirectoryMapperTest { tested.manageClass(UnitTestPersonWithIndexedAndUnindexedDnAttributes.class); } - private void assertField(DefaultObjectDirectoryMapper.EntityData entityData, - String fieldName, - String expectedAttributeName, - String expectedDnAttributeName, - boolean expectedBinary, - boolean expectedTransient, - boolean expectedList, - boolean expectedReadOnly) { + private void assertField(DefaultObjectDirectoryMapper.EntityData entityData, String fieldName, + String expectedAttributeName, String expectedDnAttributeName, boolean expectedBinary, + boolean expectedTransient, boolean expectedList, boolean expectedReadOnly) { for (Field field : entityData.metaData) { if (fieldName.equals(field.getName())) { AttributeMetaData attribute = entityData.metaData.getAttribute(field); if (StringUtils.hasLength(expectedAttributeName)) { assertThat(attribute.getName().toString()).isEqualTo(expectedAttributeName); - } else { + } + else { assertThat(attribute.getName()).isNull(); } if (StringUtils.hasLength(expectedDnAttributeName)) { assertThat(attribute.isDnAttribute()).isTrue(); assertThat(attribute.getDnAttribute().value()).isEqualTo(expectedDnAttributeName); - } else { + } + else { assertThat(attribute.isDnAttribute()).isFalse(); } @@ -143,4 +136,5 @@ public class DefaultObjectDirectoryMapperTest { field.setAccessible(true); return (T) ReflectionUtils.getField(field, target); } + } diff --git a/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPerson.java b/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPerson.java index 4cbe3a5d..0ff1b081 100644 --- a/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPerson.java +++ b/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPerson.java @@ -29,8 +29,9 @@ import org.springframework.ldap.odm.annotations.Transient; /** * @author Mattias Hellborg Arthursson */ -@Entry(objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top"}) +@Entry(objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }) public class UnitTestPerson { + @Id private Name dn; @@ -58,4 +59,5 @@ public class UnitTestPerson { // operational attribute (defined in https://tools.ietf.org/html/rfc4530) @Attribute(readonly = true) private String entryUUID; + } diff --git a/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedAndUnindexedDnAttributes.java b/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedAndUnindexedDnAttributes.java index 13f40eb2..d8c92d62 100644 --- a/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedAndUnindexedDnAttributes.java +++ b/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedAndUnindexedDnAttributes.java @@ -25,19 +25,20 @@ import javax.naming.Name; /** * @author Mattias Hellborg Arthursson */ -@Entry(objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top"}) +@Entry(objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }) public class UnitTestPersonWithIndexedAndUnindexedDnAttributes { + @Id private Name dn; - @DnAttribute(value = "cn", index=2) + @DnAttribute(value = "cn", index = 2) private String fullName; // This makes the entry invalid @DnAttribute(value = "ou") private String company; - @DnAttribute(value= "c", index=0) + @DnAttribute(value = "c", index = 0) private String country; public void setFullName(String fullName) { @@ -51,4 +52,5 @@ public class UnitTestPersonWithIndexedAndUnindexedDnAttributes { public void setCountry(String country) { this.country = country; } + } diff --git a/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedDnAttributes.java b/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedDnAttributes.java index 7ee568bf..374db477 100644 --- a/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedDnAttributes.java +++ b/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedDnAttributes.java @@ -25,18 +25,19 @@ import javax.naming.Name; /** * @author Mattias Hellborg Arthursson */ -@Entry(objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top"}) +@Entry(objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }) public class UnitTestPersonWithIndexedDnAttributes { + @Id private Name dn; - @DnAttribute(value = "cn", index=2) + @DnAttribute(value = "cn", index = 2) private String fullName; - @DnAttribute(value = "ou", index=1) + @DnAttribute(value = "ou", index = 1) private String company; - @DnAttribute(value= "c", index=0) + @DnAttribute(value = "c", index = 0) private String country; public void setFullName(String fullName) { @@ -50,4 +51,5 @@ public class UnitTestPersonWithIndexedDnAttributes { public void setCountry(String country) { this.country = country; } + } diff --git a/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithInvalidFieldType.java b/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithInvalidFieldType.java index e0d3a851..4f5ef9d5 100644 --- a/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithInvalidFieldType.java +++ b/core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithInvalidFieldType.java @@ -25,8 +25,9 @@ import javax.naming.Name; /** * @author Mattias Hellborg Arthursson */ -@Entry(objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top"}) +@Entry(objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }) public class UnitTestPersonWithInvalidFieldType { + @Id private Name dn; diff --git a/core/src/test/java/org/springframework/ldap/pool/AbstractPoolTestCase.java b/core/src/test/java/org/springframework/ldap/pool/AbstractPoolTestCase.java index baf09bc6..283a943d 100644 --- a/core/src/test/java/org/springframework/ldap/pool/AbstractPoolTestCase.java +++ b/core/src/test/java/org/springframework/ldap/pool/AbstractPoolTestCase.java @@ -28,7 +28,7 @@ import static org.mockito.Mockito.mock; /** * Contains mocks common to many tests for the connection pool. - * + * * @author Ulrik Sandberg */ public abstract class AbstractPoolTestCase { @@ -54,4 +54,5 @@ public abstract class AbstractPoolTestCase { contextSourceMock = mock(ContextSource.class); dirContextValidatorMock = mock(DirContextValidator.class); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool/DelegatingContextTest.java b/core/src/test/java/org/springframework/ldap/pool/DelegatingContextTest.java index 3fa5957a..95572590 100644 --- a/core/src/test/java/org/springframework/ldap/pool/DelegatingContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/DelegatingContextTest.java @@ -30,8 +30,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu */ public class DelegatingContextTest extends AbstractPoolTestCase { @@ -40,22 +40,24 @@ public class DelegatingContextTest extends AbstractPoolTestCase { try { new DelegatingContext(null, contextMock, DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { - new DelegatingContext(keyedObjectPoolMock, null, - DirContextType.READ_ONLY); + new DelegatingContext(keyedObjectPoolMock, null, DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { new DelegatingContext(keyedObjectPoolMock, contextMock, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -63,14 +65,13 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testHelperMethods() throws Exception { // Wrap the Context once - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); final Context delegateContext = delegatingContext.getDelegateContext(); assertThat(delegateContext).isEqualTo(contextMock); - final Context innerDelegateContext = delegatingContext - .getInnermostDelegateContext(); + final Context innerDelegateContext = delegatingContext.getInnermostDelegateContext(); assertThat(innerDelegateContext).isEqualTo(contextMock); delegatingContext.assertOpen(); @@ -78,16 +79,13 @@ public class DelegatingContextTest extends AbstractPoolTestCase { // Wrap the wrapper KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); - final DelegatingContext delegatingContext2 = new DelegatingContext( - secondKeyedObjectPoolMock, delegatingContext, + final DelegatingContext delegatingContext2 = new DelegatingContext(secondKeyedObjectPoolMock, delegatingContext, DirContextType.READ_ONLY); - final Context delegateContext2 = delegatingContext2 - .getDelegateContext(); + final Context delegateContext2 = delegatingContext2.getDelegateContext(); assertThat(delegateContext2).isEqualTo(delegatingContext); - final Context innerDelegateContext2 = delegatingContext2 - .getInnermostDelegateContext(); + final Context innerDelegateContext2 = delegatingContext2.getInnermostDelegateContext(); assertThat(innerDelegateContext2).isEqualTo(contextMock); delegatingContext2.assertOpen(); @@ -95,57 +93,54 @@ public class DelegatingContextTest extends AbstractPoolTestCase { // Close the outer wrapper delegatingContext2.close(); - final Context delegateContext2closed = delegatingContext2 - .getDelegateContext(); + final Context delegateContext2closed = delegatingContext2.getDelegateContext(); assertThat(delegateContext2closed).isNull(); - final Context innerDelegateContext2closed = delegatingContext2 - .getInnermostDelegateContext(); + final Context innerDelegateContext2closed = delegatingContext2.getInnermostDelegateContext(); assertThat(innerDelegateContext2closed).isNull(); try { delegatingContext2.assertOpen(); fail("delegatingContext2.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } // Close the outer wrapper delegatingContext.close(); - final Context delegateContextclosed = delegatingContext - .getDelegateContext(); + final Context delegateContextclosed = delegatingContext.getDelegateContext(); assertThat(delegateContextclosed).isNull(); - final Context innerDelegateContextclosed = delegatingContext - .getInnermostDelegateContext(); + final Context innerDelegateContextclosed = delegatingContext.getInnermostDelegateContext(); assertThat(innerDelegateContextclosed).isNull(); try { delegatingContext.assertOpen(); fail("delegatingContext.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); - verify(secondKeyedObjectPoolMock) - .returnObject(DirContextType.READ_ONLY, contextMock); + verify(secondKeyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); } @Test public void testObjectMethods() throws Exception { // Wrap the Context once - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); assertThat(delegatingContext.toString()).isEqualTo(contextMock.toString()); delegatingContext.hashCode(); // Run it to make sure it doesn't fail assertThat(delegatingContext.equals(delegatingContext)).isTrue(); assertThat(delegatingContext.equals(new Object())).isFalse(); - final DelegatingContext delegatingContext2 = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext2 = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); assertThat(delegatingContext.equals(delegatingContext2)).isTrue(); assertThat(delegatingContext2.equals(delegatingContext)).isTrue(); assertThat(delegatingContext.equals(contextMock)).isTrue(); @@ -169,51 +164,57 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testUnsupportedMethods() throws Exception { - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); try { delegatingContext.addToEnvironment(null, null); fail("DelegatingContext.addToEnvironment Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.createSubcontext((Name) null); fail("DelegatingContext.createSubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.createSubcontext((String) null); fail("DelegatingContext.createSubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.destroySubcontext((Name) null); fail("DelegatingContext.destroySubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.destroySubcontext((String) null); fail("DelegatingContext.destroySubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.removeFromEnvironment(null); fail("DelegatingContext.removeFromEnvironment Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } } @Test public void testAllMethodsOpened() throws Exception { - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); delegatingContext.bind((Name) null, null); delegatingContext.bind((String) null, null); @@ -241,142 +242,164 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testAllMethodsClosed() throws Exception { - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); delegatingContext.close(); try { delegatingContext.bind((Name) null, null); fail("DelegatingContext.bind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.bind((String) null, null); fail("DelegatingContext.bind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.composeName((Name) null, (Name) null); fail("DelegatingContext.composeName should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.composeName((String) null, (String) null); fail("DelegatingContext.composeName should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.getEnvironment(); fail("DelegatingContext.getEnvironment should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.getNameInNamespace(); fail("DelegatingContext.getNameInNamespace should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.getNameParser((Name) null); fail("DelegatingContext.getNameParser should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.getNameParser((String) null); fail("DelegatingContext.getNameParser should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.list((Name) null); fail("DelegatingContext.list should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.list((String) null); fail("DelegatingContext.list should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.listBindings((Name) null); fail("DelegatingContext.listBindings should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.listBindings((String) null); fail("DelegatingContext.listBindings should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.lookup((Name) null); fail("DelegatingContext.lookup should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.lookup((String) null); fail("DelegatingContext.lookup should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.lookupLink((Name) null); fail("DelegatingContext.lookupLink should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.lookupLink((String) null); fail("DelegatingContext.lookupLink should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.rebind((Name) null, null); fail("DelegatingContext.rebind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.rebind((String) null, null); fail("DelegatingContext.rebind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.rename((Name) null, (Name) null); fail("DelegatingContext.rename should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.rename((String) null, (String) null); fail("DelegatingContext.rename should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.unbind((Name) null); fail("DelegatingContext.unbind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.unbind((String) null); fail("DelegatingContext.unbind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); @@ -384,8 +407,8 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testDoubleClose() throws Exception { - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); delegatingContext.close(); @@ -397,17 +420,19 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testPoolExceptionOnClose() throws Exception { - doThrow(new Exception("Fake Pool returnObject Exception")) - .when(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); + doThrow(new Exception("Fake Pool returnObject Exception")).when(keyedObjectPoolMock) + .returnObject(DirContextType.READ_ONLY, contextMock); - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); try { delegatingContext.close(); fail("DelegatingContext.close should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } } + } diff --git a/core/src/test/java/org/springframework/ldap/pool/DelegatingDirContextTest.java b/core/src/test/java/org/springframework/ldap/pool/DelegatingDirContextTest.java index e69a6054..8995622e 100644 --- a/core/src/test/java/org/springframework/ldap/pool/DelegatingDirContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/DelegatingDirContextTest.java @@ -31,24 +31,26 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu */ public class DelegatingDirContextTest extends AbstractPoolTestCase { + @Test public void testConstructorAssertions() { try { - new DelegatingDirContext(keyedObjectPoolMock, null, - DirContextType.READ_ONLY); + new DelegatingDirContext(keyedObjectPoolMock, null, DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -57,19 +59,16 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { public void testHelperMethods() throws Exception { // Wrap the DirContext once - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); - final Context delegateContext = delegatingDirContext - .getDelegateContext(); + final Context delegateContext = delegatingDirContext.getDelegateContext(); assertThat(delegateContext).isEqualTo(dirContextMock); - final DirContext delegateDirContext = delegatingDirContext - .getDelegateDirContext(); + final DirContext delegateDirContext = delegatingDirContext.getDelegateDirContext(); assertThat(delegateDirContext).isEqualTo(dirContextMock); - final DirContext innerDelegateDirContext = delegatingDirContext - .getInnermostDelegateDirContext(); + final DirContext innerDelegateDirContext = delegatingDirContext.getInnermostDelegateDirContext(); assertThat(innerDelegateDirContext).isEqualTo(dirContextMock); delegatingDirContext.assertOpen(); @@ -77,16 +76,13 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { // Wrap the wrapper KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); - final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext( - secondKeyedObjectPoolMock, delegatingDirContext, - DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext(secondKeyedObjectPoolMock, + delegatingDirContext, DirContextType.READ_ONLY); - final DirContext delegateDirContext2 = delegatingDirContext2 - .getDelegateDirContext(); + final DirContext delegateDirContext2 = delegatingDirContext2.getDelegateDirContext(); assertThat(delegateDirContext2).isEqualTo(delegatingDirContext); - final DirContext innerDelegateDirContext2 = delegatingDirContext2 - .getInnermostDelegateDirContext(); + final DirContext innerDelegateDirContext2 = delegatingDirContext2.getInnermostDelegateDirContext(); assertThat(innerDelegateDirContext2).isEqualTo(dirContextMock); delegatingDirContext2.assertOpen(); @@ -94,49 +90,46 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { // Close the outer wrapper delegatingDirContext2.close(); - final DirContext delegateContext2closed = delegatingDirContext2 - .getDelegateDirContext(); + final DirContext delegateContext2closed = delegatingDirContext2.getDelegateDirContext(); assertThat(delegateContext2closed).isNull(); - final DirContext innerDelegateContext2closed = delegatingDirContext2 - .getInnermostDelegateDirContext(); + final DirContext innerDelegateContext2closed = delegatingDirContext2.getInnermostDelegateDirContext(); assertThat(innerDelegateContext2closed).isNull(); try { delegatingDirContext2.assertOpen(); fail("delegatingDirContext2.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } // Close the outer wrapper delegatingDirContext.close(); - final DirContext delegateDirContextClosed = delegatingDirContext - .getDelegateDirContext(); + final DirContext delegateDirContextClosed = delegatingDirContext.getDelegateDirContext(); assertThat(delegateDirContextClosed).isNull(); - final DirContext innerDelegateDirContextClosed = delegatingDirContext - .getInnermostDelegateDirContext(); + final DirContext innerDelegateDirContextClosed = delegatingDirContext.getInnermostDelegateDirContext(); assertThat(innerDelegateDirContextClosed).isNull(); try { delegatingDirContext.assertOpen(); fail("delegatingDirContext.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } - verify(secondKeyedObjectPoolMock) - .returnObject(DirContextType.READ_ONLY, dirContextMock); + verify(secondKeyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); } @Test public void testObjectMethods() throws Exception { // Wrap the DirContext once - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); assertThat(delegatingDirContext.toString()).isEqualTo(dirContextMock.toString()); delegatingDirContext.hashCode(); // Run it to make sure it doesn't // fail @@ -144,8 +137,8 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { assertThat(delegatingDirContext.equals(delegatingDirContext)).isTrue(); assertThat(delegatingDirContext.equals(new Object())).isFalse(); - final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); assertThat(delegatingDirContext.equals(delegatingDirContext2)).isTrue(); assertThat(delegatingDirContext2.equals(delegatingDirContext)).isTrue(); assertThat(delegatingDirContext.equals(dirContextMock)).isTrue(); @@ -155,8 +148,8 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { assertThat(delegatingDirContext.toString()).isEqualTo("DirContext is closed"); assertThat(delegatingDirContext.hashCode()).isEqualTo(0); // Run it to make - // sure it doesn't - // fail + // sure it doesn't + // fail assertThat(delegatingDirContext.equals(delegatingDirContext)).isTrue(); assertThat(delegatingDirContext.equals(new Object())).isFalse(); @@ -170,51 +163,57 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { @Test public void testUnsupportedMethods() throws Exception { - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); try { delegatingDirContext.createSubcontext((Name) null, null); fail("DelegatingDirContext.createSubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.createSubcontext((String) null, null); fail("DelegatingDirContext.createSubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.getSchema((Name) null); fail("DelegatingDirContext.getSchema Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.getSchema((String) null); fail("DelegatingDirContext.getSchema Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.getSchemaClassDefinition((Name) null); fail("DelegatingDirContext.getSchemaClassDefinition Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.getSchemaClassDefinition((String) null); fail("DelegatingDirContext.getSchemaClassDefinition Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } } @Test public void testAllMethodsOpened() throws Exception { - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); delegatingDirContext.bind((Name) null, null, null); delegatingDirContext.bind((String) null, null, null); @@ -240,130 +239,150 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { @Test public void testAllMethodsClosed() throws Exception { - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); delegatingDirContext.close(); try { delegatingDirContext.bind((Name) null, null, null); fail("DelegatingDirContext.bind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.bind((String) null, null, null); fail("DelegatingDirContext.bind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.getAttributes((Name) null, null); fail("DelegatingDirContext.getAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.getAttributes((Name) null); fail("DelegatingDirContext.getAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.getAttributes((String) null, null); fail("DelegatingDirContext.getAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.getAttributes((String) null); fail("DelegatingDirContext.getAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.modifyAttributes((Name) null, 0, null); fail("DelegatingDirContext.modifyAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.modifyAttributes((Name) null, null); fail("DelegatingDirContext.modifyAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.modifyAttributes((String) null, 0, null); fail("DelegatingDirContext.modifyAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.modifyAttributes((String) null, null); fail("DelegatingDirContext.modifyAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.rebind((Name) null, null, null); fail("DelegatingDirContext.rebind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.rebind((String) null, null, null); fail("DelegatingDirContext.rebind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((Name) null, (Attributes) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((Name) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((Name) null, null, null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((Name) null, (String) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((String) null, (Attributes) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((String) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((String) null, null, null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((String) null, (String) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); @@ -371,8 +390,8 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { @Test public void testDoubleClose() throws Exception { - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); delegatingDirContext.close(); @@ -381,4 +400,5 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, dirContextMock); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java b/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java index 9d2420e2..7337580f 100644 --- a/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java @@ -29,25 +29,26 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu */ public class DelegatingLdapContextTest extends AbstractPoolTestCase { + @Test public void testConstructorAssertions() { try { - new DelegatingLdapContext(keyedObjectPoolMock, null, - DirContextType.READ_ONLY); + new DelegatingLdapContext(keyedObjectPoolMock, null, DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { - new DelegatingLdapContext(keyedObjectPoolMock, ldapContextMock, - null); + new DelegatingLdapContext(keyedObjectPoolMock, ldapContextMock, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -55,19 +56,16 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { @Test public void testHelperMethods() throws Exception { // Wrap the LdapContext once - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); - final DirContext delegateDirContext = delegatingLdapContext - .getDelegateDirContext(); + final DirContext delegateDirContext = delegatingLdapContext.getDelegateDirContext(); assertThat(delegateDirContext).isEqualTo(ldapContextMock); - final LdapContext delegateLdapContext = delegatingLdapContext - .getDelegateLdapContext(); + final LdapContext delegateLdapContext = delegatingLdapContext.getDelegateLdapContext(); assertThat(delegateLdapContext).isEqualTo(ldapContextMock); - final LdapContext innerDelegateLdapContext = delegatingLdapContext - .getInnermostDelegateLdapContext(); + final LdapContext innerDelegateLdapContext = delegatingLdapContext.getInnermostDelegateLdapContext(); assertThat(innerDelegateLdapContext).isEqualTo(ldapContextMock); delegatingLdapContext.assertOpen(); @@ -75,16 +73,13 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { // Wrap the wrapper KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); - final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext( - secondKeyedObjectPoolMock, delegatingLdapContext, - DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext(secondKeyedObjectPoolMock, + delegatingLdapContext, DirContextType.READ_ONLY); - final LdapContext delegateLdapContext2 = delegatingLdapContext2 - .getDelegateLdapContext(); + final LdapContext delegateLdapContext2 = delegatingLdapContext2.getDelegateLdapContext(); assertThat(delegateLdapContext2).isEqualTo(delegatingLdapContext); - final LdapContext innerDelegateLdapContext2 = delegatingLdapContext2 - .getInnermostDelegateLdapContext(); + final LdapContext innerDelegateLdapContext2 = delegatingLdapContext2.getInnermostDelegateLdapContext(); assertThat(innerDelegateLdapContext2).isEqualTo(ldapContextMock); delegatingLdapContext2.assertOpen(); @@ -92,57 +87,54 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { // Close the outer wrapper delegatingLdapContext2.close(); - final LdapContext delegateContext2closed = delegatingLdapContext2 - .getDelegateLdapContext(); + final LdapContext delegateContext2closed = delegatingLdapContext2.getDelegateLdapContext(); assertThat(delegateContext2closed).isNull(); - final LdapContext innerDelegateContext2closed = delegatingLdapContext2 - .getInnermostDelegateLdapContext(); + final LdapContext innerDelegateContext2closed = delegatingLdapContext2.getInnermostDelegateLdapContext(); assertThat(innerDelegateContext2closed).isNull(); try { delegatingLdapContext2.assertOpen(); fail("delegatingLdapContext2.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } // Close the outer wrapper delegatingLdapContext.close(); - final LdapContext delegateLdapContextClosed = delegatingLdapContext - .getDelegateLdapContext(); + final LdapContext delegateLdapContextClosed = delegatingLdapContext.getDelegateLdapContext(); assertThat(delegateLdapContextClosed).isNull(); - final LdapContext innerDelegateLdapContextClosed = delegatingLdapContext - .getInnermostDelegateLdapContext(); + final LdapContext innerDelegateLdapContextClosed = delegatingLdapContext.getInnermostDelegateLdapContext(); assertThat(innerDelegateLdapContextClosed).isNull(); try { delegatingLdapContext.assertOpen(); fail("delegatingLdapContext.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } - verify(secondKeyedObjectPoolMock) - .returnObject(DirContextType.READ_ONLY, ldapContextMock); + verify(secondKeyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); } @Test public void testObjectMethods() throws Exception { // Wrap the LdapContext once - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); assertThat(delegatingLdapContext.toString()).isEqualTo(ldapContextMock.toString()); delegatingLdapContext.hashCode(); // Run it to make sure it doesn't fail assertThat(delegatingLdapContext.equals(delegatingLdapContext)).isTrue(); assertThat(delegatingLdapContext.equals(new Object())).isFalse(); - final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); assertThat(delegatingLdapContext.equals(delegatingLdapContext2)).isTrue(); assertThat(delegatingLdapContext2.equals(delegatingLdapContext)).isTrue(); assertThat(delegatingLdapContext.equals(ldapContextMock)).isTrue(); @@ -152,8 +144,8 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { assertThat(delegatingLdapContext.toString()).isEqualTo("LdapContext is closed"); assertThat(delegatingLdapContext.hashCode()).isEqualTo(0); // Run it to make - // sure it doesn't - // fail + // sure it doesn't + // fail assertThat(delegatingLdapContext.equals(delegatingLdapContext)).isTrue(); assertThat(delegatingLdapContext.equals(new Object())).isFalse(); @@ -167,25 +159,28 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { @Test public void testUnsupportedMethods() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); try { delegatingLdapContext.newInstance(null); fail("DelegatingLdapContext.newInstance Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingLdapContext.reconnect(null); fail("DelegatingLdapContext.reconnect Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingLdapContext.setRequestControls(null); fail("DelegatingLdapContext.setRequestControls Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } } @@ -193,8 +188,8 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { // nice @Test public void testAllMethodsOpened() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.extendedOperation(null); delegatingLdapContext.getConnectControls(); @@ -204,34 +199,38 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { @Test public void testAllMethodsClosed() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.close(); try { delegatingLdapContext.extendedOperation(null); fail("DelegatingLdapContext.extendedOperation should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingLdapContext.getConnectControls(); fail("DelegatingLdapContext.getConnectControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingLdapContext.getRequestControls(); fail("DelegatingLdapContext.getRequestControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingLdapContext.getResponseControls(); fail("DelegatingLdapContext.getResponseControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); @@ -239,8 +238,8 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { @Test public void testDoubleClose() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.close(); @@ -249,4 +248,5 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, ldapContextMock); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java b/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java index 8cdd202d..c38a2fbd 100644 --- a/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java @@ -21,17 +21,19 @@ import static org.mockito.Mockito.verify; /** * Unit tests for the MutableDelegatingLdapContext class. - * + * * @author Ulrik Sandberg */ public class MutableDelegatingLdapContextTest extends AbstractPoolTestCase { + @Test public void testSupportedMethodsAllowedToCall() throws Exception { - final MutableDelegatingLdapContext delegatingLdapContext = new MutableDelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final MutableDelegatingLdapContext delegatingLdapContext = new MutableDelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.setRequestControls(null); verify(ldapContextMock).setRequestControls(null); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactoryTest.java b/core/src/test/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactoryTest.java index 1519033d..521f337d 100644 --- a/core/src/test/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactoryTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/factory/DirContextPoolableObjectFactoryTest.java @@ -57,7 +57,6 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { final ContextSource contextSource2 = objectFactory.getContextSource(); assertThat(contextSource2).isEqualTo(contextSourceMock); - try { objectFactory.setDirContextValidator(null); fail("DirContextPoolableObjectFactory.setDirContextValidator should have thrown an IllegalArgumentException"); @@ -78,7 +77,8 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { try { objectFactory.makeObject(DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -87,7 +87,8 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { try { objectFactory.makeObject(null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -128,7 +129,8 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { try { objectFactory.validateObject(DirContextType.READ_ONLY, dirContextMock); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -137,37 +139,39 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { try { objectFactory.validateObject(null, dirContextMock); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { objectFactory.validateObject(new Object(), dirContextMock); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { objectFactory.validateObject(DirContextType.READ_ONLY, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { objectFactory.validateObject(DirContextType.READ_ONLY, new Object()); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @Test public void testValidateObject() throws Exception { - when(dirContextValidatorMock - .validateDirContext(DirContextType.READ_ONLY, dirContextMock)) - .thenReturn(true); + when(dirContextValidatorMock.validateDirContext(DirContextType.READ_ONLY, dirContextMock)).thenReturn(true); final DirContextPoolableObjectFactory objectFactory = new DirContextPoolableObjectFactory(); objectFactory.setDirContextValidator(dirContextValidatorMock); @@ -175,7 +179,7 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { final boolean valid = objectFactory.validateObject(DirContextType.READ_ONLY, dirContextMock); assertThat(valid).isTrue(); - //Check exception in validator + // Check exception in validator DirContextValidator secondDirContextValidatorMock = mock(DirContextValidator.class); when(secondDirContextValidatorMock.validateDirContext(DirContextType.READ_ONLY, dirContextMock)) @@ -193,14 +197,16 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { try { objectFactory.destroyObject(DirContextType.READ_ONLY, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { objectFactory.validateObject(DirContextType.READ_ONLY, new Object()); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -213,8 +219,7 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { DirContext throwingDirContextMock = Mockito.mock(DirContext.class); - doThrow(new RuntimeException("Failed to close")) - .when(throwingDirContextMock).close(); + doThrow(new RuntimeException("Failed to close")).when(throwingDirContextMock).close(); objectFactory.destroyObject(DirContextType.READ_ONLY, throwingDirContextMock); verify(dirContextMock).close(); @@ -225,4 +230,5 @@ public class DirContextPoolableObjectFactoryTest extends AbstractPoolTestCase { field.setAccessible(true); return (T) ReflectionUtils.getField(field, target); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool/factory/MutablePoolingContextSourceTest.java b/core/src/test/java/org/springframework/ldap/pool/factory/MutablePoolingContextSourceTest.java index 8be52610..30d50d6a 100644 --- a/core/src/test/java/org/springframework/ldap/pool/factory/MutablePoolingContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/factory/MutablePoolingContextSourceTest.java @@ -26,7 +26,7 @@ import static org.mockito.Mockito.when; /** * Unit tests for the MutablePoolingContextSource class. - * + * * @author Ulrik Sandberg */ public class MutablePoolingContextSourceTest extends AbstractPoolTestCase { @@ -44,4 +44,5 @@ public class MutablePoolingContextSourceTest extends AbstractPoolTestCase { assertThat(result.getClass()).isEqualTo(MutableDelegatingLdapContext.class); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool/factory/PoolingContextSourceTest.java b/core/src/test/java/org/springframework/ldap/pool/factory/PoolingContextSourceTest.java index d1254f3f..7b0b5be5 100644 --- a/core/src/test/java/org/springframework/ldap/pool/factory/PoolingContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/factory/PoolingContextSourceTest.java @@ -49,7 +49,7 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { poolingContextSource.setContextSource(contextSourceMock); final ContextSource contextSource2 = poolingContextSource.getContextSource(); assertThat(contextSource2).isEqualTo(contextSourceMock); - + try { poolingContextSource.setDirContextValidator(null); fail("PoolingContextSource.setDirContextValidator should have thrown an IllegalArgumentException"); @@ -60,58 +60,58 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { poolingContextSource.setDirContextValidator(dirContextValidatorMock); final DirContextValidator dirContextValidator2 = poolingContextSource.getDirContextValidator(); assertThat(dirContextValidator2).isEqualTo(dirContextValidatorMock); - + poolingContextSource.setMaxActive(1000); final int maxActive = poolingContextSource.getMaxActive(); assertThat(maxActive).isEqualTo(1000); - + poolingContextSource.setMaxIdle(500); final int maxIdle = poolingContextSource.getMaxIdle(); assertThat(maxIdle).isEqualTo(500); - + poolingContextSource.setMaxTotal(5000); final int maxTotal = poolingContextSource.getMaxTotal(); assertThat(maxTotal).isEqualTo(5000); - + poolingContextSource.setMaxWait(2000L); final long maxWait = poolingContextSource.getMaxWait(); assertThat(maxWait).isEqualTo(2000L); - + poolingContextSource.setMinEvictableIdleTimeMillis(60000L); final long minEvictableIdleTimeMillis = poolingContextSource.getMinEvictableIdleTimeMillis(); assertThat(minEvictableIdleTimeMillis).isEqualTo(60000L); - + poolingContextSource.setMinIdle(100); final int minIdle = poolingContextSource.getMinIdle(); assertThat(minIdle).isEqualTo(100); - + poolingContextSource.setNumTestsPerEvictionRun(5); final int numTestsPerEvictionRun = poolingContextSource.getNumTestsPerEvictionRun(); assertThat(numTestsPerEvictionRun).isEqualTo(5); - + poolingContextSource.setTestOnBorrow(true); final boolean testOnBorrow = poolingContextSource.getTestOnBorrow(); assertThat(testOnBorrow).isEqualTo(true); - + poolingContextSource.setTestOnReturn(true); final boolean testOnReturn = poolingContextSource.getTestOnReturn(); assertThat(testOnReturn).isEqualTo(true); - + poolingContextSource.setTestWhileIdle(true); final boolean testWhileIdle = poolingContextSource.getTestWhileIdle(); assertThat(testWhileIdle).isEqualTo(true); - + poolingContextSource.setTimeBetweenEvictionRunsMillis(120000L); final long timeBetweenEvictionRunsMillis = poolingContextSource.getTimeBetweenEvictionRunsMillis(); assertThat(timeBetweenEvictionRunsMillis).isEqualTo(120000L); - + poolingContextSource.setWhenExhaustedAction(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK); final byte whenExhaustedAction = poolingContextSource.getWhenExhaustedAction(); assertThat(whenExhaustedAction).isEqualTo(GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK); - + final int numActive = poolingContextSource.getNumActive(); assertThat(numActive).isEqualTo(0); - + final int numIdle = poolingContextSource.getNumIdle(); assertThat(numIdle).isEqualTo(0); } @@ -119,41 +119,49 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { @Test public void testGetReadOnlyContextPool() throws Exception { DirContext secondDirContextMock = mock(DirContext.class); - + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock, secondDirContextMock); final PoolingContextSource poolingContextSource = new PoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); - //Get a context + // Get a context final DirContext readOnlyContext1 = poolingContextSource.getReadOnlyContext(); - assertThat(readOnlyContext1).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext1).isEqualTo(dirContextMock); // Order reversed because + // the 'wrapper' has the + // needed equals logic assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - - //Close the context + + // Close the context readOnlyContext1.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(0); assertThat(poolingContextSource.getNumIdle()).isEqualTo(1); - - //Get the context again + + // Get the context again final DirContext readOnlyContext2 = poolingContextSource.getReadOnlyContext(); - assertThat(readOnlyContext2).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext2).isEqualTo(dirContextMock); // Order reversed because + // the 'wrapper' has the + // needed equals logic assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - - //Get a new context + + // Get a new context final DirContext readOnlyContext3 = poolingContextSource.getReadOnlyContext(); - assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); // Order reversed + // because the + // 'wrapper' has + // the needed + // equals logic assertThat(poolingContextSource.getNumActive()).isEqualTo(2); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - //Close context + // Close context readOnlyContext2.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(1); - - //Close context + + // Close context readOnlyContext3.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(0); assertThat(poolingContextSource.getNumIdle()).isEqualTo(2); @@ -162,41 +170,49 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { @Test public void testGetReadWriteContextPool() throws Exception { DirContext secondDirContextMock = mock(DirContext.class); - + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock, secondDirContextMock); final PoolingContextSource poolingContextSource = new PoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); - //Get a context + // Get a context final DirContext readOnlyContext1 = poolingContextSource.getReadWriteContext(); - assertThat(readOnlyContext1).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext1).isEqualTo(dirContextMock); // Order reversed because + // the 'wrapper' has the + // needed equals logic assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - - //Close the context + + // Close the context readOnlyContext1.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(0); assertThat(poolingContextSource.getNumIdle()).isEqualTo(1); - - //Get the context again + + // Get the context again final DirContext readOnlyContext2 = poolingContextSource.getReadWriteContext(); - assertThat(readOnlyContext2).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext2).isEqualTo(dirContextMock); // Order reversed because + // the 'wrapper' has the + // needed equals logic assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - - //Get a new context + + // Get a new context final DirContext readOnlyContext3 = poolingContextSource.getReadWriteContext(); - assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); // Order reversed + // because the + // 'wrapper' has + // the needed + // equals logic assertThat(poolingContextSource.getNumActive()).isEqualTo(2); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - //Close context + // Close context readOnlyContext2.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(1); - - //Close context + + // Close context readOnlyContext3.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(0); assertThat(poolingContextSource.getNumIdle()).isEqualTo(2); @@ -204,8 +220,7 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { @Test public void testGetContextException() throws Exception { - when(contextSourceMock.getReadWriteContext()) - .thenThrow(new RuntimeException("Problem getting context")); + when(contextSourceMock.getReadWriteContext()).thenThrow(new RuntimeException("Problem getting context")); final PoolingContextSource poolingContextSource = new PoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); @@ -228,37 +243,48 @@ public class PoolingContextSourceTest extends AbstractPoolTestCase { final PoolingContextSource poolingContextSource = new PoolingContextSource(); poolingContextSource.setContextSource(contextSourceMock); - //Get a context + // Get a context final DirContext readOnlyContext1 = poolingContextSource.getReadOnlyContext(); - assertThat(readOnlyContext1).isEqualTo(ldapContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext1).isEqualTo(ldapContextMock); // Order reversed because + // the 'wrapper' has + // the needed equals + // logic assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - - //Close the context + + // Close the context readOnlyContext1.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(0); assertThat(poolingContextSource.getNumIdle()).isEqualTo(1); - - //Get the context again + + // Get the context again final DirContext readOnlyContext2 = poolingContextSource.getReadOnlyContext(); - assertThat(readOnlyContext2).isEqualTo(ldapContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext2).isEqualTo(ldapContextMock); // Order reversed because + // the 'wrapper' has + // the needed equals + // logic assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - - //Get a new context + + // Get a new context final DirContext readOnlyContext3 = poolingContextSource.getReadOnlyContext(); - assertThat(readOnlyContext3).isEqualTo(secondLdapContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext3).isEqualTo(secondLdapContextMock); // Order reversed + // because the + // 'wrapper' has + // the needed + // equals logic assertThat(poolingContextSource.getNumActive()).isEqualTo(2); assertThat(poolingContextSource.getNumIdle()).isEqualTo(0); - //Close context + // Close context readOnlyContext2.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(1); assertThat(poolingContextSource.getNumIdle()).isEqualTo(1); - - //Close context + + // Close context readOnlyContext3.close(); assertThat(poolingContextSource.getNumActive()).isEqualTo(0); assertThat(poolingContextSource.getNumIdle()).isEqualTo(2); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool/validation/DefaultDirContextValidatorTest.java b/core/src/test/java/org/springframework/ldap/pool/validation/DefaultDirContextValidatorTest.java index 10485256..c96956e9 100644 --- a/core/src/test/java/org/springframework/ldap/pool/validation/DefaultDirContextValidatorTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/validation/DefaultDirContextValidatorTest.java @@ -30,8 +30,8 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu */ public class DefaultDirContextValidatorTest { @@ -49,21 +49,24 @@ public class DefaultDirContextValidatorTest { @Test public void testSearchScopeOneLevelScopeSetInConstructorIsUsed() throws Exception { DefaultDirContextValidator tested = new DefaultDirContextValidator(SearchControls.ONELEVEL_SCOPE); - assertThat(tested.getSearchControls().getSearchScope()).as("ONELEVEL_SCOPE, ").isEqualTo(SearchControls.ONELEVEL_SCOPE); + assertThat(tested.getSearchControls().getSearchScope()).as("ONELEVEL_SCOPE, ") + .isEqualTo(SearchControls.ONELEVEL_SCOPE); } - + // LDAP-189 @Test public void testSearchScopeSubTreeScopeSetInConstructorIsUsed() throws Exception { DefaultDirContextValidator tested = new DefaultDirContextValidator(SearchControls.SUBTREE_SCOPE); - assertThat(tested.getSearchControls().getSearchScope()).as("SUBTREE_SCOPE, ").isEqualTo(SearchControls.SUBTREE_SCOPE); + assertThat(tested.getSearchControls().getSearchScope()).as("SUBTREE_SCOPE, ") + .isEqualTo(SearchControls.SUBTREE_SCOPE); } // LDAP-189 @Test public void testSearchScopeObjectScopeSetInConstructorIsUsed() throws Exception { DefaultDirContextValidator tested = new DefaultDirContextValidator(SearchControls.OBJECT_SCOPE); - assertThat(tested.getSearchControls().getSearchScope()).as("OBJECT_SCOPE, ").isEqualTo(SearchControls.OBJECT_SCOPE); + assertThat(tested.getSearchControls().getSearchScope()).as("OBJECT_SCOPE, ") + .isEqualTo(SearchControls.OBJECT_SCOPE); } @Test @@ -77,7 +80,8 @@ public class DefaultDirContextValidatorTest { try { dirContextValidator.setFilter(null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } dirContextValidator.setFilter("filter"); @@ -87,7 +91,8 @@ public class DefaultDirContextValidatorTest { try { dirContextValidator.setSearchControls(null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } final SearchControls sc = new SearchControls(); @@ -101,17 +106,18 @@ public class DefaultDirContextValidatorTest { final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); try { - dirContextValidator.validateDirContext(DirContextType.READ_ONLY, - null); + dirContextValidator.validateDirContext(DirContextType.READ_ONLY, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { dirContextValidator.validateDirContext(null, dirContextMock); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -122,15 +128,12 @@ public class DefaultDirContextValidatorTest { final String baseName = dirContextValidator.getBase(); final String filter = dirContextValidator.getFilter(); - final SearchControls searchControls = dirContextValidator - .getSearchControls(); + final SearchControls searchControls = dirContextValidator.getSearchControls(); when(namingEnumerationMock.hasMore()).thenReturn(true); - when(dirContextMock.search(baseName, filter, searchControls)) - .thenReturn(namingEnumerationMock); + when(dirContextMock.search(baseName, filter, searchControls)).thenReturn(namingEnumerationMock); - final boolean valid = dirContextValidator.validateDirContext( - DirContextType.READ_ONLY, dirContextMock); + final boolean valid = dirContextValidator.validateDirContext(DirContextType.READ_ONLY, dirContextMock); assertThat(valid).isTrue(); } @@ -140,15 +143,12 @@ public class DefaultDirContextValidatorTest { final String baseName = dirContextValidator.getBase(); final String filter = dirContextValidator.getFilter(); - final SearchControls searchControls = dirContextValidator - .getSearchControls(); + final SearchControls searchControls = dirContextValidator.getSearchControls(); when(namingEnumerationMock.hasMore()).thenReturn(false); - when(dirContextMock.search(baseName, filter, searchControls)) - .thenReturn(namingEnumerationMock); + when(dirContextMock.search(baseName, filter, searchControls)).thenReturn(namingEnumerationMock); - final boolean valid = dirContextValidator.validateDirContext( - DirContextType.READ_ONLY, dirContextMock); + final boolean valid = dirContextValidator.validateDirContext(DirContextType.READ_ONLY, dirContextMock); assertThat(valid).isFalse(); } @@ -159,15 +159,14 @@ public class DefaultDirContextValidatorTest { final String baseName = dirContextValidator.getBase(); final String filter = dirContextValidator.getFilter(); - final SearchControls searchControls = dirContextValidator - .getSearchControls(); + final SearchControls searchControls = dirContextValidator.getSearchControls(); when(dirContextMock.search(baseName, filter, searchControls)) .thenThrow(new NamingException("Failed to search")); - final boolean valid = dirContextValidator.validateDirContext( - DirContextType.READ_ONLY, dirContextMock); + final boolean valid = dirContextValidator.validateDirContext(DirContextType.READ_ONLY, dirContextMock); assertThat(valid).isFalse(); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/AbstractPoolTestCase.java b/core/src/test/java/org/springframework/ldap/pool2/AbstractPoolTestCase.java index 652eec6d..d76ed144 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/AbstractPoolTestCase.java +++ b/core/src/test/java/org/springframework/ldap/pool2/AbstractPoolTestCase.java @@ -28,7 +28,7 @@ import static org.mockito.Mockito.mock; /** * Contains mocks common to many tests for the connection pool. - * + * * @author Ulrik Sandberg */ public abstract class AbstractPoolTestCase { @@ -54,4 +54,5 @@ public abstract class AbstractPoolTestCase { contextSourceMock = mock(ContextSource.class); dirContextValidatorMock = mock(DirContextValidator.class); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/DelegatingContextTest.java b/core/src/test/java/org/springframework/ldap/pool2/DelegatingContextTest.java index dfa73307..63a63a66 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/DelegatingContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool2/DelegatingContextTest.java @@ -30,8 +30,8 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu */ public class DelegatingContextTest extends AbstractPoolTestCase { @@ -40,22 +40,24 @@ public class DelegatingContextTest extends AbstractPoolTestCase { try { new DelegatingContext(null, contextMock, DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { - new DelegatingContext(keyedObjectPoolMock, null, - DirContextType.READ_ONLY); + new DelegatingContext(keyedObjectPoolMock, null, DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { new DelegatingContext(keyedObjectPoolMock, contextMock, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -63,14 +65,13 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testHelperMethods() throws Exception { // Wrap the Context once - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); final Context delegateContext = delegatingContext.getDelegateContext(); assertThat(delegateContext).isEqualTo(contextMock); - final Context innerDelegateContext = delegatingContext - .getInnermostDelegateContext(); + final Context innerDelegateContext = delegatingContext.getInnermostDelegateContext(); assertThat(innerDelegateContext).isEqualTo(contextMock); delegatingContext.assertOpen(); @@ -78,16 +79,13 @@ public class DelegatingContextTest extends AbstractPoolTestCase { // Wrap the wrapper KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); - final DelegatingContext delegatingContext2 = new DelegatingContext( - secondKeyedObjectPoolMock, delegatingContext, + final DelegatingContext delegatingContext2 = new DelegatingContext(secondKeyedObjectPoolMock, delegatingContext, DirContextType.READ_ONLY); - final Context delegateContext2 = delegatingContext2 - .getDelegateContext(); + final Context delegateContext2 = delegatingContext2.getDelegateContext(); assertThat(delegateContext2).isEqualTo(delegatingContext); - final Context innerDelegateContext2 = delegatingContext2 - .getInnermostDelegateContext(); + final Context innerDelegateContext2 = delegatingContext2.getInnermostDelegateContext(); assertThat(innerDelegateContext2).isEqualTo(contextMock); delegatingContext2.assertOpen(); @@ -95,57 +93,54 @@ public class DelegatingContextTest extends AbstractPoolTestCase { // Close the outer wrapper delegatingContext2.close(); - final Context delegateContext2closed = delegatingContext2 - .getDelegateContext(); + final Context delegateContext2closed = delegatingContext2.getDelegateContext(); assertThat(delegateContext2closed).isNull(); - final Context innerDelegateContext2closed = delegatingContext2 - .getInnermostDelegateContext(); + final Context innerDelegateContext2closed = delegatingContext2.getInnermostDelegateContext(); assertThat(innerDelegateContext2closed).isNull(); try { delegatingContext2.assertOpen(); fail("delegatingContext2.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } // Close the outer wrapper delegatingContext.close(); - final Context delegateContextclosed = delegatingContext - .getDelegateContext(); + final Context delegateContextclosed = delegatingContext.getDelegateContext(); assertThat(delegateContextclosed).isNull(); - final Context innerDelegateContextclosed = delegatingContext - .getInnermostDelegateContext(); + final Context innerDelegateContextclosed = delegatingContext.getInnermostDelegateContext(); assertThat(innerDelegateContextclosed).isNull(); try { delegatingContext.assertOpen(); fail("delegatingContext.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); - verify(secondKeyedObjectPoolMock) - .returnObject(DirContextType.READ_ONLY, contextMock); + verify(secondKeyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); } @Test public void testObjectMethods() throws Exception { // Wrap the Context once - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); assertThat(delegatingContext.toString()).isEqualTo(contextMock.toString()); delegatingContext.hashCode(); // Run it to make sure it doesn't fail assertThat(delegatingContext.equals(delegatingContext)).isTrue(); assertThat(delegatingContext.equals(new Object())).isFalse(); - final DelegatingContext delegatingContext2 = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext2 = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); assertThat(delegatingContext.equals(delegatingContext2)).isTrue(); assertThat(delegatingContext2.equals(delegatingContext)).isTrue(); assertThat(delegatingContext.equals(contextMock)).isTrue(); @@ -169,51 +164,57 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testUnsupportedMethods() throws Exception { - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); try { delegatingContext.addToEnvironment(null, null); fail("DelegatingContext.addToEnvironment Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.createSubcontext((Name) null); fail("DelegatingContext.createSubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.createSubcontext((String) null); fail("DelegatingContext.createSubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.destroySubcontext((Name) null); fail("DelegatingContext.destroySubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.destroySubcontext((String) null); fail("DelegatingContext.destroySubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingContext.removeFromEnvironment(null); fail("DelegatingContext.removeFromEnvironment Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } } @Test public void testAllMethodsOpened() throws Exception { - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); delegatingContext.bind((Name) null, null); delegatingContext.bind((String) null, null); @@ -241,142 +242,164 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testAllMethodsClosed() throws Exception { - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); delegatingContext.close(); try { delegatingContext.bind((Name) null, null); fail("DelegatingContext.bind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.bind((String) null, null); fail("DelegatingContext.bind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.composeName((Name) null, (Name) null); fail("DelegatingContext.composeName should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.composeName((String) null, (String) null); fail("DelegatingContext.composeName should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.getEnvironment(); fail("DelegatingContext.getEnvironment should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.getNameInNamespace(); fail("DelegatingContext.getNameInNamespace should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.getNameParser((Name) null); fail("DelegatingContext.getNameParser should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.getNameParser((String) null); fail("DelegatingContext.getNameParser should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.list((Name) null); fail("DelegatingContext.list should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.list((String) null); fail("DelegatingContext.list should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.listBindings((Name) null); fail("DelegatingContext.listBindings should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.listBindings((String) null); fail("DelegatingContext.listBindings should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.lookup((Name) null); fail("DelegatingContext.lookup should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.lookup((String) null); fail("DelegatingContext.lookup should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.lookupLink((Name) null); fail("DelegatingContext.lookupLink should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.lookupLink((String) null); fail("DelegatingContext.lookupLink should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.rebind((Name) null, null); fail("DelegatingContext.rebind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.rebind((String) null, null); fail("DelegatingContext.rebind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.rename((Name) null, (Name) null); fail("DelegatingContext.rename should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.rename((String) null, (String) null); fail("DelegatingContext.rename should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.unbind((Name) null); fail("DelegatingContext.unbind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingContext.unbind((String) null); fail("DelegatingContext.unbind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); @@ -384,8 +407,8 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testDoubleClose() throws Exception { - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); delegatingContext.close(); @@ -397,17 +420,19 @@ public class DelegatingContextTest extends AbstractPoolTestCase { @Test public void testPoolExceptionOnClose() throws Exception { - doThrow(new Exception("Fake Pool returnObject Exception")) - .when(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, contextMock); + doThrow(new Exception("Fake Pool returnObject Exception")).when(keyedObjectPoolMock) + .returnObject(DirContextType.READ_ONLY, contextMock); - final DelegatingContext delegatingContext = new DelegatingContext( - keyedObjectPoolMock, contextMock, DirContextType.READ_ONLY); + final DelegatingContext delegatingContext = new DelegatingContext(keyedObjectPoolMock, contextMock, + DirContextType.READ_ONLY); try { delegatingContext.close(); fail("DelegatingContext.close should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/DelegatingDirContextTest.java b/core/src/test/java/org/springframework/ldap/pool2/DelegatingDirContextTest.java index 9632f344..a1bffd62 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/DelegatingDirContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool2/DelegatingDirContextTest.java @@ -31,24 +31,26 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu */ public class DelegatingDirContextTest extends AbstractPoolTestCase { + @Test public void testConstructorAssertions() { try { - new DelegatingDirContext(keyedObjectPoolMock, null, - DirContextType.READ_ONLY); + new DelegatingDirContext(keyedObjectPoolMock, null, DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -57,19 +59,16 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { public void testHelperMethods() throws Exception { // Wrap the DirContext once - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); - final Context delegateContext = delegatingDirContext - .getDelegateContext(); + final Context delegateContext = delegatingDirContext.getDelegateContext(); assertThat(delegateContext).isEqualTo(dirContextMock); - final DirContext delegateDirContext = delegatingDirContext - .getDelegateDirContext(); + final DirContext delegateDirContext = delegatingDirContext.getDelegateDirContext(); assertThat(delegateDirContext).isEqualTo(dirContextMock); - final DirContext innerDelegateDirContext = delegatingDirContext - .getInnermostDelegateDirContext(); + final DirContext innerDelegateDirContext = delegatingDirContext.getInnermostDelegateDirContext(); assertThat(innerDelegateDirContext).isEqualTo(dirContextMock); delegatingDirContext.assertOpen(); @@ -77,16 +76,13 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { // Wrap the wrapper KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); - final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext( - secondKeyedObjectPoolMock, delegatingDirContext, - DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext(secondKeyedObjectPoolMock, + delegatingDirContext, DirContextType.READ_ONLY); - final DirContext delegateDirContext2 = delegatingDirContext2 - .getDelegateDirContext(); + final DirContext delegateDirContext2 = delegatingDirContext2.getDelegateDirContext(); assertThat(delegateDirContext2).isEqualTo(delegatingDirContext); - final DirContext innerDelegateDirContext2 = delegatingDirContext2 - .getInnermostDelegateDirContext(); + final DirContext innerDelegateDirContext2 = delegatingDirContext2.getInnermostDelegateDirContext(); assertThat(innerDelegateDirContext2).isEqualTo(dirContextMock); delegatingDirContext2.assertOpen(); @@ -94,49 +90,46 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { // Close the outer wrapper delegatingDirContext2.close(); - final DirContext delegateContext2closed = delegatingDirContext2 - .getDelegateDirContext(); + final DirContext delegateContext2closed = delegatingDirContext2.getDelegateDirContext(); assertThat(delegateContext2closed).isNull(); - final DirContext innerDelegateContext2closed = delegatingDirContext2 - .getInnermostDelegateDirContext(); + final DirContext innerDelegateContext2closed = delegatingDirContext2.getInnermostDelegateDirContext(); assertThat(innerDelegateContext2closed).isNull(); try { delegatingDirContext2.assertOpen(); fail("delegatingDirContext2.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } // Close the outer wrapper delegatingDirContext.close(); - final DirContext delegateDirContextClosed = delegatingDirContext - .getDelegateDirContext(); + final DirContext delegateDirContextClosed = delegatingDirContext.getDelegateDirContext(); assertThat(delegateDirContextClosed).isNull(); - final DirContext innerDelegateDirContextClosed = delegatingDirContext - .getInnermostDelegateDirContext(); + final DirContext innerDelegateDirContextClosed = delegatingDirContext.getInnermostDelegateDirContext(); assertThat(innerDelegateDirContextClosed).isNull(); try { delegatingDirContext.assertOpen(); fail("delegatingDirContext.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } - verify(secondKeyedObjectPoolMock) - .returnObject(DirContextType.READ_ONLY, dirContextMock); + verify(secondKeyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); } @Test public void testObjectMethods() throws Exception { // Wrap the DirContext once - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); assertThat(delegatingDirContext.toString()).isEqualTo(dirContextMock.toString()); delegatingDirContext.hashCode(); // Run it to make sure it doesn't // fail @@ -144,8 +137,8 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { assertThat(delegatingDirContext.equals(delegatingDirContext)).isTrue(); assertThat(delegatingDirContext.equals(new Object())).isFalse(); - final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext2 = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); assertThat(delegatingDirContext.equals(delegatingDirContext2)).isTrue(); assertThat(delegatingDirContext2.equals(delegatingDirContext)).isTrue(); assertThat(delegatingDirContext.equals(dirContextMock)).isTrue(); @@ -155,8 +148,8 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { assertThat(delegatingDirContext.toString()).isEqualTo("DirContext is closed"); assertThat(delegatingDirContext.hashCode()).isEqualTo(0); // Run it to make - // sure it doesn't - // fail + // sure it doesn't + // fail assertThat(delegatingDirContext.equals(delegatingDirContext)).isTrue(); assertThat(delegatingDirContext.equals(new Object())).isFalse(); @@ -170,51 +163,57 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { @Test public void testUnsupportedMethods() throws Exception { - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); try { delegatingDirContext.createSubcontext((Name) null, null); fail("DelegatingDirContext.createSubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.createSubcontext((String) null, null); fail("DelegatingDirContext.createSubcontext Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.getSchema((Name) null); fail("DelegatingDirContext.getSchema Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.getSchema((String) null); fail("DelegatingDirContext.getSchema Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.getSchemaClassDefinition((Name) null); fail("DelegatingDirContext.getSchemaClassDefinition Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingDirContext.getSchemaClassDefinition((String) null); fail("DelegatingDirContext.getSchemaClassDefinition Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } } @Test public void testAllMethodsOpened() throws Exception { - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); delegatingDirContext.bind((Name) null, null, null); delegatingDirContext.bind((String) null, null, null); @@ -240,130 +239,150 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { @Test public void testAllMethodsClosed() throws Exception { - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); delegatingDirContext.close(); try { delegatingDirContext.bind((Name) null, null, null); fail("DelegatingDirContext.bind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.bind((String) null, null, null); fail("DelegatingDirContext.bind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.getAttributes((Name) null, null); fail("DelegatingDirContext.getAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.getAttributes((Name) null); fail("DelegatingDirContext.getAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.getAttributes((String) null, null); fail("DelegatingDirContext.getAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.getAttributes((String) null); fail("DelegatingDirContext.getAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.modifyAttributes((Name) null, 0, null); fail("DelegatingDirContext.modifyAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.modifyAttributes((Name) null, null); fail("DelegatingDirContext.modifyAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.modifyAttributes((String) null, 0, null); fail("DelegatingDirContext.modifyAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.modifyAttributes((String) null, null); fail("DelegatingDirContext.modifyAttributes should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.rebind((Name) null, null, null); fail("DelegatingDirContext.rebind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.rebind((String) null, null, null); fail("DelegatingDirContext.rebind should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((Name) null, (Attributes) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((Name) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((Name) null, null, null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((Name) null, (String) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((String) null, (Attributes) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((String) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((String) null, null, null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingDirContext.search((String) null, (String) null, null); fail("DelegatingDirContext.search should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, dirContextMock); @@ -371,8 +390,8 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { @Test public void testDoubleClose() throws Exception { - final DelegatingDirContext delegatingDirContext = new DelegatingDirContext( - keyedObjectPoolMock, dirContextMock, DirContextType.READ_ONLY); + final DelegatingDirContext delegatingDirContext = new DelegatingDirContext(keyedObjectPoolMock, dirContextMock, + DirContextType.READ_ONLY); delegatingDirContext.close(); @@ -381,4 +400,5 @@ public class DelegatingDirContextTest extends AbstractPoolTestCase { verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, dirContextMock); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/DelegatingLdapContextTest.java b/core/src/test/java/org/springframework/ldap/pool2/DelegatingLdapContextTest.java index 9b2cceb6..43846a29 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/DelegatingLdapContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool2/DelegatingLdapContextTest.java @@ -29,25 +29,26 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** - * @author Eric Dalquist eric.dalquist@doit.wisc.edu + * @author Eric Dalquist + * eric.dalquist@doit.wisc.edu */ public class DelegatingLdapContextTest extends AbstractPoolTestCase { + @Test public void testConstructorAssertions() { try { - new DelegatingLdapContext(keyedObjectPoolMock, null, - DirContextType.READ_ONLY); + new DelegatingLdapContext(keyedObjectPoolMock, null, DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { - new DelegatingLdapContext(keyedObjectPoolMock, ldapContextMock, - null); + new DelegatingLdapContext(keyedObjectPoolMock, ldapContextMock, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -55,19 +56,16 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { @Test public void testHelperMethods() throws Exception { // Wrap the LdapContext once - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); - final DirContext delegateDirContext = delegatingLdapContext - .getDelegateDirContext(); + final DirContext delegateDirContext = delegatingLdapContext.getDelegateDirContext(); assertThat(delegateDirContext).isEqualTo(ldapContextMock); - final LdapContext delegateLdapContext = delegatingLdapContext - .getDelegateLdapContext(); + final LdapContext delegateLdapContext = delegatingLdapContext.getDelegateLdapContext(); assertThat(delegateLdapContext).isEqualTo(ldapContextMock); - final LdapContext innerDelegateLdapContext = delegatingLdapContext - .getInnermostDelegateLdapContext(); + final LdapContext innerDelegateLdapContext = delegatingLdapContext.getInnermostDelegateLdapContext(); assertThat(innerDelegateLdapContext).isEqualTo(ldapContextMock); delegatingLdapContext.assertOpen(); @@ -75,16 +73,13 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { // Wrap the wrapper KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); - final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext( - secondKeyedObjectPoolMock, delegatingLdapContext, - DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext(secondKeyedObjectPoolMock, + delegatingLdapContext, DirContextType.READ_ONLY); - final LdapContext delegateLdapContext2 = delegatingLdapContext2 - .getDelegateLdapContext(); + final LdapContext delegateLdapContext2 = delegatingLdapContext2.getDelegateLdapContext(); assertThat(delegateLdapContext2).isEqualTo(delegatingLdapContext); - final LdapContext innerDelegateLdapContext2 = delegatingLdapContext2 - .getInnermostDelegateLdapContext(); + final LdapContext innerDelegateLdapContext2 = delegatingLdapContext2.getInnermostDelegateLdapContext(); assertThat(innerDelegateLdapContext2).isEqualTo(ldapContextMock); delegatingLdapContext2.assertOpen(); @@ -92,57 +87,54 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { // Close the outer wrapper delegatingLdapContext2.close(); - final LdapContext delegateContext2closed = delegatingLdapContext2 - .getDelegateLdapContext(); + final LdapContext delegateContext2closed = delegatingLdapContext2.getDelegateLdapContext(); assertThat(delegateContext2closed).isNull(); - final LdapContext innerDelegateContext2closed = delegatingLdapContext2 - .getInnermostDelegateLdapContext(); + final LdapContext innerDelegateContext2closed = delegatingLdapContext2.getInnermostDelegateLdapContext(); assertThat(innerDelegateContext2closed).isNull(); try { delegatingLdapContext2.assertOpen(); fail("delegatingLdapContext2.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } // Close the outer wrapper delegatingLdapContext.close(); - final LdapContext delegateLdapContextClosed = delegatingLdapContext - .getDelegateLdapContext(); + final LdapContext delegateLdapContextClosed = delegatingLdapContext.getDelegateLdapContext(); assertThat(delegateLdapContextClosed).isNull(); - final LdapContext innerDelegateLdapContextClosed = delegatingLdapContext - .getInnermostDelegateLdapContext(); + final LdapContext innerDelegateLdapContextClosed = delegatingLdapContext.getInnermostDelegateLdapContext(); assertThat(innerDelegateLdapContextClosed).isNull(); try { delegatingLdapContext.assertOpen(); fail("delegatingLdapContext.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { + } + catch (NamingException ne) { // Expected } - verify(secondKeyedObjectPoolMock) - .returnObject(DirContextType.READ_ONLY, ldapContextMock); + verify(secondKeyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); } @Test public void testObjectMethods() throws Exception { // Wrap the LdapContext once - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); assertThat(delegatingLdapContext.toString()).isEqualTo(ldapContextMock.toString()); delegatingLdapContext.hashCode(); // Run it to make sure it doesn't fail assertThat(delegatingLdapContext.equals(delegatingLdapContext)).isTrue(); assertThat(delegatingLdapContext.equals(new Object())).isFalse(); - final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); assertThat(delegatingLdapContext.equals(delegatingLdapContext2)).isTrue(); assertThat(delegatingLdapContext2.equals(delegatingLdapContext)).isTrue(); assertThat(delegatingLdapContext.equals(ldapContextMock)).isTrue(); @@ -152,8 +144,8 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { assertThat(delegatingLdapContext.toString()).isEqualTo("LdapContext is closed"); assertThat(delegatingLdapContext.hashCode()).isEqualTo(0); // Run it to make - // sure it doesn't - // fail + // sure it doesn't + // fail assertThat(delegatingLdapContext.equals(delegatingLdapContext)).isTrue(); assertThat(delegatingLdapContext.equals(new Object())).isFalse(); @@ -167,25 +159,28 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { @Test public void testUnsupportedMethods() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); try { delegatingLdapContext.newInstance(null); fail("DelegatingLdapContext.newInstance Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingLdapContext.reconnect(null); fail("DelegatingLdapContext.reconnect Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } try { delegatingLdapContext.setRequestControls(null); fail("DelegatingLdapContext.setRequestControls Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { + } + catch (UnsupportedOperationException uoe) { // Expected } } @@ -193,8 +188,8 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { // nice @Test public void testAllMethodsOpened() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.extendedOperation(null); delegatingLdapContext.getConnectControls(); @@ -204,34 +199,38 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { @Test public void testAllMethodsClosed() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.close(); try { delegatingLdapContext.extendedOperation(null); fail("DelegatingLdapContext.extendedOperation should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingLdapContext.getConnectControls(); fail("DelegatingLdapContext.getConnectControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingLdapContext.getRequestControls(); fail("DelegatingLdapContext.getRequestControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } try { delegatingLdapContext.getResponseControls(); fail("DelegatingLdapContext.getResponseControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected + } + catch (NamingException ne) { + // Expected } verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); @@ -239,8 +238,8 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { @Test public void testDoubleClose() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.close(); @@ -249,4 +248,5 @@ public class DelegatingLdapContextTest extends AbstractPoolTestCase { verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, ldapContextMock); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/DummyEvictionPolicy.java b/core/src/test/java/org/springframework/ldap/pool2/DummyEvictionPolicy.java index d945c0ca..bec859b2 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/DummyEvictionPolicy.java +++ b/core/src/test/java/org/springframework/ldap/pool2/DummyEvictionPolicy.java @@ -23,15 +23,16 @@ import org.apache.commons.pool2.impl.EvictionPolicy; * A dummy {@link EvictionPolicy} implementation to test pool2 config. * * @author Anindya Chatterjee - * */ + */ public class DummyEvictionPolicy implements EvictionPolicy { /** * @see EvictionPolicy#evict(EvictionConfig, PooledObject, int) * - * */ + */ @Override public boolean evict(EvictionConfig config, PooledObject underTest, int idleCount) { return false; } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/MutableDelegatingLdapContextTest.java b/core/src/test/java/org/springframework/ldap/pool2/MutableDelegatingLdapContextTest.java index f7be8476..05c7bdd2 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/MutableDelegatingLdapContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool2/MutableDelegatingLdapContextTest.java @@ -21,17 +21,19 @@ import static org.mockito.Mockito.verify; /** * Unit tests for the MutableDelegatingLdapContext class. - * + * * @author Ulrik Sandberg */ public class MutableDelegatingLdapContextTest extends AbstractPoolTestCase { + @Test public void testSupportedMethodsAllowedToCall() throws Exception { - final MutableDelegatingLdapContext delegatingLdapContext = new MutableDelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + final MutableDelegatingLdapContext delegatingLdapContext = new MutableDelegatingLdapContext(keyedObjectPoolMock, + ldapContextMock, DirContextType.READ_ONLY); delegatingLdapContext.setRequestControls(null); verify(ldapContextMock).setRequestControls(null); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/factory/DirContextPooledObjectFactoryTest.java b/core/src/test/java/org/springframework/ldap/pool2/factory/DirContextPooledObjectFactoryTest.java index bcbbc7c9..2a3b248a 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/factory/DirContextPooledObjectFactoryTest.java +++ b/core/src/test/java/org/springframework/ldap/pool2/factory/DirContextPooledObjectFactoryTest.java @@ -59,7 +59,6 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { final ContextSource contextSource2 = objectFactory.getContextSource(); assertThat(contextSource2).isEqualTo(contextSourceMock); - try { objectFactory.setDirContextValidator(null); fail("DirContextPooledObjectFactory.setDirContextValidator should have thrown an IllegalArgumentException"); @@ -80,7 +79,8 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { try { objectFactory.makeObject(DirContextType.READ_ONLY); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -89,7 +89,8 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { try { objectFactory.makeObject(null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -131,7 +132,8 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { PooledObject pooledObject = new DefaultPooledObject(dirContextMock); objectFactory.validateObject(DirContextType.READ_ONLY, pooledObject); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -141,7 +143,8 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { PooledObject pooledObject = new DefaultPooledObject(dirContextMock); objectFactory.validateObject(null, pooledObject); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -149,14 +152,16 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { PooledObject pooledObject = new DefaultPooledObject(dirContextMock); objectFactory.validateObject(new Object(), pooledObject); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } try { objectFactory.validateObject(DirContextType.READ_ONLY, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -164,16 +169,15 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { PooledObject pooledObject = new DefaultPooledObject(new Object()); objectFactory.validateObject(DirContextType.READ_ONLY, pooledObject); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @Test public void testValidateObject() throws Exception { - when(dirContextValidatorMock - .validateDirContext(DirContextType.READ_ONLY, dirContextMock)) - .thenReturn(true); + when(dirContextValidatorMock.validateDirContext(DirContextType.READ_ONLY, dirContextMock)).thenReturn(true); final DirContextPooledObjectFactory objectFactory = new DirContextPooledObjectFactory(); objectFactory.setDirContextValidator(dirContextValidatorMock); @@ -182,7 +186,7 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { final boolean valid = objectFactory.validateObject(DirContextType.READ_ONLY, pooledObject); assertThat(valid).isTrue(); - //Check exception in validator + // Check exception in validator DirContextValidator secondDirContextValidatorMock = mock(DirContextValidator.class); when(secondDirContextValidatorMock.validateDirContext(DirContextType.READ_ONLY, dirContextMock)) @@ -200,7 +204,8 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { try { objectFactory.destroyObject(DirContextType.READ_ONLY, null); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } @@ -208,7 +213,8 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { PooledObject pooledObject = new DefaultPooledObject(new Object()); objectFactory.validateObject(DirContextType.READ_ONLY, pooledObject); fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { + } + catch (IllegalArgumentException expected) { assertThat(true).isTrue(); } } @@ -222,8 +228,7 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { DirContext throwingDirContextMock = mock(DirContext.class); - doThrow(new RuntimeException("Failed to close")) - .when(throwingDirContextMock).close(); + doThrow(new RuntimeException("Failed to close")).when(throwingDirContextMock).close(); pooledObject = new DefaultPooledObject(throwingDirContextMock); objectFactory.destroyObject(DirContextType.READ_ONLY, pooledObject); @@ -235,4 +240,5 @@ public class DirContextPooledObjectFactoryTest extends AbstractPoolTestCase { field.setAccessible(true); return (T) ReflectionUtils.getField(field, target); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/factory/MutablePooledContextSourceTest.java b/core/src/test/java/org/springframework/ldap/pool2/factory/MutablePooledContextSourceTest.java index 5cf68f7c..3fd63384 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/factory/MutablePooledContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/pool2/factory/MutablePooledContextSourceTest.java @@ -45,4 +45,5 @@ public class MutablePooledContextSourceTest extends AbstractPoolTestCase { assertThat(result.getClass()).isEqualTo(MutableDelegatingLdapContext.class); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/factory/PoolConfigTest.java b/core/src/test/java/org/springframework/ldap/pool2/factory/PoolConfigTest.java index d934a49c..6673dc64 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/factory/PoolConfigTest.java +++ b/core/src/test/java/org/springframework/ldap/pool2/factory/PoolConfigTest.java @@ -23,7 +23,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * @author Anindya Chatterjee - * */ + */ public class PoolConfigTest extends AbstractPoolTestCase { @Test @@ -110,4 +110,5 @@ public class PoolConfigTest extends AbstractPoolTestCase { final boolean lifo = poolConfig.isLifo(); assertThat(lifo).isEqualTo(true); } + } diff --git a/core/src/test/java/org/springframework/ldap/pool2/factory/PooledContextSourceTest.java b/core/src/test/java/org/springframework/ldap/pool2/factory/PooledContextSourceTest.java index d998fe7f..f92f18d3 100644 --- a/core/src/test/java/org/springframework/ldap/pool2/factory/PooledContextSourceTest.java +++ b/core/src/test/java/org/springframework/ldap/pool2/factory/PooledContextSourceTest.java @@ -70,7 +70,7 @@ public class PooledContextSourceTest extends AbstractPoolTestCase { PooledContextSource.setContextSource(contextSourceMock); final ContextSource contextSource2 = PooledContextSource.getContextSource(); assertThat(contextSource2).isEqualTo(contextSourceMock); - + try { PooledContextSource.setDirContextValidator(null); fail("PooledContextSource.setDirContextValidator should have thrown an IllegalArgumentException"); @@ -84,7 +84,7 @@ public class PooledContextSourceTest extends AbstractPoolTestCase { final int numActive = PooledContextSource.getNumActive(); assertThat(numActive).isEqualTo(0); - + final int numIdle = PooledContextSource.getNumIdle(); assertThat(numIdle).isEqualTo(0); } @@ -92,41 +92,49 @@ public class PooledContextSourceTest extends AbstractPoolTestCase { @Test public void testGetReadOnlyContextPool() throws Exception { DirContext secondDirContextMock = mock(DirContext.class); - + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock, secondDirContextMock); final PooledContextSource PooledContextSource = new PooledContextSource(null); PooledContextSource.setContextSource(contextSourceMock); - //Get a context + // Get a context final DirContext readOnlyContext1 = PooledContextSource.getReadOnlyContext(); - assertThat(readOnlyContext1).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext1).isEqualTo(dirContextMock); // Order reversed because + // the 'wrapper' has the + // needed equals logic assertThat(PooledContextSource.getNumActive()).isEqualTo(1); assertThat(PooledContextSource.getNumIdle()).isEqualTo(0); - - //Close the context + + // Close the context readOnlyContext1.close(); assertThat(PooledContextSource.getNumActive()).isEqualTo(0); assertThat(PooledContextSource.getNumIdle()).isEqualTo(1); - - //Get the context again + + // Get the context again final DirContext readOnlyContext2 = PooledContextSource.getReadOnlyContext(); - assertThat(readOnlyContext2).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext2).isEqualTo(dirContextMock); // Order reversed because + // the 'wrapper' has the + // needed equals logic assertThat(PooledContextSource.getNumActive()).isEqualTo(1); assertThat(PooledContextSource.getNumIdle()).isEqualTo(0); - - //Get a new context + + // Get a new context final DirContext readOnlyContext3 = PooledContextSource.getReadOnlyContext(); - assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); // Order reversed + // because the + // 'wrapper' has + // the needed + // equals logic assertThat(PooledContextSource.getNumActive()).isEqualTo(2); assertThat(PooledContextSource.getNumIdle()).isEqualTo(0); - //Close context + // Close context readOnlyContext2.close(); assertThat(PooledContextSource.getNumActive()).isEqualTo(1); assertThat(PooledContextSource.getNumIdle()).isEqualTo(1); - - //Close context + + // Close context readOnlyContext3.close(); assertThat(PooledContextSource.getNumActive()).isEqualTo(0); assertThat(PooledContextSource.getNumIdle()).isEqualTo(2); @@ -135,41 +143,49 @@ public class PooledContextSourceTest extends AbstractPoolTestCase { @Test public void testGetReadWriteContextPool() throws Exception { DirContext secondDirContextMock = mock(DirContext.class); - + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock, secondDirContextMock); final PooledContextSource PooledContextSource = new PooledContextSource(null); PooledContextSource.setContextSource(contextSourceMock); - //Get a context + // Get a context final DirContext readOnlyContext1 = PooledContextSource.getReadWriteContext(); - assertThat(readOnlyContext1).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext1).isEqualTo(dirContextMock); // Order reversed because + // the 'wrapper' has the + // needed equals logic assertThat(PooledContextSource.getNumActive()).isEqualTo(1); assertThat(PooledContextSource.getNumIdle()).isEqualTo(0); - - //Close the context + + // Close the context readOnlyContext1.close(); assertThat(PooledContextSource.getNumActive()).isEqualTo(0); assertThat(PooledContextSource.getNumIdle()).isEqualTo(1); - - //Get the context again + + // Get the context again final DirContext readOnlyContext2 = PooledContextSource.getReadWriteContext(); - assertThat(readOnlyContext2).isEqualTo(dirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext2).isEqualTo(dirContextMock); // Order reversed because + // the 'wrapper' has the + // needed equals logic assertThat(PooledContextSource.getNumActive()).isEqualTo(1); assertThat(PooledContextSource.getNumIdle()).isEqualTo(0); - - //Get a new context + + // Get a new context final DirContext readOnlyContext3 = PooledContextSource.getReadWriteContext(); - assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext3).isEqualTo(secondDirContextMock); // Order reversed + // because the + // 'wrapper' has + // the needed + // equals logic assertThat(PooledContextSource.getNumActive()).isEqualTo(2); assertThat(PooledContextSource.getNumIdle()).isEqualTo(0); - //Close context + // Close context readOnlyContext2.close(); assertThat(PooledContextSource.getNumActive()).isEqualTo(1); assertThat(PooledContextSource.getNumIdle()).isEqualTo(1); - - //Close context + + // Close context readOnlyContext3.close(); assertThat(PooledContextSource.getNumActive()).isEqualTo(0); assertThat(PooledContextSource.getNumIdle()).isEqualTo(2); @@ -177,8 +193,7 @@ public class PooledContextSourceTest extends AbstractPoolTestCase { @Test public void testGetContextException() throws Exception { - when(contextSourceMock.getReadWriteContext()) - .thenThrow(new RuntimeException("Problem getting context")); + when(contextSourceMock.getReadWriteContext()).thenThrow(new RuntimeException("Problem getting context")); final PooledContextSource PooledContextSource = new PooledContextSource(null); PooledContextSource.setContextSource(contextSourceMock); @@ -201,37 +216,48 @@ public class PooledContextSourceTest extends AbstractPoolTestCase { final PooledContextSource pooledContextSource = new PooledContextSource(null); pooledContextSource.setContextSource(contextSourceMock); - //Get a context + // Get a context final DirContext readOnlyContext1 = pooledContextSource.getReadOnlyContext(); - assertThat(readOnlyContext1).isEqualTo(ldapContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext1).isEqualTo(ldapContextMock); // Order reversed because + // the 'wrapper' has + // the needed equals + // logic assertThat(pooledContextSource.getNumActive()).isEqualTo(1); assertThat(pooledContextSource.getNumIdle()).isEqualTo(0); - - //Close the context + + // Close the context readOnlyContext1.close(); assertThat(pooledContextSource.getNumActive()).isEqualTo(0); assertThat(pooledContextSource.getNumIdle()).isEqualTo(1); - - //Get the context again + + // Get the context again final DirContext readOnlyContext2 = pooledContextSource.getReadOnlyContext(); - assertThat(readOnlyContext2).isEqualTo(ldapContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext2).isEqualTo(ldapContextMock); // Order reversed because + // the 'wrapper' has + // the needed equals + // logic assertThat(pooledContextSource.getNumActive()).isEqualTo(1); assertThat(pooledContextSource.getNumIdle()).isEqualTo(0); - - //Get a new context + + // Get a new context final DirContext readOnlyContext3 = pooledContextSource.getReadOnlyContext(); - assertThat(readOnlyContext3).isEqualTo(secondLdapContextMock); //Order reversed because the 'wrapper' has the needed equals logic + assertThat(readOnlyContext3).isEqualTo(secondLdapContextMock); // Order reversed + // because the + // 'wrapper' has + // the needed + // equals logic assertThat(pooledContextSource.getNumActive()).isEqualTo(2); assertThat(pooledContextSource.getNumIdle()).isEqualTo(0); - //Close context + // Close context readOnlyContext2.close(); assertThat(pooledContextSource.getNumActive()).isEqualTo(1); assertThat(pooledContextSource.getNumIdle()).isEqualTo(1); - - //Close context + + // Close context readOnlyContext3.close(); assertThat(pooledContextSource.getNumActive()).isEqualTo(0); assertThat(pooledContextSource.getNumIdle()).isEqualTo(2); } + } diff --git a/core/src/test/java/org/springframework/ldap/query/LdapQueryBuilderTest.java b/core/src/test/java/org/springframework/ldap/query/LdapQueryBuilderTest.java index 19421db2..45b9a596 100644 --- a/core/src/test/java/org/springframework/ldap/query/LdapQueryBuilderTest.java +++ b/core/src/test/java/org/springframework/ldap/query/LdapQueryBuilderTest.java @@ -43,7 +43,6 @@ public class LdapQueryBuilderTest { assertThat(result.filter().encode()).isEqualTo("(cn=J*hn Doe)"); } - @Test public void buildWhitespaceWildcards() { LdapQuery result = query().where("cn").whitespaceWildcardsLike("John Doe"); @@ -88,12 +87,8 @@ public class LdapQueryBuilderTest { @Test public void testBuildSimpleAnd() { - LdapQuery query = query() - .base("dc=261consulting, dc=com") - .searchScope(SearchScope.ONELEVEL) - .timeLimit(200) - .countLimit(221) - .where("objectclass").is("person").and("cn").is("John Doe"); + LdapQuery query = query().base("dc=261consulting, dc=com").searchScope(SearchScope.ONELEVEL).timeLimit(200) + .countLimit(221).where("objectclass").is("person").and("cn").is("John Doe"); assertThat(query.base()).isEqualTo(LdapUtils.newLdapName("dc=261consulting, dc=com")); assertThat(query.searchScope()).isEqualTo(SearchScope.ONELEVEL); @@ -111,8 +106,7 @@ public class LdapQueryBuilderTest { @Test public void buildAndOrPrecedence() { - LdapQuery result = query().where("objectclass").is("person") - .and("cn").is("John Doe") + LdapQuery result = query().where("objectclass").is("person").and("cn").is("John Doe") .or(query().where("sn").is("Doe")); assertThat(result.filter().encode()).isEqualTo("(|(&(objectclass=person)(cn=John Doe))(sn=Doe))"); @@ -126,11 +120,8 @@ public class LdapQueryBuilderTest { @Test public void buildNestedAnd() { - LdapQuery result = query() - .where("objectclass").is("person") - .and(query() - .where("sn").is("Doe") - .or("sn").like("Die")); + LdapQuery result = query().where("objectclass").is("person") + .and(query().where("sn").is("Doe").or("sn").like("Die")); assertThat(result.filter().encode()).isEqualTo("(&(objectclass=person)(|(sn=Doe)(sn=Die)))"); } @@ -157,4 +148,5 @@ public class LdapQueryBuilderTest { public void verifyThatOperatorChangeIsIllegal() { query().where("cn").is("John Doe").and("sn").is("Doe").or("objectclass").is("person"); } + } diff --git a/core/src/test/java/org/springframework/ldap/support/LdapEncoderTest.java b/core/src/test/java/org/springframework/ldap/support/LdapEncoderTest.java index fc3b6727..f1f8a2b5 100644 --- a/core/src/test/java/org/springframework/ldap/support/LdapEncoderTest.java +++ b/core/src/test/java/org/springframework/ldap/support/LdapEncoderTest.java @@ -23,10 +23,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Unit test for the LdapEncode class. - * + * * @author Adam Skogman */ -public class LdapEncoderTest { +public class LdapEncoderTest { @Test public void testFilterEncode() { @@ -46,8 +46,7 @@ public class LdapEncoderTest { @Test public void testNameDecode() { - String res = LdapEncoder - .nameDecode("\\# foo \\,\\+\\\"\\\\\\<\\>\\;\\ "); + String res = LdapEncoder.nameDecode("\\# foo \\,\\+\\\"\\\\\\<\\>\\;\\ "); assertThat(res).isEqualTo("# foo ,+\"\\<>; "); } @@ -88,4 +87,5 @@ public class LdapEncoderTest { assertThat(actual).isEqualTo(expected); } + } diff --git a/core/src/test/java/org/springframework/ldap/support/LdapNameBuilderTest.java b/core/src/test/java/org/springframework/ldap/support/LdapNameBuilderTest.java index ad78f123..4b9505f8 100644 --- a/core/src/test/java/org/springframework/ldap/support/LdapNameBuilderTest.java +++ b/core/src/test/java/org/springframework/ldap/support/LdapNameBuilderTest.java @@ -23,7 +23,8 @@ public class LdapNameBuilderTest { @Test public void testAddComponentToBaseName() { - LdapNameBuilder tested = LdapNameBuilder.newInstance(LdapUtils.newLdapName("dc=com")).add("dc", "261consulting"); + LdapNameBuilder tested = LdapNameBuilder.newInstance(LdapUtils.newLdapName("dc=com")).add("dc", + "261consulting"); assertThat(tested.build().toString()).isEqualTo("dc=261consulting,dc=com"); } @@ -35,7 +36,8 @@ public class LdapNameBuilderTest { @Test public void testAddNameToBaseString() { - LdapNameBuilder tested = LdapNameBuilder.newInstance("dc=261consulting,dc=com").add(LdapUtils.newLdapName("ou=people")); + LdapNameBuilder tested = LdapNameBuilder.newInstance("dc=261consulting,dc=com") + .add(LdapUtils.newLdapName("ou=people")); assertThat(tested.build().toString()).isEqualTo("ou=people,dc=261consulting,dc=com"); } diff --git a/core/src/test/java/org/springframework/ldap/support/LdapUtilsTest.java b/core/src/test/java/org/springframework/ldap/support/LdapUtilsTest.java index 53f386dc..802a3a7d 100644 --- a/core/src/test/java/org/springframework/ldap/support/LdapUtilsTest.java +++ b/core/src/test/java/org/springframework/ldap/support/LdapUtilsTest.java @@ -36,6 +36,7 @@ import static org.mockito.Mockito.verify; public class LdapUtilsTest { private static final String EXPECTED_DN_STRING = "cn=john.doe, OU=Users,OU=SE,OU=G,OU=I,OU=M"; + private static final String EXPECTED_MULTIVALUE_DN_STRING = "cn=john.doe, OU=Users,OU=SE,OU=G+O=GR,OU=I,OU=M"; private AttributeValueCallbackHandler handlerMock; @@ -72,7 +73,8 @@ public class LdapUtilsTest { try { LdapUtils.collectAttributeValues(attributes, expectedAttributeName, list); fail("NoSuchAttributeException expected"); - } catch (NoSuchAttributeException expected) { + } + catch (NoSuchAttributeException expected) { assertThat(true).isTrue(); } } @@ -105,29 +107,24 @@ public class LdapUtilsTest { */ @Test public void testConvertBinarySidToString() throws Exception { - byte[] sid = {(byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, - (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0xe9, (byte) 0x67, (byte) 0xbb, (byte) 0x98, - (byte) 0xd6, (byte) 0xb7, (byte) 0xd7, (byte) 0xbf, - (byte) 0x82, (byte) 0x05, (byte) 0x1e, (byte) 0x6c, - (byte) 0x28, (byte) 0x06, (byte) 0x00, (byte) 0x00}; + byte[] sid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x05, (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xe9, (byte) 0x67, (byte) 0xbb, + (byte) 0x98, (byte) 0xd6, (byte) 0xb7, (byte) 0xd7, (byte) 0xbf, (byte) 0x82, (byte) 0x05, (byte) 0x1e, + (byte) 0x6c, (byte) 0x28, (byte) 0x06, (byte) 0x00, (byte) 0x00 }; String result = LdapUtils.convertBinarySidToString(sid); assertThat(result).isEqualTo("S-1-5-21-2562418665-3218585558-1813906818-1576"); } /** - * Example SID from "https://blogs.msdn.com/oldnewthing/archive/2004/03/15/89753.aspx". + * Example SID from + * "https://blogs.msdn.com/oldnewthing/archive/2004/03/15/89753.aspx". */ @Test public void testConvertAnotherBinarySidToString() throws Exception { - byte[] sid = {(byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, - (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0xa0, (byte) 0x65, (byte) 0xcf, (byte) 0x7e, - (byte) 0x78, (byte) 0x4b, (byte) 0x9b, (byte) 0x5f, - (byte) 0xe7, (byte) 0x7c, (byte) 0x87, (byte) 0x70, - (byte) 0x09, (byte) 0x1c, (byte) 0x01, (byte) 0x00}; + byte[] sid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x05, (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xa0, (byte) 0x65, (byte) 0xcf, + (byte) 0x7e, (byte) 0x78, (byte) 0x4b, (byte) 0x9b, (byte) 0x5f, (byte) 0xe7, (byte) 0x7c, (byte) 0x87, + (byte) 0x70, (byte) 0x09, (byte) 0x1c, (byte) 0x01, (byte) 0x00 }; String result = LdapUtils.convertBinarySidToString(sid); assertThat(result).isEqualTo("S-1-5-21-2127521184-1604012920-1887927527-72713"); } @@ -137,13 +134,10 @@ public class LdapUtilsTest { */ @Test public void testConvertHandCraftedBinarySidToString() throws Exception { - byte[] sid = {(byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, - (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00}; + byte[] sid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x05, (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; String result = LdapUtils.convertBinarySidToString(sid); assertThat(result).isEqualTo("S-1-5-21-1-2-3-4"); } @@ -152,44 +146,44 @@ public class LdapUtilsTest { public void testSmallNumberToBytesBigEndian() throws Exception { byte[] result = LdapUtils.numberToBytes("5", 6, true); assertThat(result.length).isEqualTo(6); - assertThat(result[0]).isEqualTo((byte)0); - assertThat(result[1]).isEqualTo((byte)0); - assertThat(result[2]).isEqualTo((byte)0); - assertThat(result[3]).isEqualTo((byte)0); - assertThat(result[4]).isEqualTo((byte)0); - assertThat(result[5]).isEqualTo((byte)5); + assertThat(result[0]).isEqualTo((byte) 0); + assertThat(result[1]).isEqualTo((byte) 0); + assertThat(result[2]).isEqualTo((byte) 0); + assertThat(result[3]).isEqualTo((byte) 0); + assertThat(result[4]).isEqualTo((byte) 0); + assertThat(result[5]).isEqualTo((byte) 5); } @Test public void testLargeNumberToBytesBigEndian() throws Exception { byte[] result = LdapUtils.numberToBytes("1183728", 6, true); assertThat(result.length).isEqualTo(6); - assertThat(result[0]).isEqualTo((byte)0); - assertThat(result[1]).isEqualTo((byte)0); - assertThat(result[2]).isEqualTo((byte)0); - assertThat(result[3]).isEqualTo((byte)18); - assertThat(result[4]).isEqualTo((byte)15); - assertThat(result[5]).isEqualTo((byte)-16); + assertThat(result[0]).isEqualTo((byte) 0); + assertThat(result[1]).isEqualTo((byte) 0); + assertThat(result[2]).isEqualTo((byte) 0); + assertThat(result[3]).isEqualTo((byte) 18); + assertThat(result[4]).isEqualTo((byte) 15); + assertThat(result[5]).isEqualTo((byte) -16); } @Test public void testSmallNumberToBytesLittleEndian() throws Exception { byte[] result = LdapUtils.numberToBytes("21", 4, false); assertThat(result.length).isEqualTo(4); - assertThat(result[0]).isEqualTo((byte)21); - assertThat(result[1]).isEqualTo((byte)0); - assertThat(result[2]).isEqualTo((byte)0); - assertThat(result[3]).isEqualTo((byte)0); + assertThat(result[0]).isEqualTo((byte) 21); + assertThat(result[1]).isEqualTo((byte) 0); + assertThat(result[2]).isEqualTo((byte) 0); + assertThat(result[3]).isEqualTo((byte) 0); } @Test public void testLargeNumberToBytesLittleEndian() throws Exception { byte[] result = LdapUtils.numberToBytes("2127521184", 4, false); assertThat(result.length).isEqualTo(4); - assertThat(result[0]).isEqualTo((byte)-96); - assertThat(result[1]).isEqualTo((byte)101); - assertThat(result[2]).isEqualTo((byte)-49); - assertThat(result[3]).isEqualTo((byte)126); + assertThat(result[0]).isEqualTo((byte) -96); + assertThat(result[1]).isEqualTo((byte) 101); + assertThat(result[2]).isEqualTo((byte) -49); + assertThat(result[3]).isEqualTo((byte) 126); } /** @@ -197,13 +191,10 @@ public class LdapUtilsTest { */ @Test public void testConvertHandCraftedStringSidToBinary() throws Exception { - byte[] expectedSid = {(byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, - (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x01, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x03, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00}; + byte[] expectedSid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x05, (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x02, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x00, + (byte) 0x00, (byte) 0x00, (byte) 0x04, (byte) 0x00, (byte) 0x00, (byte) 0x00 }; byte[] result = LdapUtils.convertStringSidToBinary("S-1-5-21-1-2-3-4"); assertThat(ArrayUtils.isSameLength(expectedSid, result)).isTrue(); for (int i = 0; i < result.length; i++) { @@ -216,13 +207,10 @@ public class LdapUtilsTest { */ @Test public void testConvertStringSidToBinary() throws Exception { - byte[] expectedSid = {(byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, - (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x05, - (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, - (byte) 0xe9, (byte) 0x67, (byte) 0xbb, (byte) 0x98, - (byte) 0xd6, (byte) 0xb7, (byte) 0xd7, (byte) 0xbf, - (byte) 0x82, (byte) 0x05, (byte) 0x1e, (byte) 0x6c, - (byte) 0x28, (byte) 0x06, (byte) 0x00, (byte) 0x00}; + byte[] expectedSid = { (byte) 0x01, (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, + (byte) 0x00, (byte) 0x05, (byte) 0x15, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0xe9, (byte) 0x67, + (byte) 0xbb, (byte) 0x98, (byte) 0xd6, (byte) 0xb7, (byte) 0xd7, (byte) 0xbf, (byte) 0x82, (byte) 0x05, + (byte) 0x1e, (byte) 0x6c, (byte) 0x28, (byte) 0x06, (byte) 0x00, (byte) 0x00 }; byte[] result = LdapUtils.convertStringSidToBinary("S-1-5-21-2562418665-3218585558-1813906818-1576"); assertThat(ArrayUtils.isSameLength(expectedSid, result)).as("incorrect length of array").isTrue(); for (int i = 0; i < result.length; i++) { @@ -311,363 +299,268 @@ public class LdapUtilsTest { public void testConvertLdapExceptions() { // Test the Exceptions in the javax.naming package - assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.AttributeInUseException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.directory.AttributeInUseException()).getClass()) .isEqualTo(org.springframework.ldap.AttributeInUseException.class); assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.AttributeModificationException()) - .getClass()).isEqualTo( - org.springframework.ldap.AttributeModificationException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.CannotProceedException()) - .getClass()).isEqualTo( - org.springframework.ldap.CannotProceedException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.CommunicationException()) - .getClass()).isEqualTo( - org.springframework.ldap.CommunicationException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.ConfigurationException()) - .getClass()).isEqualTo( - org.springframework.ldap.ConfigurationException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.ContextNotEmptyException()).getClass()) + LdapUtils.convertLdapException(new javax.naming.directory.AttributeModificationException()).getClass()) + .isEqualTo(org.springframework.ldap.AttributeModificationException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.CannotProceedException()).getClass()) + .isEqualTo(org.springframework.ldap.CannotProceedException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.CommunicationException()).getClass()) + .isEqualTo(org.springframework.ldap.CommunicationException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.ConfigurationException()).getClass()) + .isEqualTo(org.springframework.ldap.ConfigurationException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.ContextNotEmptyException()).getClass()) .isEqualTo(org.springframework.ldap.ContextNotEmptyException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.InsufficientResourcesException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.InsufficientResourcesException()).getClass()) .isEqualTo(org.springframework.ldap.InsufficientResourcesException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.InterruptedNamingException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.InterruptedNamingException()).getClass()) .isEqualTo(org.springframework.ldap.InterruptedNamingException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.directory.InvalidAttributeIdentifierException()) + .getClass()).isEqualTo(org.springframework.ldap.InvalidAttributeIdentifierException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.directory.InvalidAttributesException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidAttributesException.class); assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.InvalidAttributeIdentifierException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidAttributeIdentifierException.class); + LdapUtils.convertLdapException(new javax.naming.directory.InvalidAttributeValueException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidAttributeValueException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.InvalidNameException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidNameException.class); assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.InvalidAttributesException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidAttributesException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.InvalidAttributeValueException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidAttributeValueException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.InvalidNameException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidNameException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.InvalidSearchControlsException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidSearchControlsException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.InvalidSearchFilterException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidSearchFilterException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.SizeLimitExceededException()).getClass()) + LdapUtils.convertLdapException(new javax.naming.directory.InvalidSearchControlsException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidSearchControlsException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.directory.InvalidSearchFilterException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidSearchFilterException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.SizeLimitExceededException()).getClass()) .isEqualTo(org.springframework.ldap.SizeLimitExceededException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.TimeLimitExceededException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.TimeLimitExceededException()).getClass()) .isEqualTo(org.springframework.ldap.TimeLimitExceededException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.LimitExceededException()) - .getClass()).isEqualTo( - org.springframework.ldap.LimitExceededException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.LinkLoopException()) - .getClass()).isEqualTo( - org.springframework.ldap.LinkLoopException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.MalformedLinkException()) - .getClass()).isEqualTo( - org.springframework.ldap.MalformedLinkException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.LinkException()) - .getClass()).isEqualTo( - org.springframework.ldap.LinkException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.NameAlreadyBoundException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.LimitExceededException()).getClass()) + .isEqualTo(org.springframework.ldap.LimitExceededException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.LinkLoopException()).getClass()) + .isEqualTo(org.springframework.ldap.LinkLoopException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.MalformedLinkException()).getClass()) + .isEqualTo(org.springframework.ldap.MalformedLinkException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.LinkException()).getClass()) + .isEqualTo(org.springframework.ldap.LinkException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.NameAlreadyBoundException()).getClass()) .isEqualTo(org.springframework.ldap.NameAlreadyBoundException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.NameNotFoundException()) - .getClass()).isEqualTo( - org.springframework.ldap.NameNotFoundException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.NoPermissionException()) - .getClass()).isEqualTo( - org.springframework.ldap.NoPermissionException.class); - assertThat( - LdapUtils - .convertLdapException(new javax.naming.AuthenticationException()) - .getClass()).isEqualTo( - org.springframework.ldap.AuthenticationException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.AuthenticationNotSupportedException()) - .getClass()).isEqualTo( - org.springframework.ldap.AuthenticationNotSupportedException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.NoInitialContextException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.NameNotFoundException()).getClass()) + .isEqualTo(org.springframework.ldap.NameNotFoundException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.NoPermissionException()).getClass()) + .isEqualTo(org.springframework.ldap.NoPermissionException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.AuthenticationException()).getClass()) + .isEqualTo(org.springframework.ldap.AuthenticationException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.AuthenticationNotSupportedException()).getClass()) + .isEqualTo(org.springframework.ldap.AuthenticationNotSupportedException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.NoInitialContextException()).getClass()) .isEqualTo(org.springframework.ldap.NoInitialContextException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.NoSuchAttributeException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.directory.NoSuchAttributeException()).getClass()) .isEqualTo(org.springframework.ldap.NoSuchAttributeException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.NotContextException()) - .getClass()).isEqualTo( - org.springframework.ldap.NotContextException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.OperationNotSupportedException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.NotContextException()).getClass()) + .isEqualTo(org.springframework.ldap.NotContextException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.OperationNotSupportedException()).getClass()) .isEqualTo(org.springframework.ldap.OperationNotSupportedException.class); - assertThat( - LdapUtils.convertLdapException(new javax.naming.PartialResultException()) - .getClass()).isEqualTo( - org.springframework.ldap.PartialResultException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.directory.SchemaViolationException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.PartialResultException()).getClass()) + .isEqualTo(org.springframework.ldap.PartialResultException.class); + assertThat(LdapUtils.convertLdapException(new javax.naming.directory.SchemaViolationException()).getClass()) .isEqualTo(org.springframework.ldap.SchemaViolationException.class); - assertThat( - LdapUtils.convertLdapException( - new javax.naming.ServiceUnavailableException()).getClass()) + assertThat(LdapUtils.convertLdapException(new javax.naming.ServiceUnavailableException()).getClass()) .isEqualTo(org.springframework.ldap.ServiceUnavailableException.class); // Test Exceptions that extend javax.naming packaage extensions - assertThat( - LdapUtils.convertLdapException(new MockAttributeInUseException()) - .getClass()).isEqualTo( - org.springframework.ldap.AttributeInUseException.class); - assertThat( - LdapUtils.convertLdapException(new MockAttributeModificationException()) - .getClass()).isEqualTo( - org.springframework.ldap.AttributeModificationException.class); - assertThat( - LdapUtils.convertLdapException(new MockCannotProceedException()) - .getClass()).isEqualTo( - org.springframework.ldap.CannotProceedException.class); - assertThat( - LdapUtils.convertLdapException(new MockCommunicationException()) - .getClass()).isEqualTo( - org.springframework.ldap.CommunicationException.class); - assertThat( - LdapUtils.convertLdapException(new MockConfigurationException()) - .getClass()).isEqualTo( - org.springframework.ldap.ConfigurationException.class); - assertThat( - LdapUtils.convertLdapException(new MockContextNotEmptyException()) - .getClass()).isEqualTo( - org.springframework.ldap.ContextNotEmptyException.class); - assertThat( - LdapUtils.convertLdapException(new MockInsufficientResourcesException()) - .getClass()).isEqualTo( - org.springframework.ldap.InsufficientResourcesException.class); - assertThat( - LdapUtils.convertLdapException(new MockInterruptedNamingException()) - .getClass()).isEqualTo( - org.springframework.ldap.InterruptedNamingException.class); - assertThat( - LdapUtils.convertLdapException( - new MockInvalidAttributeIdentifierException()).getClass()) - .isEqualTo( - org.springframework.ldap.InvalidAttributeIdentifierException.class); - assertThat( - LdapUtils.convertLdapException(new MockInvalidAttributesException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidAttributesException.class); - assertThat( - LdapUtils.convertLdapException(new MockInvalidAttributeValueException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidAttributeValueException.class); - assertThat( - LdapUtils.convertLdapException(new MockInvalidNameException()).getClass()) + assertThat(LdapUtils.convertLdapException(new MockAttributeInUseException()).getClass()) + .isEqualTo(org.springframework.ldap.AttributeInUseException.class); + assertThat(LdapUtils.convertLdapException(new MockAttributeModificationException()).getClass()) + .isEqualTo(org.springframework.ldap.AttributeModificationException.class); + assertThat(LdapUtils.convertLdapException(new MockCannotProceedException()).getClass()) + .isEqualTo(org.springframework.ldap.CannotProceedException.class); + assertThat(LdapUtils.convertLdapException(new MockCommunicationException()).getClass()) + .isEqualTo(org.springframework.ldap.CommunicationException.class); + assertThat(LdapUtils.convertLdapException(new MockConfigurationException()).getClass()) + .isEqualTo(org.springframework.ldap.ConfigurationException.class); + assertThat(LdapUtils.convertLdapException(new MockContextNotEmptyException()).getClass()) + .isEqualTo(org.springframework.ldap.ContextNotEmptyException.class); + assertThat(LdapUtils.convertLdapException(new MockInsufficientResourcesException()).getClass()) + .isEqualTo(org.springframework.ldap.InsufficientResourcesException.class); + assertThat(LdapUtils.convertLdapException(new MockInterruptedNamingException()).getClass()) + .isEqualTo(org.springframework.ldap.InterruptedNamingException.class); + assertThat(LdapUtils.convertLdapException(new MockInvalidAttributeIdentifierException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidAttributeIdentifierException.class); + assertThat(LdapUtils.convertLdapException(new MockInvalidAttributesException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidAttributesException.class); + assertThat(LdapUtils.convertLdapException(new MockInvalidAttributeValueException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidAttributeValueException.class); + assertThat(LdapUtils.convertLdapException(new MockInvalidNameException()).getClass()) .isEqualTo(org.springframework.ldap.InvalidNameException.class); - assertThat( - LdapUtils.convertLdapException(new MockInvalidSearchControlsException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidSearchControlsException.class); - assertThat( - LdapUtils.convertLdapException(new MockInvalidSearchFilterException()) - .getClass()).isEqualTo( - org.springframework.ldap.InvalidSearchFilterException.class); - assertThat( - LdapUtils.convertLdapException(new MockSizeLimitExceededException()) - .getClass()).isEqualTo( - org.springframework.ldap.SizeLimitExceededException.class); - assertThat( - LdapUtils.convertLdapException(new MockTimeLimitExceededException()) - .getClass()).isEqualTo( - org.springframework.ldap.TimeLimitExceededException.class); - assertThat( - LdapUtils.convertLdapException(new MockLimitExceededException()) - .getClass()).isEqualTo( - org.springframework.ldap.LimitExceededException.class); + assertThat(LdapUtils.convertLdapException(new MockInvalidSearchControlsException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidSearchControlsException.class); + assertThat(LdapUtils.convertLdapException(new MockInvalidSearchFilterException()).getClass()) + .isEqualTo(org.springframework.ldap.InvalidSearchFilterException.class); + assertThat(LdapUtils.convertLdapException(new MockSizeLimitExceededException()).getClass()) + .isEqualTo(org.springframework.ldap.SizeLimitExceededException.class); + assertThat(LdapUtils.convertLdapException(new MockTimeLimitExceededException()).getClass()) + .isEqualTo(org.springframework.ldap.TimeLimitExceededException.class); + assertThat(LdapUtils.convertLdapException(new MockLimitExceededException()).getClass()) + .isEqualTo(org.springframework.ldap.LimitExceededException.class); assertThat(LdapUtils.convertLdapException(new MockLinkLoopException()).getClass()) .isEqualTo(org.springframework.ldap.LinkLoopException.class); - assertThat( - LdapUtils.convertLdapException(new MockMalformedLinkException()) - .getClass()).isEqualTo( - org.springframework.ldap.MalformedLinkException.class); + assertThat(LdapUtils.convertLdapException(new MockMalformedLinkException()).getClass()) + .isEqualTo(org.springframework.ldap.MalformedLinkException.class); assertThat(LdapUtils.convertLdapException(new MockLinkException()).getClass()) .isEqualTo(org.springframework.ldap.LinkException.class); - assertThat( - LdapUtils.convertLdapException(new MockNameAlreadyBoundException()) - .getClass()).isEqualTo( - org.springframework.ldap.NameAlreadyBoundException.class); - assertThat( - LdapUtils.convertLdapException(new MockNameNotFoundException()) - .getClass()).isEqualTo( - org.springframework.ldap.NameNotFoundException.class); - assertThat( - LdapUtils.convertLdapException(new MockNoPermissionException()) - .getClass()).isEqualTo( - org.springframework.ldap.NoPermissionException.class); - assertThat( - LdapUtils.convertLdapException(new MockAuthenticationException()) - .getClass()).isEqualTo( - org.springframework.ldap.AuthenticationException.class); - assertThat( - LdapUtils.convertLdapException( - new MockAuthenticationNotSupportedException()).getClass()) - .isEqualTo( - org.springframework.ldap.AuthenticationNotSupportedException.class); - assertThat( - LdapUtils.convertLdapException(new MockNoInitialContextException()) - .getClass()).isEqualTo( - org.springframework.ldap.NoInitialContextException.class); - assertThat( - LdapUtils.convertLdapException(new MockNoSuchAttributeException()) - .getClass()).isEqualTo( - org.springframework.ldap.NoSuchAttributeException.class); - assertThat( - LdapUtils.convertLdapException(new MockNotContextException()).getClass()) + assertThat(LdapUtils.convertLdapException(new MockNameAlreadyBoundException()).getClass()) + .isEqualTo(org.springframework.ldap.NameAlreadyBoundException.class); + assertThat(LdapUtils.convertLdapException(new MockNameNotFoundException()).getClass()) + .isEqualTo(org.springframework.ldap.NameNotFoundException.class); + assertThat(LdapUtils.convertLdapException(new MockNoPermissionException()).getClass()) + .isEqualTo(org.springframework.ldap.NoPermissionException.class); + assertThat(LdapUtils.convertLdapException(new MockAuthenticationException()).getClass()) + .isEqualTo(org.springframework.ldap.AuthenticationException.class); + assertThat(LdapUtils.convertLdapException(new MockAuthenticationNotSupportedException()).getClass()) + .isEqualTo(org.springframework.ldap.AuthenticationNotSupportedException.class); + assertThat(LdapUtils.convertLdapException(new MockNoInitialContextException()).getClass()) + .isEqualTo(org.springframework.ldap.NoInitialContextException.class); + assertThat(LdapUtils.convertLdapException(new MockNoSuchAttributeException()).getClass()) + .isEqualTo(org.springframework.ldap.NoSuchAttributeException.class); + assertThat(LdapUtils.convertLdapException(new MockNotContextException()).getClass()) .isEqualTo(org.springframework.ldap.NotContextException.class); - assertThat( - LdapUtils.convertLdapException(new MockOperationNotSupportedException()) - .getClass()).isEqualTo( - org.springframework.ldap.OperationNotSupportedException.class); - assertThat( - LdapUtils.convertLdapException(new MockPartialResultException()) - .getClass()).isEqualTo( - org.springframework.ldap.PartialResultException.class); - assertThat( - LdapUtils.convertLdapException(new MockSchemaViolationException()) - .getClass()).isEqualTo( - org.springframework.ldap.SchemaViolationException.class); - assertThat( - LdapUtils.convertLdapException(new MockServiceUnavailableException()) - .getClass()).isEqualTo( - org.springframework.ldap.ServiceUnavailableException.class); + assertThat(LdapUtils.convertLdapException(new MockOperationNotSupportedException()).getClass()) + .isEqualTo(org.springframework.ldap.OperationNotSupportedException.class); + assertThat(LdapUtils.convertLdapException(new MockPartialResultException()).getClass()) + .isEqualTo(org.springframework.ldap.PartialResultException.class); + assertThat(LdapUtils.convertLdapException(new MockSchemaViolationException()).getClass()) + .isEqualTo(org.springframework.ldap.SchemaViolationException.class); + assertThat(LdapUtils.convertLdapException(new MockServiceUnavailableException()).getClass()) + .isEqualTo(org.springframework.ldap.ServiceUnavailableException.class); } public class MockAttributeInUseException extends javax.naming.directory.AttributeInUseException { + } public class MockAttributeModificationException extends javax.naming.directory.AttributeModificationException { + } public class MockCannotProceedException extends javax.naming.CannotProceedException { + } public class MockCommunicationException extends javax.naming.CommunicationException { + } public class MockConfigurationException extends javax.naming.ConfigurationException { + } public class MockContextNotEmptyException extends javax.naming.ContextNotEmptyException { + } public class MockInsufficientResourcesException extends javax.naming.InsufficientResourcesException { + } public class MockInterruptedNamingException extends javax.naming.InterruptedNamingException { + } - public class MockInvalidAttributeIdentifierException extends javax.naming.directory.InvalidAttributeIdentifierException { + public class MockInvalidAttributeIdentifierException + extends javax.naming.directory.InvalidAttributeIdentifierException { + } public class MockInvalidAttributesException extends javax.naming.directory.InvalidAttributesException { + } public class MockInvalidAttributeValueException extends javax.naming.directory.InvalidAttributeValueException { + } public class MockInvalidNameException extends javax.naming.InvalidNameException { + } public class MockInvalidSearchControlsException extends javax.naming.directory.InvalidSearchControlsException { + } public class MockInvalidSearchFilterException extends javax.naming.directory.InvalidSearchFilterException { + } public class MockSizeLimitExceededException extends javax.naming.SizeLimitExceededException { + } public class MockTimeLimitExceededException extends javax.naming.TimeLimitExceededException { + } public class MockLimitExceededException extends javax.naming.LimitExceededException { + } public class MockLinkLoopException extends javax.naming.LinkLoopException { + } public class MockMalformedLinkException extends javax.naming.MalformedLinkException { + } public class MockLinkException extends javax.naming.LinkException { + } public class MockNameAlreadyBoundException extends javax.naming.NameAlreadyBoundException { + } public class MockNameNotFoundException extends javax.naming.NameNotFoundException { + } public class MockNoPermissionException extends javax.naming.NoPermissionException { + } public class MockAuthenticationException extends javax.naming.AuthenticationException { + } public class MockAuthenticationNotSupportedException extends javax.naming.AuthenticationNotSupportedException { + } public class MockNoInitialContextException extends javax.naming.NoInitialContextException { + } public class MockNoSuchAttributeException extends javax.naming.directory.NoSuchAttributeException { + } public class MockNotContextException extends javax.naming.NotContextException { + } public class MockOperationNotSupportedException extends javax.naming.OperationNotSupportedException { + } public class MockPartialResultException extends javax.naming.PartialResultException { + } public class MockSchemaViolationException extends javax.naming.directory.SchemaViolationException { + } public class MockServiceUnavailableException extends javax.naming.ServiceUnavailableException { + } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationExecutorTest.java index 32fb9505..b1ca72df 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationExecutorTest.java @@ -28,6 +28,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; public class BindOperationExecutorTest { + private LdapOperations ldapOperationsMock; @Before @@ -40,8 +41,7 @@ public class BindOperationExecutorTest { LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - BindOperationExecutor tested = new BindOperationExecutor( - ldapOperationsMock, expectedDn, expectedObject, + BindOperationExecutor tested = new BindOperationExecutor(ldapOperationsMock, expectedDn, expectedObject, expectedAttributes); // perform teste @@ -55,8 +55,7 @@ public class BindOperationExecutorTest { LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - BindOperationExecutor tested = new BindOperationExecutor( - ldapOperationsMock, expectedDn, expectedObject, + BindOperationExecutor tested = new BindOperationExecutor(ldapOperationsMock, expectedDn, expectedObject, expectedAttributes); verifyNoMoreInteractions(ldapOperationsMock); @@ -68,8 +67,7 @@ public class BindOperationExecutorTest { @Test public void testRollback() { LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); - BindOperationExecutor tested = new BindOperationExecutor( - ldapOperationsMock, expectedDn, null, null); + BindOperationExecutor tested = new BindOperationExecutor(ldapOperationsMock, expectedDn, null, null); // perform teste tested.rollback(); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationRecorderTest.java index bb9c7b1c..0a25140a 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/BindOperationRecorderTest.java @@ -30,6 +30,7 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; public class BindOperationRecorderTest { + private LdapOperations ldapOperationsMock; @Before @@ -40,38 +41,33 @@ public class BindOperationRecorderTest { @Test public void testRecordOperation_Name() { - BindOperationRecorder tested = new BindOperationRecorder( - ldapOperationsMock); + BindOperationRecorder tested = new BindOperationRecorder(ldapOperationsMock); LdapName expectedDn = LdapUtils.newLdapName("cn=John Doe"); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); // Perform test. CompensatingTransactionOperationExecutor operation = tested - .recordOperation(new Object[] { expectedDn, expectedObject, - expectedAttributes }); + .recordOperation(new Object[] { expectedDn, expectedObject, expectedAttributes }); assertThat(operation instanceof BindOperationExecutor).isTrue(); BindOperationExecutor rollbackOperation = (BindOperationExecutor) operation; assertThat(rollbackOperation.getDn()).isSameAs(expectedDn); assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); assertThat(rollbackOperation.getOriginalObject()).isSameAs(expectedObject); - assertSame(expectedAttributes, rollbackOperation - .getOriginalAttributes()); + assertSame(expectedAttributes, rollbackOperation.getOriginalAttributes()); } @Test public void testPerformOperation_String() { - BindOperationRecorder tested = new BindOperationRecorder( - ldapOperationsMock); + BindOperationRecorder tested = new BindOperationRecorder(ldapOperationsMock); String expectedDn = "cn=John Doe"; Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); // Perform test. CompensatingTransactionOperationExecutor operation = tested - .recordOperation(new Object[] { expectedDn, expectedObject, - expectedAttributes }); + .recordOperation(new Object[] { expectedDn, expectedObject, expectedAttributes }); assertThat(operation instanceof BindOperationExecutor).isTrue(); BindOperationExecutor rollbackOperation = (BindOperationExecutor) operation; @@ -81,11 +77,11 @@ public class BindOperationRecorderTest { @Test(expected = IllegalArgumentException.class) public void testPerformOperation_Invalid() { - BindOperationRecorder tested = new BindOperationRecorder( - ldapOperationsMock); + BindOperationRecorder tested = new BindOperationRecorder(ldapOperationsMock); Object expectedDn = new Object(); // Perform test. - tested.recordOperation(new Object[]{expectedDn}); + tested.recordOperation(new Object[] { expectedDn }); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactoryTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactoryTest.java index 38fc67ca..4d6ed70d 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactoryTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapCompensatingTransactionOperationFactoryTest.java @@ -26,6 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class LdapCompensatingTransactionOperationFactoryTest { + private LdapOperations ldapOperationsMock; private TempEntryRenamingStrategy renamingStrategyMock; @@ -40,8 +41,7 @@ public class LdapCompensatingTransactionOperationFactoryTest { renamingStrategyMock = mock(TempEntryRenamingStrategy.class); dirContextMock = mock(DirContext.class); - tested = new LdapCompensatingTransactionOperationFactory( - renamingStrategyMock) { + tested = new LdapCompensatingTransactionOperationFactory(renamingStrategyMock) { LdapOperations createLdapOperationsInstance(DirContext ctx) { assertThat(ctx).isEqualTo(dirContextMock); @@ -53,8 +53,7 @@ public class LdapCompensatingTransactionOperationFactoryTest { @Test public void testGetRecordingOperation_Bind() throws Exception { - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "bind"); + CompensatingTransactionOperationRecorder result = tested.createRecordingOperation(dirContextMock, "bind"); assertThat(result instanceof BindOperationRecorder).isTrue(); BindOperationRecorder bindOperationRecorder = (BindOperationRecorder) result; assertThat(bindOperationRecorder.getLdapOperations()).isSameAs(ldapOperationsMock); @@ -62,8 +61,7 @@ public class LdapCompensatingTransactionOperationFactoryTest { @Test public void testGetRecordingOperation_Rebind() throws Exception { - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "rebind"); + CompensatingTransactionOperationRecorder result = tested.createRecordingOperation(dirContextMock, "rebind"); assertThat(result instanceof RebindOperationRecorder).isTrue(); RebindOperationRecorder rebindOperationRecorder = (RebindOperationRecorder) result; assertThat(rebindOperationRecorder.getLdapOperations()).isSameAs(ldapOperationsMock); @@ -72,8 +70,7 @@ public class LdapCompensatingTransactionOperationFactoryTest { @Test public void testGetRecordingOperation_Rename() throws Exception { - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "rename"); + CompensatingTransactionOperationRecorder result = tested.createRecordingOperation(dirContextMock, "rename"); assertThat(result instanceof RenameOperationRecorder).isTrue(); RenameOperationRecorder recordingOperation = (RenameOperationRecorder) result; assertThat(recordingOperation.getLdapOperations()).isSameAs(ldapOperationsMock); @@ -81,8 +78,8 @@ public class LdapCompensatingTransactionOperationFactoryTest { @Test public void testGetRecordingOperation_ModifyAttributes() throws Exception { - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "modifyAttributes"); + CompensatingTransactionOperationRecorder result = tested.createRecordingOperation(dirContextMock, + "modifyAttributes"); assertThat(result instanceof ModifyAttributesOperationRecorder).isTrue(); ModifyAttributesOperationRecorder recordingOperation = (ModifyAttributesOperationRecorder) result; assertThat(recordingOperation.getLdapOperations()).isSameAs(ldapOperationsMock); @@ -90,11 +87,11 @@ public class LdapCompensatingTransactionOperationFactoryTest { @Test public void testGetRecordingOperation_Unbind() throws Exception { - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "unbind"); + CompensatingTransactionOperationRecorder result = tested.createRecordingOperation(dirContextMock, "unbind"); assertThat(result instanceof UnbindOperationRecorder).isTrue(); UnbindOperationRecorder recordingOperation = (UnbindOperationRecorder) result; assertThat(recordingOperation.getLdapOperations()).isSameAs(ldapOperationsMock); assertThat(recordingOperation.getRenamingStrategy()).isSameAs(renamingStrategyMock); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtilsTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtilsTest.java index 290675d4..6e7314ee 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtilsTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtilsTest.java @@ -54,20 +54,13 @@ public class LdapTransactionUtilsTest { @Test public void testIsSupportedWriteTransactionOperation() { - assertTrue(LdapTransactionUtils - .isSupportedWriteTransactionOperation("bind")); - assertTrue(LdapTransactionUtils - .isSupportedWriteTransactionOperation("rebind")); - assertTrue(LdapTransactionUtils - .isSupportedWriteTransactionOperation("unbind")); - assertTrue(LdapTransactionUtils - .isSupportedWriteTransactionOperation("modifyAttributes")); - assertTrue(LdapTransactionUtils - .isSupportedWriteTransactionOperation("rename")); - assertFalse(LdapTransactionUtils - .isSupportedWriteTransactionOperation("lookup")); - assertFalse(LdapTransactionUtils - .isSupportedWriteTransactionOperation("search")); + assertTrue(LdapTransactionUtils.isSupportedWriteTransactionOperation("bind")); + assertTrue(LdapTransactionUtils.isSupportedWriteTransactionOperation("rebind")); + assertTrue(LdapTransactionUtils.isSupportedWriteTransactionOperation("unbind")); + assertTrue(LdapTransactionUtils.isSupportedWriteTransactionOperation("modifyAttributes")); + assertTrue(LdapTransactionUtils.isSupportedWriteTransactionOperation("rename")); + assertFalse(LdapTransactionUtils.isSupportedWriteTransactionOperation("lookup")); + assertFalse(LdapTransactionUtils.isSupportedWriteTransactionOperation("search")); } public void dummyMethod() { diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutorTest.java index 3d71145a..2c45adf1 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationExecutorTest.java @@ -28,6 +28,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; public class ModifyAttributesOperationExecutorTest { + private LdapOperations ldapOperationsMock; @Before @@ -42,8 +43,8 @@ public class ModifyAttributesOperationExecutorTest { Name expectedDn = LdapUtils.newLdapName("cn=john doe"); - ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, - expectedDn, expectedActualItems, expectedCompensatingItems); + ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, expectedDn, + expectedActualItems, expectedCompensatingItems); // Perform test tested.performOperation(); @@ -58,8 +59,8 @@ public class ModifyAttributesOperationExecutorTest { Name expectedDn = LdapUtils.newLdapName("cn=john doe"); - ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, - expectedDn, expectedActualItems, expectedCompensatingItems); + ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, expectedDn, + expectedActualItems, expectedCompensatingItems); // No operation here verifyNoMoreInteractions(ldapOperationsMock); @@ -75,12 +76,13 @@ public class ModifyAttributesOperationExecutorTest { Name expectedDn = LdapUtils.newLdapName("cn=john doe"); - ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, - expectedDn, expectedActualItems, expectedCompensatingItems); + ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, expectedDn, + expectedActualItems, expectedCompensatingItems); // Perform test tested.rollback(); verify(ldapOperationsMock).modifyAttributes(expectedDn, expectedCompensatingItems); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorderTest.java index 7fdadae3..cae69e75 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/ModifyAttributesOperationRecorderTest.java @@ -37,6 +37,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ModifyAttributesOperationRecorderTest { + private LdapOperations ldapOperationsMock; private IncrementalAttributesMapper attributesMapperMock; @@ -53,11 +54,11 @@ public class ModifyAttributesOperationRecorderTest { @Test public void testRecordOperation() { - final ModificationItem incomingItem = new ModificationItem( - DirContext.ADD_ATTRIBUTE, new BasicAttribute("attribute1")); - ModificationItem[] incomingMods = new ModificationItem[]{incomingItem}; - final ModificationItem compensatingItem = new ModificationItem( - DirContext.ADD_ATTRIBUTE, new BasicAttribute("attribute2")); + final ModificationItem incomingItem = new ModificationItem(DirContext.ADD_ATTRIBUTE, + new BasicAttribute("attribute1")); + ModificationItem[] incomingMods = new ModificationItem[] { incomingItem }; + final ModificationItem compensatingItem = new ModificationItem(DirContext.ADD_ATTRIBUTE, + new BasicAttribute("attribute2")); final Attributes expectedAttributes = new BasicAttributes(); @@ -66,8 +67,7 @@ public class ModifyAttributesOperationRecorderTest { return attributesMapperMock; } - protected ModificationItem getCompensatingModificationItem( - Attributes originalAttributes, + protected ModificationItem getCompensatingModificationItem(Attributes originalAttributes, ModificationItem modificationItem) { assertThat(originalAttributes).isSameAs(expectedAttributes); assertThat(modificationItem).isSameAs(incomingItem); @@ -78,16 +78,14 @@ public class ModifyAttributesOperationRecorderTest { LdapName expectedName = LdapUtils.newLdapName("cn=john doe"); when(attributesMapperMock.hasMore()).thenReturn(true, false); - when(attributesMapperMock.getAttributesForLookup()) - .thenReturn(new String[]{"attribute1"}); - when(ldapOperationsMock.lookup(expectedName, new String[]{"attribute1"}, attributesMapperMock)) - .thenReturn(expectedAttributes); - when(attributesMapperMock.getCollectedAttributes()) + when(attributesMapperMock.getAttributesForLookup()).thenReturn(new String[] { "attribute1" }); + when(ldapOperationsMock.lookup(expectedName, new String[] { "attribute1" }, attributesMapperMock)) .thenReturn(expectedAttributes); + when(attributesMapperMock.getCollectedAttributes()).thenReturn(expectedAttributes); // Perform test CompensatingTransactionOperationExecutor operation = tested - .recordOperation(new Object[]{expectedName, incomingMods}); + .recordOperation(new Object[] { expectedName, incomingMods }); // Verify outcome assertThat(operation instanceof ModifyAttributesOperationExecutor).isTrue(); @@ -102,20 +100,18 @@ public class ModifyAttributesOperationRecorderTest { } @Test - public void testGetCompensatingModificationItem_RemoveFullExistingAttribute() - throws NamingException { + public void testGetCompensatingModificationItem_RemoveFullExistingAttribute() throws NamingException { BasicAttribute attribute = new BasicAttribute("someattr"); attribute.add("value1"); attribute.add("value2"); Attributes attributes = new BasicAttributes(); attributes.put(attribute); - ModificationItem originalItem = new ModificationItem( - DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("someattr")); + ModificationItem originalItem = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, + new BasicAttribute("someattr")); // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); + ModificationItem result = tested.getCompensatingModificationItem(attributes, originalItem); // Verify result assertThat(result.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE); @@ -127,8 +123,7 @@ public class ModifyAttributesOperationRecorderTest { } @Test - public void testGetCompensatingModificationItem_RemoveTwoAttributeValues() - throws NamingException { + public void testGetCompensatingModificationItem_RemoveTwoAttributeValues() throws NamingException { BasicAttribute attribute = new BasicAttribute("someattr"); attribute.add("value1"); attribute.add("value2"); @@ -139,12 +134,10 @@ public class ModifyAttributesOperationRecorderTest { BasicAttribute modificationAttribute = new BasicAttribute("someattr"); modificationAttribute.add("value1"); modificationAttribute.add("value2"); - ModificationItem originalItem = new ModificationItem( - DirContext.REMOVE_ATTRIBUTE, modificationAttribute); + ModificationItem originalItem = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, modificationAttribute); // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); + ModificationItem result = tested.getCompensatingModificationItem(attributes, originalItem); // Verify result assertThat(result.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE); @@ -156,8 +149,7 @@ public class ModifyAttributesOperationRecorderTest { } @Test - public void testGetCompensatingModificationItem_ReplaceExistingAttribute() - throws NamingException { + public void testGetCompensatingModificationItem_ReplaceExistingAttribute() throws NamingException { BasicAttribute attribute = new BasicAttribute("someattr"); attribute.add("value1"); attribute.add("value2"); @@ -167,12 +159,11 @@ public class ModifyAttributesOperationRecorderTest { BasicAttribute modificationAttribute = new BasicAttribute("someattr"); modificationAttribute.add("newvalue1"); modificationAttribute.add("newvalue2"); - ModificationItem originalItem = new ModificationItem( - DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("someattr")); + ModificationItem originalItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, + new BasicAttribute("someattr")); // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); + ModificationItem result = tested.getCompensatingModificationItem(attributes, originalItem); // Verify result assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE); @@ -184,19 +175,16 @@ public class ModifyAttributesOperationRecorderTest { } @Test - public void testGetCompensatingModificationItem_ReplaceNonExistingAttribute() - throws NamingException { + public void testGetCompensatingModificationItem_ReplaceNonExistingAttribute() throws NamingException { Attributes attributes = new BasicAttributes(); BasicAttribute modificationAttribute = new BasicAttribute("someattr"); modificationAttribute.add("newvalue1"); modificationAttribute.add("newvalue2"); - ModificationItem originalItem = new ModificationItem( - DirContext.REPLACE_ATTRIBUTE, modificationAttribute); + ModificationItem originalItem = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, modificationAttribute); // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); + ModificationItem result = tested.getCompensatingModificationItem(attributes, originalItem); // Verify result assertThat(result.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE); @@ -206,19 +194,16 @@ public class ModifyAttributesOperationRecorderTest { } @Test - public void testGetCompensatingModificationItem_AddNonExistingAttribute() - throws NamingException { + public void testGetCompensatingModificationItem_AddNonExistingAttribute() throws NamingException { Attributes attributes = new BasicAttributes(); BasicAttribute modificationAttribute = new BasicAttribute("someattr"); modificationAttribute.add("newvalue1"); modificationAttribute.add("newvalue2"); - ModificationItem originalItem = new ModificationItem( - DirContext.ADD_ATTRIBUTE, modificationAttribute); + ModificationItem originalItem = new ModificationItem(DirContext.ADD_ATTRIBUTE, modificationAttribute); // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); + ModificationItem result = tested.getCompensatingModificationItem(attributes, originalItem); // Verify result assertThat(result.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE); @@ -228,8 +213,7 @@ public class ModifyAttributesOperationRecorderTest { } @Test - public void testGetCompensatingModificationItem_AddExistingAttribute() - throws NamingException { + public void testGetCompensatingModificationItem_AddExistingAttribute() throws NamingException { BasicAttribute attribute = new BasicAttribute("someattr"); attribute.add("value1"); attribute.add("value2"); @@ -239,12 +223,10 @@ public class ModifyAttributesOperationRecorderTest { BasicAttribute modificationAttribute = new BasicAttribute("someattr"); modificationAttribute.add("newvalue1"); modificationAttribute.add("newvalue2"); - ModificationItem originalItem = new ModificationItem( - DirContext.ADD_ATTRIBUTE, new BasicAttribute("someattr")); + ModificationItem originalItem = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("someattr")); // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); + ModificationItem result = tested.getCompensatingModificationItem(attributes, originalItem); // Verify result assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE); @@ -253,4 +235,5 @@ public class ModifyAttributesOperationRecorderTest { assertThat(result.getAttribute().get(0)).isEqualTo("value1"); assertThat(result.getAttribute().get(1)).isEqualTo("value2"); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTest.java index f3a2dfd9..23a9db78 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationExecutorTest.java @@ -37,34 +37,27 @@ public class RebindOperationExecutorTest { @Test public void testPerformOperation() { - LdapName expectedOriginalDn = LdapUtils.newLdapName( - "cn=john doe"); - LdapName expectedTempDn = LdapUtils.newLdapName( - "cn=john doe_temp"); + LdapName expectedOriginalDn = LdapUtils.newLdapName("cn=john doe"); + LdapName expectedTempDn = LdapUtils.newLdapName("cn=john doe_temp"); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - RebindOperationExecutor tested = new RebindOperationExecutor( - ldapOperationsMock, expectedOriginalDn, expectedTempDn, - expectedObject, expectedAttributes); + RebindOperationExecutor tested = new RebindOperationExecutor(ldapOperationsMock, expectedOriginalDn, + expectedTempDn, expectedObject, expectedAttributes); // perform test tested.performOperation(); verify(ldapOperationsMock).rename(expectedOriginalDn, expectedTempDn); - verify(ldapOperationsMock) - .bind(expectedOriginalDn, expectedObject, expectedAttributes); + verify(ldapOperationsMock).bind(expectedOriginalDn, expectedObject, expectedAttributes); } @Test public void testCommit() { - LdapName expectedOriginalDn = LdapUtils.newLdapName( - "cn=john doe"); - LdapName expectedTempDn = LdapUtils.newLdapName( - "cn=john doe_temp"); + LdapName expectedOriginalDn = LdapUtils.newLdapName("cn=john doe"); + LdapName expectedTempDn = LdapUtils.newLdapName("cn=john doe_temp"); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - RebindOperationExecutor tested = new RebindOperationExecutor( - ldapOperationsMock, expectedOriginalDn, expectedTempDn, - expectedObject, expectedAttributes); + RebindOperationExecutor tested = new RebindOperationExecutor(ldapOperationsMock, expectedOriginalDn, + expectedTempDn, expectedObject, expectedAttributes); // perform test tested.commit(); @@ -73,15 +66,12 @@ public class RebindOperationExecutorTest { @Test public void testRollback() { - LdapName expectedOriginalDn = LdapUtils.newLdapName( - "cn=john doe"); - LdapName expectedTempDn = LdapUtils.newLdapName( - "cn=john doe_temp"); + LdapName expectedOriginalDn = LdapUtils.newLdapName("cn=john doe"); + LdapName expectedTempDn = LdapUtils.newLdapName("cn=john doe_temp"); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); - RebindOperationExecutor tested = new RebindOperationExecutor( - ldapOperationsMock, expectedOriginalDn, expectedTempDn, - expectedObject, expectedAttributes); + RebindOperationExecutor tested = new RebindOperationExecutor(ldapOperationsMock, expectedOriginalDn, + expectedTempDn, expectedObject, expectedAttributes); // perform test tested.rollback(); @@ -89,4 +79,5 @@ public class RebindOperationExecutorTest { verify(ldapOperationsMock).unbind(expectedOriginalDn); verify(ldapOperationsMock).rename(expectedTempDn, expectedOriginalDn); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorderTest.java index 9bf1d550..a979ecf2 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/RebindOperationRecorderTest.java @@ -29,6 +29,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RebindOperationRecorderTest { + private LdapOperations ldapOperationsMock; private TempEntryRenamingStrategy renamingStrategyMock; @@ -42,23 +43,18 @@ public class RebindOperationRecorderTest { @Test public void testRecordOperation() { - final LdapName expectedDn = LdapUtils.newLdapName( - "cn=john doe"); - final LdapName expectedTempDn = LdapUtils.newLdapName( - "cn=john doe"); - RebindOperationRecorder tested = new RebindOperationRecorder( - ldapOperationsMock, renamingStrategyMock); + final LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); + final LdapName expectedTempDn = LdapUtils.newLdapName("cn=john doe"); + RebindOperationRecorder tested = new RebindOperationRecorder(ldapOperationsMock, renamingStrategyMock); - when(renamingStrategyMock.getTemporaryName(expectedDn)) - .thenReturn(expectedTempDn); + when(renamingStrategyMock.getTemporaryName(expectedDn)).thenReturn(expectedTempDn); Object expectedObject = new Object(); BasicAttributes expectedAttributes = new BasicAttributes(); // perform test CompensatingTransactionOperationExecutor result = tested - .recordOperation(new Object[] { expectedDn, expectedObject, - expectedAttributes }); + .recordOperation(new Object[] { expectedDn, expectedObject, expectedAttributes }); assertThat(result instanceof RebindOperationExecutor).isTrue(); RebindOperationExecutor rollbackOperation = (RebindOperationExecutor) result; assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); @@ -67,4 +63,5 @@ public class RebindOperationRecorderTest { assertThat(rollbackOperation.getOriginalObject()).isSameAs(expectedObject); assertThat(rollbackOperation.getOriginalAttributes()).isSameAs(expectedAttributes); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutorTest.java index 202985e6..91e0aa07 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationExecutorTest.java @@ -28,21 +28,21 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; public class RenameOperationExecutorTest { + private LdapOperations ldapOperationsMock; @Before public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class);; + ldapOperationsMock = mock(LdapOperations.class); + ; } - - @Test public void testPerformOperation() { LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); - RenameOperationExecutor tested = new RenameOperationExecutor( - ldapOperationsMock, expectedOldName, expectedNewName); + RenameOperationExecutor tested = new RenameOperationExecutor(ldapOperationsMock, expectedOldName, + expectedNewName); // Perform test. tested.performOperation(); @@ -54,8 +54,8 @@ public class RenameOperationExecutorTest { public void testCommit() { LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); - RenameOperationExecutor tested = new RenameOperationExecutor( - ldapOperationsMock, expectedOldName, expectedNewName); + RenameOperationExecutor tested = new RenameOperationExecutor(ldapOperationsMock, expectedOldName, + expectedNewName); // Nothing to do for this operation. verifyNoMoreInteractions(ldapOperationsMock); @@ -68,8 +68,8 @@ public class RenameOperationExecutorTest { public void testRollback() { LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); - RenameOperationExecutor tested = new RenameOperationExecutor( - ldapOperationsMock, expectedOldName, expectedNewName); + RenameOperationExecutor tested = new RenameOperationExecutor(ldapOperationsMock, expectedOldName, + expectedNewName); // Perform test. tested.rollback(); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorderTest.java index f1b88818..5b627ac2 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/RenameOperationRecorderTest.java @@ -29,13 +29,13 @@ public class RenameOperationRecorderTest { @Before public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class);; + ldapOperationsMock = mock(LdapOperations.class); + ; } @Test public void testRecordOperation() { - RenameOperationRecorder tested = new RenameOperationRecorder( - ldapOperationsMock); + RenameOperationRecorder tested = new RenameOperationRecorder(ldapOperationsMock); // Perform test CompensatingTransactionOperationExecutor operation = tested @@ -47,4 +47,5 @@ public class RenameOperationRecorderTest { assertThat(rollbackOperation.getNewDn().toString()).isEqualTo("ou=newou"); assertThat(rollbackOperation.getOriginalDn().toString()).isEqualTo("ou=someou"); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutorTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutorTest.java index 2358250d..ff88b09a 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutorTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationExecutorTest.java @@ -26,19 +26,21 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class UnbindOperationExecutorTest { + private LdapOperations ldapOperationsMock; @Before public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class);; + ldapOperationsMock = mock(LdapOperations.class); + ; } @Test public void testPerformOperation() { LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); - UnbindOperationExecutor tested = new UnbindOperationExecutor( - ldapOperationsMock, expectedOldName, expectedTempName); + UnbindOperationExecutor tested = new UnbindOperationExecutor(ldapOperationsMock, expectedOldName, + expectedTempName); // Perform test tested.performOperation(); @@ -50,8 +52,8 @@ public class UnbindOperationExecutorTest { public void testCommit() { LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); - UnbindOperationExecutor tested = new UnbindOperationExecutor( - ldapOperationsMock, expectedOldName, expectedTempName); + UnbindOperationExecutor tested = new UnbindOperationExecutor(ldapOperationsMock, expectedOldName, + expectedTempName); // Perform test tested.commit(); @@ -62,13 +64,12 @@ public class UnbindOperationExecutorTest { public void testRollback() { LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); - UnbindOperationExecutor tested = new UnbindOperationExecutor( - ldapOperationsMock, expectedOldName, expectedTempName); - - + UnbindOperationExecutor tested = new UnbindOperationExecutor(ldapOperationsMock, expectedOldName, + expectedTempName); // Perform test tested.rollback(); verify(ldapOperationsMock).rename(expectedTempName, expectedOldName); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorderTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorderTest.java index c67eca10..96d6a1e0 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorderTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/UnbindOperationRecorderTest.java @@ -28,32 +28,29 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class UnbindOperationRecorderTest { + private LdapOperations ldapOperationsMock; private TempEntryRenamingStrategy renamingStrategyMock; @Before public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class);; + ldapOperationsMock = mock(LdapOperations.class); + ; renamingStrategyMock = mock(TempEntryRenamingStrategy.class); } @Test public void testRecordOperation() { - final LdapName expectedTempName = LdapUtils.newLdapName( - "cn=john doe_temp"); - final LdapName expectedDn = LdapUtils.newLdapName( - "cn=john doe"); - UnbindOperationRecorder tested = new UnbindOperationRecorder( - ldapOperationsMock, renamingStrategyMock); + final LdapName expectedTempName = LdapUtils.newLdapName("cn=john doe_temp"); + final LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); + UnbindOperationRecorder tested = new UnbindOperationRecorder(ldapOperationsMock, renamingStrategyMock); - when(renamingStrategyMock.getTemporaryName(expectedDn)) - .thenReturn(expectedTempName); + when(renamingStrategyMock.getTemporaryName(expectedDn)).thenReturn(expectedTempName); // Perform test - CompensatingTransactionOperationExecutor operation = tested - .recordOperation(new Object[] { expectedDn }); + CompensatingTransactionOperationExecutor operation = tested.recordOperation(new Object[] { expectedDn }); // Verify result assertThat(operation instanceof UnbindOperationExecutor).isTrue(); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/CompensatingTransactionUtilsTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/CompensatingTransactionUtilsTest.java index 8daf83ed..777b3e89 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/CompensatingTransactionUtilsTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/CompensatingTransactionUtilsTest.java @@ -50,33 +50,29 @@ public class CompensatingTransactionUtilsTest { @Test public void testPerformOperation() throws Throwable { - CompensatingTransactionHolderSupport holder = new DirContextHolder( - null, dirContextMock); + CompensatingTransactionHolderSupport holder = new DirContextHolder(null, dirContextMock); holder.setTransactionOperationManager(operationManagerMock); - TransactionSynchronizationManager.bindResource(contextSourceMock, - holder); + TransactionSynchronizationManager.bindResource(contextSourceMock, holder); Object[] expectedArgs = new Object[] { "someDn" }; - CompensatingTransactionUtils.performOperation(contextSourceMock, - dirContextMock, getUnbindMethod(), expectedArgs); - verify(operationManagerMock).performOperation(dirContextMock, "unbind", + CompensatingTransactionUtils.performOperation(contextSourceMock, dirContextMock, getUnbindMethod(), expectedArgs); + verify(operationManagerMock).performOperation(dirContextMock, "unbind", expectedArgs); } @Test public void testPerformOperation_NoTransaction() throws Throwable { Object[] expectedArgs = new Object[] { "someDn" }; - CompensatingTransactionUtils.performOperation(contextSourceMock, - dirContextMock, getUnbindMethod(), expectedArgs); + CompensatingTransactionUtils.performOperation(contextSourceMock, dirContextMock, getUnbindMethod(), + expectedArgs); verify(dirContextMock).unbind("someDn"); } private Method getUnbindMethod() throws NoSuchMethodException { - return DirContext.class.getMethod("unbind", - new Class[] { String.class }); + return DirContext.class.getMethod("unbind", new Class[] { String.class }); } public void dummyMethod() { diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerTest.java index f695d49e..3e53ba66 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManagerTest.java @@ -45,9 +45,11 @@ import static org.mockito.Mockito.when; public class ContextSourceTransactionManagerTest { private ContextSource contextSourceMock; + private DirContext contextMock; private ContextSourceTransactionManager tested; + private CompensatingTransactionOperationManager transactionDataManagerMock; private TransactionDefinition transactionDefinitionMock; @@ -163,8 +165,8 @@ public class ContextSourceTransactionManagerTest { final ContextSourceTransactionManager txMgrInner = new ContextSourceTransactionManager(); txMgrInner.setContextSource(unconnectableContextSourceMock); - final TransactionStatus txInner = txMgrInner.getTransaction(new DefaultTransactionDefinition( - TransactionDefinition.PROPAGATION_REQUIRES_NEW)); + final TransactionStatus txInner = txMgrInner.getTransaction( + new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW)); try { // Do something with the connection that succeeds or fails @@ -193,4 +195,5 @@ public class ContextSourceTransactionManagerTest { verify(connectionMock).rollback(); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java index 0b70123a..8eae0a50 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareContextSourceProxyTest.java @@ -29,13 +29,17 @@ import static org.mockito.Mockito.when; /** * Tests for {@link TransactionAwareContextSourceProxy}. - * + * * @author Mattias Hellborg Arthursson */ public class TransactionAwareContextSourceProxyTest { + private ContextSource contextSourceMock; + private TransactionAwareContextSourceProxy tested; + private LdapContext ldapContextMock; + private DirContext dirContextMock; @Before @@ -80,4 +84,5 @@ public class TransactionAwareContextSourceProxyTest { assertThat(result instanceof LdapContext).isTrue(); assertThat(result instanceof DirContextProxy).isTrue(); } + } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandlerTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandlerTest.java index ebb6f609..83d0b13d 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandlerTest.java @@ -30,8 +30,11 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; public class TransactionAwareDirContextInvocationHandlerTest { private ContextSource contextSourceMock; + private DirContext dirContextMock; + private TransactionAwareDirContextInvocationHandler tested; + private DirContextHolder holder; @Before @@ -51,10 +54,8 @@ public class TransactionAwareDirContextInvocationHandlerTest { } @Test - public void testDoCloseConnection_ActiveTransaction() - throws NamingException { - TransactionSynchronizationManager.bindResource(contextSourceMock, - holder); + public void testDoCloseConnection_ActiveTransaction() throws NamingException { + TransactionSynchronizationManager.bindResource(contextSourceMock, holder); // Context should not be closed. verifyNoMoreInteractions(dirContextMock); @@ -63,10 +64,8 @@ public class TransactionAwareDirContextInvocationHandlerTest { } @Test - public void testDoCloseConnection_NotTransactionalContext() - throws NamingException { - TransactionSynchronizationManager.bindResource(contextSourceMock, - holder); + public void testDoCloseConnection_NotTransactionalContext() throws NamingException { + TransactionSynchronizationManager.bindResource(contextSourceMock, holder); DirContext dirContextMock2 = mock(DirContext.class); diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategyTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategyTest.java index 2c0fa123..654f8587 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategyTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DefaultTempEntryRenamingStrategyTest.java @@ -27,8 +27,7 @@ public class DefaultTempEntryRenamingStrategyTest { @Test public void testGetTemporaryName() { - LdapName expectedOriginalName = LdapUtils.newLdapName( - "cn=john doe, ou=somecompany, c=SE"); + LdapName expectedOriginalName = LdapUtils.newLdapName("cn=john doe, ou=somecompany, c=SE"); DefaultTempEntryRenamingStrategy tested = new DefaultTempEntryRenamingStrategy(); Name result = tested.getTemporaryName(expectedOriginalName); @@ -38,13 +37,11 @@ public class DefaultTempEntryRenamingStrategyTest { @Test public void testGetTemporaryDN_MultivalueDN() { - LdapName expectedOriginalName = LdapUtils.newLdapName( - "cn=john doe+sn=doe, ou=somecompany, c=SE"); + LdapName expectedOriginalName = LdapUtils.newLdapName("cn=john doe+sn=doe, ou=somecompany, c=SE"); DefaultTempEntryRenamingStrategy tested = new DefaultTempEntryRenamingStrategy(); Name result = tested.getTemporaryName(expectedOriginalName); assertThat(result.toString()).isEqualTo("cn=john doe+sn=doe_temp,ou=somecompany,c=SE"); } - } diff --git a/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategyTest.java b/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategyTest.java index 07f23e6b..1de94a89 100644 --- a/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategyTest.java +++ b/core/src/test/java/org/springframework/ldap/transaction/compensating/support/DifferentSubtreeTempEntryRenamingStrategyTest.java @@ -24,10 +24,10 @@ import javax.naming.ldap.LdapName; import static org.assertj.core.api.Assertions.assertThat; public class DifferentSubtreeTempEntryRenamingStrategyTest { + @Test public void testGetTemporaryName() { - LdapName originalName = LdapUtils.newLdapName( - "cn=john doe, ou=somecompany, c=SE"); + LdapName originalName = LdapUtils.newLdapName("cn=john doe, ou=somecompany, c=SE"); DifferentSubtreeTempEntryRenamingStrategy tested = new DifferentSubtreeTempEntryRenamingStrategy( LdapUtils.newLdapName("ou=tempEntries")); diff --git a/core/src/test/java/org/springframework/ldap/util/ListComparatorTest.java b/core/src/test/java/org/springframework/ldap/util/ListComparatorTest.java index 8bef4801..52fb62c1 100644 --- a/core/src/test/java/org/springframework/ldap/util/ListComparatorTest.java +++ b/core/src/test/java/org/springframework/ldap/util/ListComparatorTest.java @@ -82,4 +82,5 @@ public class ListComparatorTest { int result = tested.compare(list1, list2); assertThat(result < 0).isTrue(); } + } diff --git a/core/src/test/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManagerTest.java b/core/src/test/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManagerTest.java index 7230415a..83ad1435 100644 --- a/core/src/test/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManagerTest.java +++ b/core/src/test/java/org/springframework/transaction/compensating/support/DefaultCompensatingTransactionOperationManagerTest.java @@ -33,7 +33,9 @@ import static org.mockito.Mockito.when; public class DefaultCompensatingTransactionOperationManagerTest { private CompensatingTransactionOperationExecutor operationExecutorMock; + private CompensatingTransactionOperationFactory operationFactoryMock; + private CompensatingTransactionOperationRecorder operationRecorderMock; @Before @@ -104,4 +106,5 @@ public class DefaultCompensatingTransactionOperationManagerTest { tested.commit(); } + } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/InvalidAttributeFormatException.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/InvalidAttributeFormatException.java index 55956d54..74b64dc6 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/InvalidAttributeFormatException.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/InvalidAttributeFormatException.java @@ -19,7 +19,7 @@ import org.springframework.ldap.NamingException; /** * Thrown whenever a parsed attribute does not conform to LDAP specifications. - * + * * @author Keith Barlow * */ diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/InvalidRecordFormatException.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/InvalidRecordFormatException.java index 5004df25..ec12bae5 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/InvalidRecordFormatException.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/InvalidRecordFormatException.java @@ -19,7 +19,7 @@ import org.springframework.ldap.NamingException; /** * Thrown whenever a parsed record does not conform to LDAP specifications. - * + * * @author Keith Barlow * */ diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/parser/LdifParser.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/parser/LdifParser.java index fff3f394..9e91005a 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/parser/LdifParser.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/parser/LdifParser.java @@ -42,63 +42,74 @@ import java.io.InputStreamReader; import java.util.NoSuchElementException; /** - * The {@link LdifParser LdifParser} is the main class of the {@link org.springframework.ldap.ldif} package. - * This class reads lines from a resource and assembles them into an {@link LdapAttributes LdapAttributes} object. - * The {@link LdifParser LdifParser} does ignores changetype LDIF entries as their usefulness in the - * context of an application has yet to be determined. + * The {@link LdifParser LdifParser} is the main class of the + * {@link org.springframework.ldap.ldif} package. This class reads lines from a resource + * and assembles them into an {@link LdapAttributes LdapAttributes} object. The + * {@link LdifParser LdifParser} does ignores changetype LDIF entries as their + * usefulness in the context of an application has yet to be determined. *

    * Design
    - * {@link LdifParser LdifParser} provides the main interface for operation but requires three supporting classes to - * enable operation: + * {@link LdifParser LdifParser} provides the main interface for operation but requires + * three supporting classes to enable operation: *

      - *
    • {@link SeparatorPolicy SeparatorPolicy} - establishes the mechanism by which lines are assembled into attributes.
    • - *
    • {@link AttributeValidationPolicy AttributeValidationPolicy} - ensures that attributes are correctly structured prior to parsing.
    • - *
    • {@link Specification Specification} - provides a mechanism by which object structure can be validated after assembly.
    • + *
    • {@link SeparatorPolicy SeparatorPolicy} - establishes the mechanism by which lines + * are assembled into attributes.
    • + *
    • {@link AttributeValidationPolicy AttributeValidationPolicy} - ensures that + * attributes are correctly structured prior to parsing.
    • + *
    • {@link Specification Specification} - provides a mechanism by which object + * structure can be validated after assembly.
    • *
    - * Together, these 4 classes read from the resource line by line and translate the data into objects for use. + * Together, these 4 classes read from the resource line by line and translate the data + * into objects for use. *

    * Usage
    - * {@link #getRecord() getRecord()} reads the next available record from the resource. Lines are read and - * passed to the {@link SeparatorPolicy SeparatorPolicy} for interpretation. The parser continues to read - * lines and appends them to the buffer until it encounters the start of a new attribute or an end of record - * delimiter. When the new attribute or end of record is encountered, the buffer is passed to the - * {@link AttributeValidationPolicy AttributeValidationPolicy} which ensures the buffer conforms to a valid - * attribute definition as defined in RFC2849 and returns an {@link org.springframework.ldap.core.LdapAttribute LdapAttribute} object - * which is then added to the record, an {@link LdapAttributes LdapAttributes} object. Upon encountering the - * end of record, the record is validated by the {@link Specification Specification} policy and, - * if valid, returned to the requester. + * {@link #getRecord() getRecord()} reads the next available record from the resource. + * Lines are read and passed to the {@link SeparatorPolicy SeparatorPolicy} for + * interpretation. The parser continues to read lines and appends them to the buffer until + * it encounters the start of a new attribute or an end of record delimiter. When the new + * attribute or end of record is encountered, the buffer is passed to the + * {@link AttributeValidationPolicy AttributeValidationPolicy} which ensures the buffer + * conforms to a valid attribute definition as defined in RFC2849 and returns an + * {@link org.springframework.ldap.core.LdapAttribute LdapAttribute} object which is then + * added to the record, an {@link LdapAttributes LdapAttributes} object. Upon encountering + * the end of record, the record is validated by the {@link Specification Specification} + * policy and, if valid, returned to the requester. *

    - * NOTE: By default, objects are not validated. If validation is required, - * an appropriate specification object must be set. + * NOTE: By default, objects are not validated. If validation is required, an + * appropriate specification object must be set. *

    - * The parser requires the resource to be {@link #open() open()} prior to an invocation of {@link #getRecord() getRecord()}. - * {@link #hasMoreRecords() hasMoreRecords()} can be used to loop over the resource until all records have been - * retrieved. Likewise, the {@link #reset() reset()} method will reset the resource. + * The parser requires the resource to be {@link #open() open()} prior to an invocation of + * {@link #getRecord() getRecord()}. {@link #hasMoreRecords() hasMoreRecords()} can be + * used to loop over the resource until all records have been retrieved. Likewise, the + * {@link #reset() reset()} method will reset the resource. *

    - * Objects implementing the {@link javax.naming.directory.Attributes Attributes} interface are required to support a case sensitivity setting - * which controls whether or not the attribute IDs of the object are case sensitive. The {@link #caseInsensitive caseInsensitive} - * setting of the {@link LdifParser LdifParser} is passed to the constructor of any {@link javax.naming.directory.Attributes Attributes} created. The + * Objects implementing the {@link javax.naming.directory.Attributes Attributes} interface + * are required to support a case sensitivity setting which controls whether or not the + * attribute IDs of the object are case sensitive. The {@link #caseInsensitive + * caseInsensitive} setting of the {@link LdifParser LdifParser} is passed to the + * constructor of any {@link javax.naming.directory.Attributes Attributes} created. The * default value for this setting is true so that case insensitive objects are created. - * + * * @author Keith Barlow * */ public class LdifParser implements Parser, InitializingBean { private static final Logger LOG = LoggerFactory.getLogger(LdifParser.class); - + /** * The resource to parse. */ private Resource resource; - + /** * A BufferedReader to read the file. */ private BufferedReader reader; - + /** - * The SeparatorPolicy to use for interpreting attributes from the lines of the resource. + * The SeparatorPolicy to use for interpreting attributes from the lines of the + * resource. */ private SeparatorPolicy separatorPolicy = new SeparatorPolicy(); @@ -106,85 +117,83 @@ public class LdifParser implements Parser, InitializingBean { * The AttributeValidationPolicy to use to interpret attributes. */ private AttributeValidationPolicy attributePolicy = new DefaultAttributeValidationPolicy(); - + /** * The RecordSpecification for validating records produced. */ private Specification specification = new DefaultSchemaSpecification(); - + /** - * This setting is used to control the case sensitivity of LdapAttribute objects returned by the parser. + * This setting is used to control the case sensitivity of LdapAttribute objects + * returned by the parser. */ private boolean caseInsensitive = true; - + /** * Default constructor. */ public LdifParser() { - + } /** * Creates a LdifParser with the indicated case sensitivity setting. - * - * @param caseInsensitive Case sensitivity setting for LdapAttributes objects returned by the parser. + * @param caseInsensitive Case sensitivity setting for LdapAttributes objects returned + * by the parser. */ public LdifParser(boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; } - + /** - * Creates an LdifParser for the specified resource with the provided case sensitivity setting. - * + * Creates an LdifParser for the specified resource with the provided case sensitivity + * setting. * @param resource The resource to parse. - * @param caseInsensitive Case sensitivity setting for LdapAttributes objects returned by the parser. + * @param caseInsensitive Case sensitivity setting for LdapAttributes objects returned + * by the parser. */ public LdifParser(Resource resource, boolean caseInsensitive) { this.resource = resource; this.caseInsensitive = caseInsensitive; } - + /** * Convenience constructor for resource specification. - * * @param resource The resource to parse. */ public LdifParser(Resource resource) { this.resource = resource; } - + /** * Convenience constructor: accepts a File object. - * * @param file The file to parse. */ public LdifParser(File file) { this.resource = new FileSystemResource(file); } - + /** * Set the separator policy. - * + * * The default separator policy should suffice for most needs. - * * @param separatorPolicy Separator policy. */ public void setSeparatorPolicy(SeparatorPolicy separatorPolicy) { this.separatorPolicy = separatorPolicy; } - + /** * Policy object enforcing the rules for acceptable attributes. - * * @param avPolicy Attribute validation policy. */ public void setAttributeValidationPolicy(AttributeValidationPolicy avPolicy) { this.attributePolicy = avPolicy; } - + /** * Policy object for enforcing rules to acceptable LDAP objects. - * + * * This policy may be used to enforce schema restrictions. * @param specification */ @@ -193,23 +202,23 @@ public class LdifParser implements Parser, InitializingBean { } public void setResource(Resource resource) { - this.resource = resource; + this.resource = resource; } public void setCaseInsensitive(boolean caseInsensitive) { this.caseInsensitive = caseInsensitive; } - + public void open() throws IOException { Assert.notNull(resource, "Resource must be set."); - reader = new BufferedReader(new InputStreamReader(resource.getInputStream())); + reader = new BufferedReader(new InputStreamReader(resource.getInputStream())); } public boolean isReady() throws IOException { return reader.ready(); } - - public void close() throws IOException { + + public void close() throws IOException { if (resource.isOpen()) reader.close(); } @@ -218,151 +227,161 @@ public class LdifParser implements Parser, InitializingBean { Assert.notNull(reader, "A reader has not been obtained."); reader.reset(); } - + public boolean hasMoreRecords() throws IOException { return reader.ready(); } - + public LdapAttributes getRecord() throws IOException { Assert.notNull(reader, "A reader must be obtained: parser not open."); - + if (!reader.ready()) { LOG.debug("Reader not ready!"); return null; } - + LdapAttributes record = null; StringBuilder builder = new StringBuilder(); - + String line = reader.readLine(); - - while(true) { - + + while (true) { + LineIdentifier identifier = separatorPolicy.assess(line); - - switch(identifier) { - case NewRecord: - LOG.trace("Starting new record."); - //Start new record. - record = new LdapAttributes(caseInsensitive); - builder = new StringBuilder(line); - break; - - case Control: - LOG.trace("'control' encountered."); - - //Log WARN and discard record. - LOG.warn("LDIF change records have no implementation: record will be ignored."); - builder = null; - record = null; - - break; - - case ChangeType: - LOG.trace("'changetype' encountered."); - - //Log WARN and discard record. - LOG.warn("LDIF change records have no implementation: record will be ignored."); - builder = null; - record = null; - - break; - - case Attribute: - //flush buffer. - addAttributeToRecord(builder.toString(), record); + switch (identifier) { + case NewRecord: + LOG.trace("Starting new record."); + // Start new record. + record = new LdapAttributes(caseInsensitive); + builder = new StringBuilder(line); - LOG.trace("Starting new attribute."); - //Start new attribute. - builder = new StringBuilder(line); - - break; - - case Continuation: - LOG.trace("...appending line to buffer."); - //Append line to buffer. - builder.append(line.replaceFirst(" ", "")); - - break; - - case EndOfRecord: - LOG.trace("...done parsing record. (EndOfRecord)"); - - //Validate record and return. - if (record == null) { - return null; - } else { - try { - //flush buffer. - addAttributeToRecord(builder.toString(), record); - - if (specification.isSatisfiedBy(record)) { - LOG.debug("record parsed:\n" + record); - return record; - - } else { - throw new InvalidRecordFormatException("Record [dn: " + record.getDN() + "] does not conform to specification."); - } - } catch(NamingException e) { - LOG.error("Error adding attribute to record", e); - return null; + break; + + case Control: + LOG.trace("'control' encountered."); + + // Log WARN and discard record. + LOG.warn("LDIF change records have no implementation: record will be ignored."); + builder = null; + record = null; + + break; + + case ChangeType: + LOG.trace("'changetype' encountered."); + + // Log WARN and discard record. + LOG.warn("LDIF change records have no implementation: record will be ignored."); + builder = null; + record = null; + + break; + + case Attribute: + // flush buffer. + addAttributeToRecord(builder.toString(), record); + + LOG.trace("Starting new attribute."); + // Start new attribute. + builder = new StringBuilder(line); + + break; + + case Continuation: + LOG.trace("...appending line to buffer."); + // Append line to buffer. + builder.append(line.replaceFirst(" ", "")); + + break; + + case EndOfRecord: + LOG.trace("...done parsing record. (EndOfRecord)"); + + // Validate record and return. + if (record == null) { + return null; + } + else { + try { + // flush buffer. + addAttributeToRecord(builder.toString(), record); + + if (specification.isSatisfiedBy(record)) { + LOG.debug("record parsed:\n" + record); + return record; + + } + else { + throw new InvalidRecordFormatException( + "Record [dn: " + record.getDN() + "] does not conform to specification."); } } - - default: - //Take no action -- applies to VersionIdentifier, Comments, and voided records. + catch (NamingException e) { + LOG.error("Error adding attribute to record", e); + return null; + } + } + + default: + // Take no action -- applies to VersionIdentifier, Comments, and voided + // records. } - + line = reader.readLine(); - if(line == null && record == null) { - //Never encountered a valid record. + if (line == null && record == null) { + // Never encountered a valid record. return null; } } } - + private void addAttributeToRecord(String buffer, LdapAttributes record) { try { if (StringUtils.hasLength(buffer) && record != null) { - //Validate previous attribute and add to record. + // Validate previous attribute and add to record. Attribute attribute = attributePolicy.parse(buffer); - + if (attribute.getID().equalsIgnoreCase("dn")) { LOG.trace("...adding DN to record."); - + String dn; if (attribute.get() instanceof byte[]) { dn = new String((byte[]) attribute.get()); - } else { + } + else { dn = (String) attribute.get(); } record.setName(LdapUtils.newLdapName(dn)); - - } else { + + } + else { LOG.trace("...adding attribute to record."); Attribute attr = record.get(attribute.getID()); - + if (attr != null) { attr.add(attribute.get()); - } else { + } + else { record.put(attribute); } } - } - } catch (NamingException e) { + } + } + catch (NamingException e) { LOG.error("Error adding attribute to record", e); - } catch (NoSuchElementException e) { + } + catch (NoSuchElementException e) { LOG.error("Error adding attribute to record", e); } } public void afterPropertiesSet() throws Exception { Assert.notNull(resource, "A resource to parse is required."); - Assert.isTrue(resource.exists(), resource.getDescription() + ": resource does not exist!"); - Assert.isTrue(resource.isReadable(), "Resource is not readable."); + Assert.isTrue(resource.exists(), resource.getDescription() + ": resource does not exist!"); + Assert.isTrue(resource.isReadable(), "Resource is not readable."); } - + } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/parser/Parser.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/parser/Parser.java index c2cca318..195e12c2 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/parser/Parser.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/parser/Parser.java @@ -21,8 +21,8 @@ import javax.naming.directory.Attributes; import java.io.IOException; /** - * The Parser interface represents the required methods to be implemented by parser utilities. - * These methods are the base set of methods needed to provide parsing ability. + * The Parser interface represents the required methods to be implemented by parser + * utilities. These methods are the base set of methods needed to provide parsing ability. * * @author Keith Barlow */ @@ -30,60 +30,56 @@ public interface Parser { /** * Sets the resource to parse. - * * @param resource The resource to parse. */ void setResource(Resource resource); - + /** - * Sets the control parameter for specifying case sensitivity on creation of the {@link Attributes} object. - * + * Sets the control parameter for specifying case sensitivity on creation of the + * {@link Attributes} object. * @param caseInsensitive The resource to parse. */ void setCaseInsensitive(boolean caseInsensitive); - + /** * Opens the resource: the resource must be opened prior to parsing. - * * @throws IOException if a problem is encountered while trying to open the resource. */ void open() throws IOException; - + /** * Closes the resource after parsing. - * * @throws IOException if a problem is encountered while trying to close the resource. */ void close() throws IOException; - + /** * Resets the line read parser. - * * @throws IOException if a problem is encountered while trying to reset the resource. */ void reset() throws IOException; - + /** * True if the resource contains more records; false otherwise. - * * @return boolean indicating whether or not the end of record has been reached. - * @throws IOException if a problem is encountered while trying to validate the resource is ready. + * @throws IOException if a problem is encountered while trying to validate the + * resource is ready. */ boolean hasMoreRecords() throws IOException; - + /** * Parses the next record from the resource. - * * @return LdapAttributes object representing the record parsed. - * @throws IOException if a problem is encountered while trying to read from the resource. + * @throws IOException if a problem is encountered while trying to read from the + * resource. */ Attributes getRecord() throws IOException; - + /** * Indicates whether or not the parser is ready to to return results. - * * @return boolean indicator * @throws IOException if there is a problem with the underlying resource. */ boolean isReady() throws IOException; + } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/AttributeValidationPolicy.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/AttributeValidationPolicy.java index 1958444b..2cc1de3e 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/AttributeValidationPolicy.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/AttributeValidationPolicy.java @@ -21,16 +21,15 @@ import javax.naming.directory.Attribute; * Interface defining the required methods for AttributeValidationPolicies. * * @author Keith Barlow - * + * */ public interface AttributeValidationPolicy { /** * Validates attribute contained in the buffer and returns an LdapAttribute. - * * @param buffer Buffer containing the line parsed from the resource. * @return LdapAttribute representing the attribute parsed. */ Attribute parse(String buffer); - + } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/DefaultAttributeValidationPolicy.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/DefaultAttributeValidationPolicy.java index 573eeabc..16a3df4a 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/DefaultAttributeValidationPolicy.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/DefaultAttributeValidationPolicy.java @@ -32,15 +32,16 @@ import java.util.regex.Pattern; /** * Ensures the buffer represents a valid attribute as defined by RFC2849. - * - * Meets the standards imposed by RFC 2849 for the "LDAP Data Interchange Format (LDIF) - * - Technical Specification". - * - * Special attention is called to URL support: RFC 2849 requires that - * LDIFs support URLs as defined in 1738; however, RFC 1738 has been updated by several RFCs including - * RFC 1808, RFC 2396, and RFC 3986 (which obsoleted the formers). Unsupported features of this - * implementation of URL identification include query strings and fragments in HTTP URLs. - * + * + * Meets the standards imposed by RFC 2849 for the "LDAP Data Interchange Format (LDIF) - + * Technical Specification". + * + * Special attention is called to URL support: RFC 2849 requires that LDIFs support URLs + * as defined in 1738; however, RFC 1738 has been updated by several RFCs including RFC + * 1808, RFC 2396, and RFC 3986 (which obsoleted the formers). Unsupported features of + * this implementation of URL identification include query strings and fragments in HTTP + * URLs. + * * @author Keith Barlow * */ @@ -48,236 +49,266 @@ import java.util.regex.Pattern; public class DefaultAttributeValidationPolicy implements AttributeValidationPolicy { private static Logger log = LoggerFactory.getLogger(DefaultAttributeValidationPolicy.class); - + /** * Pattern Declarations. */ - - //General Definitions + + // General Definitions private static final String DIGIT = "\\p{Digit}"; - + private static final String LOW_ALPHA = "\\p{Lower}"; - + private static final String HIGH_ALPHA = "\\p{Upper}"; - + private static final String ALPHA = "\\p{Alpha}"; - + private static final String ALPHANUM = "\\p{Alnum}"; - + private static final String HEX = "\\p{XDigit}"; - - private static final String SAFE = "[\\x24\\x2D\\x5F\\x2E\\x2B]"; //$|-|_|.|+ - - private static final String EXTRA = "[\\x21\\x2A\\x27\\x7B\\x7D\\x2C]"; //!|*|'|(|)|, - - private static final String PUNCTUATION = "[\\x3C\\x3E\\x23\\x25\\x22]"; //<|>|#|%|" - + + private static final String SAFE = "[\\x24\\x2D\\x5F\\x2E\\x2B]"; // $|-|_|.|+ + + private static final String EXTRA = "[\\x21\\x2A\\x27\\x7B\\x7D\\x2C]"; // !|*|'|(|)|, + + private static final String PUNCTUATION = "[\\x3C\\x3E\\x23\\x25\\x22]"; // <|>|#|%|" + private static final String ESCAPE = "%" + HEX + "{2}"; - - private static final String RESERVED = "[\\x3B\\x2F\\x3F\\x3A\\x40\\x26\\x3D]"; //;|/|?|:|@|&|= - + + private static final String RESERVED = "[\\x3B\\x2F\\x3F\\x3A\\x40\\x26\\x3D]"; // ;|/|?|:|@|&|= + private static final String UNRESERVED = "[" + ALPHA + DIGIT + SAFE + EXTRA + "]"; - + private static final String UCHAR = "(?:" + UNRESERVED + "|" + ESCAPE + ")"; - + private static final String XCHAR = "(?:" + UNRESERVED + "|" + RESERVED + "|" + ESCAPE + ")"; - + private static final String DIGITS = DIGIT + "+"; - - //Standard LDAP Attribute Definitions + + // Standard LDAP Attribute Definitions private static final String ATTRIBUTE_SEPARATOR = ":"; private static final String OPTION_SEPARATOR = ";"; - + private static final String BASE64_INDICATOR = ":"; - + private static final String URL_INDICATOR = "<"; - + private static final String ATTRIBUTE_TYPE_CHARS = ALPHA + DIGIT + "-"; - + private static final String LDAP_OID = "[[0-9]|[1-9][0-9]+][\\.(?:[0-9]|[1-9][0-9]+)]+"; - + private static final String OPTION = "[" + ATTRIBUTE_TYPE_CHARS + "]+"; - + private static final String OPTIONS = "[" + OPTION_SEPARATOR + OPTION + "]*"; - + private static final String ATTRIBUTE_TYPE = LDAP_OID + "|" + ALPHANUM + "[" + ATTRIBUTE_TYPE_CHARS + "]*"; private static final String ATTRIBUTE_DESCRIPTION = "(" + ATTRIBUTE_TYPE + ")(" + OPTIONS + ")"; - - private static final String SAFE_CHAR = "[\\p{ASCII}&&[^\\x00\\x0A\\x0D]]"; //Any ASCII except NUL, LF, and CR - - private static final String SAFE_INIT_CHAR = "[\\p{ASCII}&&[^ \\x00\\x0A\\x0D\\x3A\\x3C]]"; //Any ASCII except NUL, LF, CR, SPACE, colon, and less-than - + + private static final String SAFE_CHAR = "[\\p{ASCII}&&[^\\x00\\x0A\\x0D]]"; // Any + // ASCII + // except + // NUL, + // LF, and + // CR + + private static final String SAFE_INIT_CHAR = "[\\p{ASCII}&&[^ \\x00\\x0A\\x0D\\x3A\\x3C]]"; // Any + // ASCII + // except + // NUL, + // LF, + // CR, + // SPACE, + // colon, + // and + // less-than + private static final String SAFE_STRING = "(" + SAFE_INIT_CHAR + SAFE_CHAR + "*)"; - - private static final String FILL = "[ ]*"; //Any number of spaces - - //BASE64 Definitions - private static final String BASE64_CHAR = "[\\x2B\\x2F\\x30-\\x39\\x3D\\x41-\\x5A\\x61-\\x7A]"; //+, /, 0-9, -, A-Z, a-z - + + private static final String FILL = "[ ]*"; // Any number of spaces + + // BASE64 Definitions + private static final String BASE64_CHAR = "[\\x2B\\x2F\\x30-\\x39\\x3D\\x41-\\x5A\\x61-\\x7A]"; // +, + // /, + // 0-9, + // -, + // A-Z, + // a-z + private static final String BASE64_STRING = "(" + BASE64_CHAR + "*)"; - - //UTF8 Definitions - private static final String UTF8_CHAR = "[\\p{L}|[0-9]|\\s]"; // \p{L} for any kind of letter from any language, including spaces and digits - + + // UTF8 Definitions + private static final String UTF8_CHAR = "[\\p{L}|[0-9]|\\s]"; // \p{L} for any kind of + // letter from any + // language, including + // spaces and digits + private static final String UTF8_STRING = "(" + UTF8_CHAR + "+)"; - //URL Components - private static final String USER = "[" + UCHAR + "\\x3B\\x3F\\x26\\x3D]*"; //UCHAR|;|?|&|= - - private static final String PASSWORD = "[" + UCHAR + "\\x3B\\x3F\\x26\\x3D]*"; //UCHAR|;|?|&|= - - private static final String DOMAINLABEL = ALPHANUM + "|" + ALPHANUM + "[" + ALPHANUM + "-]*" + ALPHANUM; - - private static final String TOPLABEL = ALPHA + "|" + ALPHA + "[" + ALPHANUM + "-]*" + ALPHANUM; - - private static final String HOSTNAME = "(?:" + DOMAINLABEL + "\\.)*" + TOPLABEL; - - private static final String IPADDRESS = "(?:" + DIGIT + "{1,3}\\.){3}" + DIGIT + "{1,3}"; - - private static final String HOST = "(?:" + HOSTNAME + "|" + IPADDRESS + ")"; - - private static final String PORT = DIGITS; - - private static final String HOSTPORT = HOST + "(?::" + PORT + ")?"; - - private static final String URLPATH = XCHAR + "*"; - - private static final String LOGIN = "(?:" + USER + "(?::" + PASSWORD + ")?@)?" + HOSTPORT; - - //URL Definitions - private static final String SCHEME = "[" + LOW_ALPHA + DIGIT + "\\x2B\\x2D\\x2E]+"; - - private static final String IP_SCHEMEPART = "//" + LOGIN + "(?:/" + URLPATH + ")?"; - - private static final String SCHEMEPART = "(?:" + XCHAR + "*|" + IP_SCHEMEPART + ")"; - - private static final String GENERIC_URL = SCHEME + ":" + SCHEMEPART; - - //HTTP Definition - private static final String HSEGMENT = "[" + UCHAR + "\\x3A\\x3B\\x26\\x3D\\x40]*"; //UCHAR|:|;|&|=|@ - - private static final String HPATH = HSEGMENT + "[/" + HSEGMENT + "]*"; - - private static final String SEARCH = HSEGMENT; - - private static final String HTTP_URL = "http://" + HOSTPORT + "(?:/" + HPATH + "(?:\\x3F" + SEARCH + ")?)?"; - - //FTP - private static final String FSEGMENT = "[" + UCHAR + "\\x3F\\x3A\\x26\\x3D\\x40]*"; //UCHAR|?|:|&|=|@ - - private static final String FPATH = FSEGMENT + "[/" + FSEGMENT + "]*"; - - private static final String FTPTYPE = "[AIDaid]"; - - private static final String FTP_URL = "ftp://" + LOGIN + "(?:/" + FPATH + "(?:;type=" + FTPTYPE + ")?)?"; - - //NEWS - private static final String GROUP = ALPHA + "[" + ALPHA + DIGIT + "\\x2D\\x2E\\x2B\\x5F]*"; //ALPHA [ALPHA|DIGIT|-|.|+|_]* + // URL Components + private static final String USER = "[" + UCHAR + "\\x3B\\x3F\\x26\\x3D]*"; // UCHAR|;|?|&|= + + private static final String PASSWORD = "[" + UCHAR + "\\x3B\\x3F\\x26\\x3D]*"; // UCHAR|;|?|&|= + + private static final String DOMAINLABEL = ALPHANUM + "|" + ALPHANUM + "[" + ALPHANUM + "-]*" + ALPHANUM; + + private static final String TOPLABEL = ALPHA + "|" + ALPHA + "[" + ALPHANUM + "-]*" + ALPHANUM; + + private static final String HOSTNAME = "(?:" + DOMAINLABEL + "\\.)*" + TOPLABEL; + + private static final String IPADDRESS = "(?:" + DIGIT + "{1,3}\\.){3}" + DIGIT + "{1,3}"; + + private static final String HOST = "(?:" + HOSTNAME + "|" + IPADDRESS + ")"; + + private static final String PORT = DIGITS; + + private static final String HOSTPORT = HOST + "(?::" + PORT + ")?"; + + private static final String URLPATH = XCHAR + "*"; + + private static final String LOGIN = "(?:" + USER + "(?::" + PASSWORD + ")?@)?" + HOSTPORT; + + // URL Definitions + private static final String SCHEME = "[" + LOW_ALPHA + DIGIT + "\\x2B\\x2D\\x2E]+"; + + private static final String IP_SCHEMEPART = "//" + LOGIN + "(?:/" + URLPATH + ")?"; + + private static final String SCHEMEPART = "(?:" + XCHAR + "*|" + IP_SCHEMEPART + ")"; + + private static final String GENERIC_URL = SCHEME + ":" + SCHEMEPART; + + // HTTP Definition + private static final String HSEGMENT = "[" + UCHAR + "\\x3A\\x3B\\x26\\x3D\\x40]*"; // UCHAR|:|;|&|=|@ + + private static final String HPATH = HSEGMENT + "[/" + HSEGMENT + "]*"; + + private static final String SEARCH = HSEGMENT; + + private static final String HTTP_URL = "http://" + HOSTPORT + "(?:/" + HPATH + "(?:\\x3F" + SEARCH + ")?)?"; + + // FTP + private static final String FSEGMENT = "[" + UCHAR + "\\x3F\\x3A\\x26\\x3D\\x40]*"; // UCHAR|?|:|&|=|@ + + private static final String FPATH = FSEGMENT + "[/" + FSEGMENT + "]*"; + + private static final String FTPTYPE = "[AIDaid]"; + + private static final String FTP_URL = "ftp://" + LOGIN + "(?:/" + FPATH + "(?:;type=" + FTPTYPE + ")?)?"; + + // NEWS + private static final String GROUP = ALPHA + "[" + ALPHA + DIGIT + "\\x2D\\x2E\\x2B\\x5F]*"; // ALPHA + // [ALPHA|DIGIT|-|.|+|_]* + + private static final String ARTICLE = "[" + UCHAR + "\\x3A\\x3B\\x2F\\x3F\\x26\\x3D]@" + HOST; // [UCHAR|;|/|?|:|&|=]@HOST - private static final String ARTICLE = "[" + UCHAR + "\\x3A\\x3B\\x2F\\x3F\\x26\\x3D]@" + HOST; //[UCHAR|;|/|?|:|&|=]@HOST - private static final String GROUPPART = "(?:\\x2A|" + GROUP + "|" + ARTICLE + ")"; - + private static final String NEWS_URL = "news:" + GROUPPART; - - //NNTP + + // NNTP private static final String NNTP_URL = "nntp://" + HOSTPORT + "/" + GROUP + "/" + DIGITS; - - //TELNET + + // TELNET private static final String TELNET_URL = "telnet://" + LOGIN + "[/]?"; - - //GOPHER + + // GOPHER private static final String GTYPE = XCHAR; - + private static final String SELECTOR = XCHAR + "*"; - + private static final String GOPHER_STRING = XCHAR + "*"; - - private static final String GOPHER_URL = "gopher://" + HOSTPORT + "(?:/(?:" + GTYPE + "(?:" + SELECTOR + "(?:%09" + SEARCH + "(?:%09" + GOPHER_STRING + ")?)?)?)?)?"; - - //WAIS + + private static final String GOPHER_URL = "gopher://" + HOSTPORT + "(?:/(?:" + GTYPE + "(?:" + SELECTOR + "(?:%09" + + SEARCH + "(?:%09" + GOPHER_STRING + ")?)?)?)?)?"; + + // WAIS private static final String WPATH = UCHAR + "*"; - + private static final String WTYPE = UCHAR + "*"; - + private static final String DATABASE = UCHAR + "*"; - + private static final String WAIS_DOC = "wais://" + HOSTPORT + "/" + DATABASE + "/" + WTYPE + "/" + WPATH; - + private static final String WAIS_INDEX = "wais://" + HOSTPORT + "/" + DATABASE + "\\?" + SEARCH; - + private static final String WAIS_DATABASE = "wais://" + HOSTPORT + "/" + DATABASE; - + private static final String WAIS_URL = WAIS_DATABASE + "|" + WAIS_INDEX + "|" + WAIS_DOC; - - //MAILTO + + // MAILTO private static final String ENCODED_822_ADDR = XCHAR + "+"; - + private static final String MAILTO_URL = "mailto:" + ENCODED_822_ADDR; - - //FILE - private static final String FILE_URL = "file://(?:" + HOST + "|localhost)?/" + FPATH ; - - //PROPERO - private static final String FIELD_VALUE = "[" + UCHAR + "\\x3F\\x3A\\x40\\x26]*"; //[UCHAR|?|:|@|&]* - - private static final String FIELD_NAME = "[" + UCHAR + "\\x3F\\x3A\\x40\\x26]*"; //[UCHAR|?|:|@|&]* - + + // FILE + private static final String FILE_URL = "file://(?:" + HOST + "|localhost)?/" + FPATH; + + // PROPERO + private static final String FIELD_VALUE = "[" + UCHAR + "\\x3F\\x3A\\x40\\x26]*"; // [UCHAR|?|:|@|&]* + + private static final String FIELD_NAME = "[" + UCHAR + "\\x3F\\x3A\\x40\\x26]*"; // [UCHAR|?|:|@|&]* + private static final String FIELD_SPEC = ";" + FIELD_NAME + "=" + FIELD_VALUE; - - private static final String PSEGMENT = "[" + UCHAR + "\\x3F\\x3A\\x40\\x26\\x3D]*"; //[UCHAR|?|:|@|&|=]* - + + private static final String PSEGMENT = "[" + UCHAR + "\\x3F\\x3A\\x40\\x26\\x3D]*"; // [UCHAR|?|:|@|&|=]* + private static final String PPATH = PSEGMENT + "(?:/" + PSEGMENT + ")*"; - + private static final String PROSPERO_URL = "prospero://" + HOSTPORT + "/" + PPATH + "(?:" + FIELD_SPEC + ")*"; - - //GENERIC + + // GENERIC private static final String OTHER_URL = GENERIC_URL; - - private static final String URL = "((?:" + HTTP_URL + ")|(?:" + FTP_URL + ")|(?:" + NEWS_URL + ")|(?:" + NNTP_URL + ")|(?:" + TELNET_URL + ")|(?:" + GOPHER_URL + ")|(?:" + WAIS_URL + ")|(?:" + MAILTO_URL + ")|(?:" + FILE_URL + ")|(?:" + PROSPERO_URL + ")|(?:" + OTHER_URL + "))"; //URL Pattern - - //Expression Definitions - private static final String ATTRIBUTE_EXPRESSION = "^" + ATTRIBUTE_DESCRIPTION + ATTRIBUTE_SEPARATOR + FILL + SAFE_STRING + "{0,1}$"; //Regular Attribute - - private static final String BASE64_ATTRIBUTE_EXPRESSION = "^" + ATTRIBUTE_DESCRIPTION + ATTRIBUTE_SEPARATOR + BASE64_INDICATOR + FILL + BASE64_STRING + "$"; //Base 64 - - private static final String URL_ATTRIBUTE_EXPRESSION = "^" + ATTRIBUTE_DESCRIPTION + ATTRIBUTE_SEPARATOR + URL_INDICATOR + FILL + URL + "$"; //URL - - private static final String UTF8_ATTRIBUTE_EXPRESSION = "^" + ATTRIBUTE_DESCRIPTION + ATTRIBUTE_SEPARATOR + FILL + UTF8_STRING; - - //Pattern Declarations + + private static final String URL = "((?:" + HTTP_URL + ")|(?:" + FTP_URL + ")|(?:" + NEWS_URL + ")|(?:" + NNTP_URL + + ")|(?:" + TELNET_URL + ")|(?:" + GOPHER_URL + ")|(?:" + WAIS_URL + ")|(?:" + MAILTO_URL + ")|(?:" + + FILE_URL + ")|(?:" + PROSPERO_URL + ")|(?:" + OTHER_URL + "))"; // URL + // Pattern + + // Expression Definitions + private static final String ATTRIBUTE_EXPRESSION = "^" + ATTRIBUTE_DESCRIPTION + ATTRIBUTE_SEPARATOR + FILL + + SAFE_STRING + "{0,1}$"; // Regular Attribute + + private static final String BASE64_ATTRIBUTE_EXPRESSION = "^" + ATTRIBUTE_DESCRIPTION + ATTRIBUTE_SEPARATOR + + BASE64_INDICATOR + FILL + BASE64_STRING + "$"; // Base 64 + + private static final String URL_ATTRIBUTE_EXPRESSION = "^" + ATTRIBUTE_DESCRIPTION + ATTRIBUTE_SEPARATOR + + URL_INDICATOR + FILL + URL + "$"; // URL + + private static final String UTF8_ATTRIBUTE_EXPRESSION = "^" + ATTRIBUTE_DESCRIPTION + ATTRIBUTE_SEPARATOR + FILL + + UTF8_STRING; + + // Pattern Declarations private static final Pattern ATTRIBUTE_PATTERN = Pattern.compile(ATTRIBUTE_EXPRESSION); - + private static final Pattern BASE64_ATTRIBUTE_PATTERN = Pattern.compile(BASE64_ATTRIBUTE_EXPRESSION); - + private static final Pattern URL_ATTRIBUTE_PATTERN = Pattern.compile(URL_ATTRIBUTE_EXPRESSION); private static final Pattern UTF8_ATTRIBUTE_PATTERN = Pattern.compile(UTF8_ATTRIBUTE_EXPRESSION); private boolean ordered = false; - + /** * Default constructor. */ public DefaultAttributeValidationPolicy() { - + } - + /** - * Constructor for indicating whether or not attribute values should be ordered alphabetically. - * - * @param ordered value. + * Constructor for indicating whether or not attribute values should be ordered + * alphabetically. + * @param ordered value. */ public DefaultAttributeValidationPolicy(boolean ordered) { this.ordered = ordered; } - + /** * Indicates whether or not the attribute values should be ordered alphabetically. - * - * @param ordered value. + * @param ordered value. */ public void setOrdered(boolean ordered) { this.ordered = ordered; @@ -288,105 +319,113 @@ public class DefaultAttributeValidationPolicy implements AttributeValidationPoli *

    * Ensures attributes meets one of four prescribed patterns for valid attributes: *

      - *
    1. A standard attribute pattern of the form: ATTR_ID[;options]: VALUE
    2. - *
    3. A Base64 attribute pattern of the form: ATTR_ID[;options]:: BASE64_VALUE
    4. - *
    5. A url attribute pattern of the form: ATTR_ID[;options]:< URL_VALUE
    6. - *
    7. A UTF8 attribute pattern of the form: ATTR_ID[;options]: UTF8_VALUE
    8. + *
    9. A standard attribute pattern of the form: ATTR_ID[;options]: VALUE
    10. + *
    11. A Base64 attribute pattern of the form: ATTR_ID[;options]:: BASE64_VALUE
    12. + *
    13. A url attribute pattern of the form: ATTR_ID[;options]:< URL_VALUE
    14. + *
    15. A UTF8 attribute pattern of the form: ATTR_ID[;options]: UTF8_VALUE
    16. *
    *

    - * Upon success an LdapAttribute object is returned. - * + * Upon success an LdapAttribute object is returned. * @param buffer {@inheritDoc} * @return {@inheritDoc} - * @throws InvalidAttributeFormatException if the attribute does not meet one of the three patterns above - * or the attribute cannot be parsed. + * @throws InvalidAttributeFormatException if the attribute does not meet one of the + * three patterns above or the attribute cannot be parsed. */ public Attribute parse(String buffer) { log.trace("Parsing --> [" + buffer + "]"); - - Matcher matcher = ATTRIBUTE_PATTERN.matcher(buffer); + + Matcher matcher = ATTRIBUTE_PATTERN.matcher(buffer); if (matcher.matches()) { - //Is a regular attribute... - return parseStringAttribute(matcher); + // Is a regular attribute... + return parseStringAttribute(matcher); } - - matcher = BASE64_ATTRIBUTE_PATTERN.matcher(buffer); + + matcher = BASE64_ATTRIBUTE_PATTERN.matcher(buffer); if (matcher.matches()) { - //Is a base64 attribute... - return parseBase64Attribute(matcher); + // Is a base64 attribute... + return parseBase64Attribute(matcher); } - - matcher = URL_ATTRIBUTE_PATTERN.matcher(buffer); + + matcher = URL_ATTRIBUTE_PATTERN.matcher(buffer); if (matcher.matches()) { - //Is a URL attribute... - return parseUrlAttribute(matcher); + // Is a URL attribute... + return parseUrlAttribute(matcher); } - - matcher = UTF8_ATTRIBUTE_PATTERN.matcher(buffer); + + matcher = UTF8_ATTRIBUTE_PATTERN.matcher(buffer); if (matcher.matches()) { - //Is a UTF8 attribute... - return parseUtf8Attribute(matcher); + // Is a UTF8 attribute... + return parseUtf8Attribute(matcher); } - - //default: no match. - throw new InvalidAttributeFormatException("Not a valid attribute: [" + buffer + "]"); + + // default: no match. + throw new InvalidAttributeFormatException("Not a valid attribute: [" + buffer + "]"); } - + private LdapAttribute parseStringAttribute(Matcher matcher) { String id = matcher.group(1); String value = matcher.group(3); - List options = Arrays.asList((!StringUtils.hasLength(matcher.group(2)) ? new String[] {} : matcher.group(2).replaceFirst(";","").split(OPTION_SEPARATOR))); - + List options = Arrays.asList((!StringUtils.hasLength(matcher.group(2)) ? new String[] {} + : matcher.group(2).replaceFirst(";", "").split(OPTION_SEPARATOR))); + if (options.isEmpty()) { return new LdapAttribute(id, value, ordered); - } else { + } + else { return new LdapAttribute(id, value, options, ordered); } } - private LdapAttribute parseBase64Attribute(Matcher matcher) { try { String id = matcher.group(1); String value = matcher.group(3); - List options = Arrays.asList((StringUtils.isEmpty(matcher.group(2)) ? new String[] {} : matcher.group(2).replaceFirst(";","").split(OPTION_SEPARATOR))); - + List options = Arrays.asList((StringUtils.isEmpty(matcher.group(2)) ? new String[] {} + : matcher.group(2).replaceFirst(";", "").split(OPTION_SEPARATOR))); + if (options.isEmpty()) { return new LdapAttribute(id, LdapEncoder.parseBase64Binary(value), ordered); - } else { + } + else { return new LdapAttribute(id, LdapEncoder.parseBase64Binary(value), options, ordered); } - } catch (IllegalArgumentException e) { + } + catch (IllegalArgumentException e) { throw new InvalidAttributeFormatException(e); } } - private LdapAttribute parseUrlAttribute(Matcher matcher) { try { String id = matcher.group(1); String value = matcher.group(3); - List options = Arrays.asList((StringUtils.isEmpty(matcher.group(2)) ? new String[] {} : matcher.group(2).replaceFirst(";","").split(OPTION_SEPARATOR))); - + List options = Arrays.asList((StringUtils.isEmpty(matcher.group(2)) ? new String[] {} + : matcher.group(2).replaceFirst(";", "").split(OPTION_SEPARATOR))); + if (options.isEmpty()) { return new LdapAttribute(id, new URI(value), ordered); - } else { + } + else { return new LdapAttribute(id, new URI(value), options, ordered); } - } catch (URISyntaxException e) { + } + catch (URISyntaxException e) { throw new InvalidAttributeFormatException(e); } } - + private LdapAttribute parseUtf8Attribute(Matcher matcher) { String id = matcher.group(1); String value = matcher.group(3); - List options = Arrays.asList((!StringUtils.hasLength(matcher.group(2)) ? new String[] {} : matcher.group(2).replaceFirst(";","").split(OPTION_SEPARATOR))); - + List options = Arrays.asList((!StringUtils.hasLength(matcher.group(2)) ? new String[] {} + : matcher.group(2).replaceFirst(";", "").split(OPTION_SEPARATOR))); + if (options.isEmpty()) { return new LdapAttribute(id, value, ordered); - } else { + } + else { return new LdapAttribute(id, value, options, ordered); } } + } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/LineIdentifier.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/LineIdentifier.java index 881a1f71..393247f3 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/LineIdentifier.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/LineIdentifier.java @@ -17,53 +17,58 @@ package org.springframework.ldap.ldif.support; /** * Enumeration declaring possible event types when parsing LDIF files. - * + * * @author Keith Barlow */ public enum LineIdentifier { + /** - * Every LDIF file may optionally start with a version identifier of the form 'version: 1'. + * Every LDIF file may optionally start with a version identifier of the form + * 'version: 1'. */ - VersionIdentifier, - - /** - * Signifies the start of a new record in the file has been encountered: a DN declaration. - */ - NewRecord, - - /** - * Signals the end of record has been reached. - */ - EndOfRecord, - - /** - * Signifies the event when a new attribute is encountered. - */ - Attribute, - - /** - * Indicates the current line parsed is a continuation of the previous line. - */ - Continuation, - - /** - * The current line is a comment and should be ignored. - */ - Comment, - - /** - * An LDAP changetype control was encountered. - */ - Control, - - /** - * Record being parsed is a 'changetype' record. - */ - ChangeType, - - /** - * Parsed line should be ignored - used to skip remaining lines in a 'changetype' record. - */ - Void + VersionIdentifier, + + /** + * Signifies the start of a new record in the file has been encountered: a DN + * declaration. + */ + NewRecord, + + /** + * Signals the end of record has been reached. + */ + EndOfRecord, + + /** + * Signifies the event when a new attribute is encountered. + */ + Attribute, + + /** + * Indicates the current line parsed is a continuation of the previous line. + */ + Continuation, + + /** + * The current line is a comment and should be ignored. + */ + Comment, + + /** + * An LDAP changetype control was encountered. + */ + Control, + + /** + * Record being parsed is a 'changetype' record. + */ + ChangeType, + + /** + * Parsed line should be ignored - used to skip remaining lines in a 'changetype' + * record. + */ + Void + } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/SeparatorPolicy.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/SeparatorPolicy.java index e8c91564..d7147633 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/SeparatorPolicy.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/SeparatorPolicy.java @@ -20,97 +20,108 @@ import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; /** - * Policy object for enforcing LDIF record separation rules. Designed explicitly - * for use in LdifParser. This default separator policy should really not be - * required to be replaced but it is modular just in case. + * Policy object for enforcing LDIF record separation rules. Designed explicitly for use + * in LdifParser. This default separator policy should really not be required to be + * replaced but it is modular just in case. *

    - * This class applies the separation policy prescribed in RFC2849 for LDIF files - * and identifies the line type from the input. - * + * This class applies the separation policy prescribed in RFC2849 for LDIF files and + * identifies the line type from the input. + * * @author Keith Barlow * */ public class SeparatorPolicy { private static Logger log = LoggerFactory.getLogger(SeparatorPolicy.class); - - /* + + /* * Line Identification Patterns. */ private static final String VERSION_IDENTIFIER = "^version: [0-9]+(\\.[0-9]*){0,1}$"; - + private static final String CONTROL = "control:"; - + private static final String CHANGE_TYPE = "changetype:"; - + private static final String CONTINUATION = " "; - + private static final String COMMENT = "#"; - + private static final String NEW_RECORD = "^dn:.*$"; private boolean record = false; - + private boolean skip = false; - + public SeparatorPolicy() { - + } /** * Assess a read line. *

    - * In LDIF, lines must adhere to a particular format. A line can only contain one attribute - * and its value. The value may span multiple lines. Continuation lines are marked by the presence - * of a single space in the 1st position. Non-continuation lines must start in the first position. - * + * In LDIF, lines must adhere to a particular format. A line can only contain one + * attribute and its value. The value may span multiple lines. Continuation lines are + * marked by the presence of a single space in the 1st position. Non-continuation + * lines must start in the first position. + * */ public LineIdentifier assess(String line) { log.trace("Assessing --> [" + line + "]"); - + if (record) { if (!StringUtils.hasLength(line)) { record = false; skip = false; return LineIdentifier.EndOfRecord; - - } else if (skip) { + + } + else if (skip) { return LineIdentifier.Void; - - } else { + + } + else { if (line.startsWith(CONTROL)) { skip = true; return LineIdentifier.Control; - - } else if (line.startsWith(CHANGE_TYPE)) { + + } + else if (line.startsWith(CHANGE_TYPE)) { skip = true; return LineIdentifier.ChangeType; - - } else if (line.startsWith(COMMENT)) { + + } + else if (line.startsWith(COMMENT)) { return LineIdentifier.Comment; - - } else if (line.startsWith(CONTINUATION)) { + + } + else if (line.startsWith(CONTINUATION)) { return LineIdentifier.Continuation; - - } else { + + } + else { return LineIdentifier.Attribute; - + } } - } else { + } + else { if (StringUtils.hasLength(line) && line.matches(VERSION_IDENTIFIER) && !skip) { - //Version Identifiers are ignored by parser. - return LineIdentifier.VersionIdentifier; - - } else if (StringUtils.hasLength(line) && line.matches(NEW_RECORD)) { + // Version Identifiers are ignored by parser. + return LineIdentifier.VersionIdentifier; + + } + else if (StringUtils.hasLength(line) && line.matches(NEW_RECORD)) { record = true; skip = false; return LineIdentifier.NewRecord; - - } else { + + } + else { return LineIdentifier.Void; } } } + } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/BasicSchemaSpecification.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/BasicSchemaSpecification.java index 0ea5ab3d..cff53ee3 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/BasicSchemaSpecification.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/BasicSchemaSpecification.java @@ -10,14 +10,14 @@ import javax.naming.ldap.Rdn; /** * BasicSchemaSpecification establishes a minimal set of requirements for object classes. *

    - * This basic specification, which does not actually validate against any schema, deems objects - * valid as long as they meet the following criteria: + * This basic specification, which does not actually validate against any schema, deems + * objects valid as long as they meet the following criteria: *

      - *
    • the object has a non-null DN.
    • - *
    • the object contains the naming attribute declared by the DN.
    • - *
    • the object declares an objectClass.
    • - *
    - * + *
  • the object has a non-null DN.
  • + *
  • the object contains the naming attribute declared by the DN.
  • + *
  • the object declares an objectClass.
  • + * + * * @author Keith Barlow * */ @@ -25,39 +25,40 @@ public class BasicSchemaSpecification implements Specification { /** * Determines if the policy is satisfied by the supplied LdapAttributes object. - * - * @throws NamingException - */ + * @throws NamingException + */ public boolean isSatisfiedBy(LdapAttributes record) throws NamingException { if (record != null) { - - //DN is required. + + // DN is required. LdapName dn = record.getName(); if (dn != null) { - - //objectClass definition is required. + + // objectClass definition is required. if (record.get("objectClass") != null) { - - //Naming attribute is required. + + // Naming attribute is required. Rdn rdn = dn.getRdn(dn.size() - 1); if (record.get(rdn.getType()) != null) { Object object = record.get(rdn.getType()).get(); - + if (object instanceof String) { String value = (String) object; - if (((String)rdn.getValue()).equalsIgnoreCase(value)) { + if (((String) rdn.getValue()).equalsIgnoreCase(value)) { return true; } - } else if(object instanceof byte[]) { - String rdnValue = LdapEncoder.printBase64Binary(((String)rdn.getValue()).getBytes()); + } + else if (object instanceof byte[]) { + String rdnValue = LdapEncoder.printBase64Binary(((String) rdn.getValue()).getBytes()); String attributeValue = LdapEncoder.printBase64Binary((byte[]) object); - if (rdnValue.equals(attributeValue)) return true; - } + if (rdnValue.equals(attributeValue)) + return true; + } } } } } - + return false; } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/DefaultSchemaSpecification.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/DefaultSchemaSpecification.java index ba617504..7c5db0e9 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/DefaultSchemaSpecification.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/DefaultSchemaSpecification.java @@ -24,7 +24,7 @@ import org.springframework.ldap.core.LdapAttributes; *

    * This specification is intended for cases where validation of the parsed entries is not * required. - * + * * @author Keith Barlow * */ @@ -32,9 +32,8 @@ public class DefaultSchemaSpecification implements Specification /** * Determines if the policy is satisfied by the supplied LdapAttributes object. - * - * @throws NamingException - */ + * @throws NamingException + */ public boolean isSatisfiedBy(LdapAttributes record) throws NamingException { return true; } diff --git a/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/Specification.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/Specification.java index e71a29b7..0dc48fae 100644 --- a/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/Specification.java +++ b/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/Specification.java @@ -18,16 +18,15 @@ package org.springframework.ldap.schema; import javax.naming.NamingException; /** - * The specification interface is implemented to declare rules that - * a record must conform to. The motivation behind this class was - * to provide a mechanism to enable schema validations. - * - * @author Keith Barlow + * The specification interface is implemented to declare rules that a record must conform + * to. The motivation behind this class was to provide a mechanism to enable schema + * validations. * + * @author Keith Barlow * @param */ public interface Specification { boolean isSatisfiedBy(T record) throws NamingException; - + } diff --git a/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/DefaultAttributeValidationPolicyTest.java b/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/DefaultAttributeValidationPolicyTest.java index 2987dd20..57dd18f0 100644 --- a/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/DefaultAttributeValidationPolicyTest.java +++ b/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/DefaultAttributeValidationPolicyTest.java @@ -37,9 +37,9 @@ import static org.assertj.core.api.Assertions.fail; /** * Parses a preselected set of attributes to test the full spectrum of functionality - * expected of an attribute parser. Attributes are validated to ensure they conform to - * the requirements for attribute values prescribed in RFC2849. - * + * expected of an attribute parser. Attributes are validated to ensure they conform to the + * requirements for attribute values prescribed in RFC2849. + * * @author Keith Barlow * */ @@ -47,23 +47,29 @@ import static org.assertj.core.api.Assertions.fail; public class DefaultAttributeValidationPolicyTest { private static Logger log = LoggerFactory.getLogger(DefaultAttributeValidationPolicyTest.class); - + private static DefaultAttributeValidationPolicy policy = new DefaultAttributeValidationPolicy(); - private static enum AttributeType { STRING, BASE64, URL, UTF8 } - + private static enum AttributeType { + + STRING, BASE64, URL, UTF8 + + } + private String line; + private String id; + private String options; + private String value; + private AttributeType type; - - private List exceptions = Arrays.asList(new String[] { - "description: :A big sailing fan.", - "cn;lang-ja:: 5bCP56yg5Y6fIO.ODreODieODi+ODvA==", - "url:< https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28" - }); - + + private List exceptions = Arrays + .asList(new String[] { "description: :A big sailing fan.", "cn;lang-ja:: 5bCP56yg5Y6fIO.ODreODieODi+ODvA==", + "url:< https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28" }); + /** * The data set to parse. * @return @@ -71,45 +77,63 @@ public class DefaultAttributeValidationPolicyTest { @Parameters public static Collection data() { return Arrays.asList(new Object[][] { - //Format: line, id, options, value, type - - //String - { "cn: Keith Barlow", "cn", "", "Keith Barlow", AttributeType.STRING}, - { "sn: Jensen", "sn", "", "Jensen", AttributeType.STRING}, - { "cn: Barbara J Jensen", "cn", "", "Barbara J Jensen", AttributeType.STRING}, - { "telephonenumber: +1 408 555 1212", "telephonenumber", "", "+1 408 555 1212", AttributeType.STRING}, - { "description: A big sailing fan.", "description", "", "A big sailing fan.", AttributeType.STRING}, - { "title;lang-en;phonetic: Sales, Director", "title", ";lang-en;phonetic", "Sales, Director", AttributeType.STRING}, - { "mail: rogasawara@airius.co.jp", "mail", "", "rogasawara@airius.co.jp", AttributeType.STRING}, - { "description: A big sailing fan.", "description", "", "A big sailing fan.", AttributeType.STRING}, - { "description: :A big sailing fan.", "description", "", ":A big sailing fan.", AttributeType.STRING}, - - //Base64 - { "xml:: PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=", "xml", "", "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=", AttributeType.BASE64}, - { "ou;lang-ja;phonetic:: 44GI44GE44GO44KH44GG44G2", "ou", ";lang-ja;phonetic", "44GI44GE44GO44KH44GG44G2", AttributeType.BASE64 }, - { "dn:: dWlkPXJvZ2FzYXdhcmEsb3U95Za25qWt6YOoLG89QWlyaXVz", "dn", "", "dWlkPXJvZ2FzYXdhcmEsb3U95Za25qWt6YOoLG89QWlyaXVz", AttributeType.BASE64 }, - { "cn;lang-ja:: 5bCP56yg5Y6fIOODreODieODi+ODvA==", "cn", ";lang-ja", "5bCP56yg5Y6fIOODreODieODi+ODvA==", AttributeType.BASE64 }, - { "cn;lang-ja:: 5bCP56yg5Y6fIO.ODreODieODi+ODvA==", "cn", ";lang-ja", "5bCP56yg5Y6fIO.ODreODieODi+ODvA==", AttributeType.BASE64 }, - - //Url - { "url:< https://www.oracle.com/", "url", "", "https://www.oracle.com/", AttributeType.URL}, - { "url:< https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html", "url", "", "https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html", AttributeType.URL}, - { "url:< ftp://kbarlow:test@ftp.is.co.za/rfc/rfc1808.txt", "url", "", "ftp://kbarlow:test@ftp.is.co.za/rfc/rfc1808.txt", AttributeType.URL}, - { "url;option:< ftp://ftp.is.co.za:2100/rfc/rfc1808.txt;type=a", "url", ";option", "ftp://ftp.is.co.za:2100/rfc/rfc1808.txt;type=a", AttributeType.URL}, - { "url:< telnet://kbarlow@melvyl.ucop.edu/", "url", "", "telnet://kbarlow@melvyl.ucop.edu/", AttributeType.URL}, - { "url;option1;option2:< telnet://kbarlow:test@melvyl.ucop.edu/", "url", ";option1;option2", "telnet://kbarlow:test@melvyl.ucop.edu/", AttributeType.URL}, - { "url:< gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", "url", "", "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", AttributeType.URL}, - { "url:< file:///usr/local/directory/photos/fiona.jpg", "url", "", "file:///usr/local/directory/photos/fiona.jpg", AttributeType.URL}, - { "url:< mailto:java-net@java.sun.com", "url", "", "mailto:java-net@java.sun.com", AttributeType.URL}, - { "url:< news:comp.infosystems.www.servers.unix", "url", "", "news:comp.infosystems.www.servers.unix", AttributeType.URL}, - { "url:< prospero://host.dom:1525//pros/name;key=value", "url", "", "prospero://host.dom:1525//pros/name;key=value", AttributeType.URL}, - { "url:< nntp://news.cs.hut.fi/alt.html/239157", "url", "", "nntp://news.cs.hut.fi/alt.html/239157", AttributeType.URL}, - { "url:< wais://vega.lib.ncsu.edu/alawon.src?nren", "url", "", "wais://vega.lib.ncsu.edu/alawon.src?nren", AttributeType.URL}, - { "url:< https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28", "url", "", "https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28", AttributeType.URL}, - - //UTF8 + // Format: line, id, options, value, type + + // String + { "cn: Keith Barlow", "cn", "", "Keith Barlow", AttributeType.STRING }, + { "sn: Jensen", "sn", "", "Jensen", AttributeType.STRING }, + { "cn: Barbara J Jensen", "cn", "", "Barbara J Jensen", AttributeType.STRING }, + { "telephonenumber: +1 408 555 1212", "telephonenumber", "", "+1 408 555 1212", AttributeType.STRING }, + { "description: A big sailing fan.", "description", "", "A big sailing fan.", AttributeType.STRING }, + { "title;lang-en;phonetic: Sales, Director", "title", ";lang-en;phonetic", "Sales, Director", + AttributeType.STRING }, + { "mail: rogasawara@airius.co.jp", "mail", "", "rogasawara@airius.co.jp", AttributeType.STRING }, + { "description: A big sailing fan.", "description", "", "A big sailing fan.", AttributeType.STRING }, + { "description: :A big sailing fan.", "description", "", ":A big sailing fan.", AttributeType.STRING }, + + // Base64 + { "xml:: PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=", "xml", "", + "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=", AttributeType.BASE64 }, + { "ou;lang-ja;phonetic:: 44GI44GE44GO44KH44GG44G2", "ou", ";lang-ja;phonetic", + "44GI44GE44GO44KH44GG44G2", AttributeType.BASE64 }, + { "dn:: dWlkPXJvZ2FzYXdhcmEsb3U95Za25qWt6YOoLG89QWlyaXVz", "dn", "", + "dWlkPXJvZ2FzYXdhcmEsb3U95Za25qWt6YOoLG89QWlyaXVz", AttributeType.BASE64 }, + { "cn;lang-ja:: 5bCP56yg5Y6fIOODreODieODi+ODvA==", "cn", ";lang-ja", "5bCP56yg5Y6fIOODreODieODi+ODvA==", + AttributeType.BASE64 }, + { "cn;lang-ja:: 5bCP56yg5Y6fIO.ODreODieODi+ODvA==", "cn", ";lang-ja", + "5bCP56yg5Y6fIO.ODreODieODi+ODvA==", AttributeType.BASE64 }, + + // Url + { "url:< https://www.oracle.com/", "url", "", "https://www.oracle.com/", AttributeType.URL }, + { "url:< https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html", "url", "", + "https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html", AttributeType.URL }, + { "url:< ftp://kbarlow:test@ftp.is.co.za/rfc/rfc1808.txt", "url", "", + "ftp://kbarlow:test@ftp.is.co.za/rfc/rfc1808.txt", AttributeType.URL }, + { "url;option:< ftp://ftp.is.co.za:2100/rfc/rfc1808.txt;type=a", "url", ";option", + "ftp://ftp.is.co.za:2100/rfc/rfc1808.txt;type=a", AttributeType.URL }, + { "url:< telnet://kbarlow@melvyl.ucop.edu/", "url", "", "telnet://kbarlow@melvyl.ucop.edu/", + AttributeType.URL }, + { "url;option1;option2:< telnet://kbarlow:test@melvyl.ucop.edu/", "url", ";option1;option2", + "telnet://kbarlow:test@melvyl.ucop.edu/", AttributeType.URL }, + { "url:< gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", "url", "", + "gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles", AttributeType.URL }, + { "url:< file:///usr/local/directory/photos/fiona.jpg", "url", "", + "file:///usr/local/directory/photos/fiona.jpg", AttributeType.URL }, + { "url:< mailto:java-net@java.sun.com", "url", "", "mailto:java-net@java.sun.com", AttributeType.URL }, + { "url:< news:comp.infosystems.www.servers.unix", "url", "", "news:comp.infosystems.www.servers.unix", + AttributeType.URL }, + { "url:< prospero://host.dom:1525//pros/name;key=value", "url", "", + "prospero://host.dom:1525//pros/name;key=value", AttributeType.URL }, + { "url:< nntp://news.cs.hut.fi/alt.html/239157", "url", "", "nntp://news.cs.hut.fi/alt.html/239157", + AttributeType.URL }, + { "url:< wais://vega.lib.ncsu.edu/alawon.src?nren", "url", "", + "wais://vega.lib.ncsu.edu/alawon.src?nren", AttributeType.URL }, + { "url:< https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28", "url", "", + "https://java.sun.com/j2se/1.3/docs/guide/collections/designfaq.html#28", AttributeType.URL }, + + // UTF8 { "company: Østfold Akershus", "company", "", "Østfold Akershus", AttributeType.STRING } - + }); } @@ -121,7 +145,8 @@ public class DefaultAttributeValidationPolicyTest { * @param value The value expected from successful parsing. * @param type The attribute type: one of enum AttributeType. */ - public DefaultAttributeValidationPolicyTest(String line, String id, String options, String value, AttributeType type) { + public DefaultAttributeValidationPolicyTest(String line, String id, String options, String value, + AttributeType type) { this.line = line; this.id = id; this.options = options; @@ -130,50 +155,55 @@ public class DefaultAttributeValidationPolicyTest { } /** - * The test case: parses passed in parameters and validates the outcome against the expected results. + * The test case: parses passed in parameters and validates the outcome against the + * expected results. */ @Test public void parseAttribute() { try { LdapAttribute attribute = (LdapAttribute) policy.parse(line); - - assertThat(id.equalsIgnoreCase(attribute.getID())).as("IDs do not match: [expected: " + attribute.getID() + ", obtained: " + id + "]").isTrue(); - - String[] expected = !StringUtils.hasLength(options) ? new String[] {} : options.replaceFirst(";","").split(";"); + + assertThat(id.equalsIgnoreCase(attribute.getID())) + .as("IDs do not match: [expected: " + attribute.getID() + ", obtained: " + id + "]").isTrue(); + + String[] expected = !StringUtils.hasLength(options) ? new String[] {} + : options.replaceFirst(";", "").split(";"); Arrays.sort(expected); String[] obtained = attribute.getOptions().toArray(new String[] {}); Arrays.sort(obtained); assertThat(obtained).as("Options do not match: ").isEqualTo(expected); - - switch(type) { + + switch (type) { case STRING: assertThat(attribute.get() instanceof String).as("Value is not a string.").isTrue(); assertThat(attribute.get()).as("Values do not match: ").isEqualTo(value); break; - + case BASE64: byte[] bytes = LdapEncoder.parseBase64Binary(value); assertThat(attribute.get() instanceof byte[]).as("Value is not a byte[].").isTrue(); assertThat((byte[]) attribute.get()).as("Values do not match: ").isEqualTo(bytes); break; - + case URL: - URI url = new URI(value); + URI url = new URI(value); assertThat(attribute.get() instanceof URI).as("Value is not a URL.").isTrue(); assertThat(attribute.get()).as("Values do not match: ").isEqualTo(url); break; - + case UTF8: assertThat(attribute.get() instanceof String).as("Value is not a UTF8.").isTrue(); assertThat(attribute.get()).as("Values do not match: ").isEqualTo(value); break; } - + log.info("Success!"); - - } catch (Exception e) { + + } + catch (Exception e) { if (!exceptions.contains(line)) fail("Exception thrown: " + e.getClass().getSimpleName() + " (message: " + e.getMessage() + ")"); } } + } diff --git a/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/Ldap233LdifParserTest.java b/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/Ldap233LdifParserTest.java index 11a8cad1..dfb64a3f 100644 --- a/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/Ldap233LdifParserTest.java +++ b/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/Ldap233LdifParserTest.java @@ -33,7 +33,6 @@ public class Ldap233LdifParserTest { /** * This previously went into endless loop. - * * @throws IOException */ @Test diff --git a/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/LdifParserTest.java b/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/LdifParserTest.java index 611cb27d..3ae7abb1 100644 --- a/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/LdifParserTest.java +++ b/ldif/ldif-core/src/test/java/org/springframework/ldap/ldif/LdifParserTest.java @@ -34,16 +34,14 @@ import static org.assertj.core.api.Assertions.fail; /** * Unit test for LdifParser. * - * Test results in complete end to end test of all LdifParser functionality: - * 1.) Open a file - * 2.) Read lines and compose an attribute. - * 3.) Parse the attribute and create a LdapAttribute object. - * 4.) Repeat until end of record (Identify end of record). - * 5.) Return a valid LdapAttributes object. - * 6.) Close file upon completion. + * Test results in complete end to end test of all LdifParser functionality: 1.) Open a + * file 2.) Read lines and compose an attribute. 3.) Parse the attribute and create a + * LdapAttribute object. 4.) Repeat until end of record (Identify end of record). 5.) + * Return a valid LdapAttributes object. 6.) Close file upon completion. * - * Provided test file is comprised of sample LDIFs from RFC2849 and exhausts the full range of - * the functionality prescribed by RFC2849 for the LDAP Data Interchange Format (LDIF). + * Provided test file is comprised of sample LDIFs from RFC2849 and exhausts the full + * range of the functionality prescribed by RFC2849 for the LDAP Data Interchange Format + * (LDIF). * * @author Keith Barlow * @@ -55,9 +53,9 @@ public class LdifParserTest { private LdifParser parser; /** - * Default constructor: loads a preselected resource with sample LDIF entries. - * Each entry is parsed and checked for a DN and objectclass. Output is printed for visual verification - * of LDIF correctness. + * Default constructor: loads a preselected resource with sample LDIF entries. Each + * entry is parsed and checked for a DN and objectclass. Output is printed for visual + * verification of LDIF correctness. */ public LdifParserTest() { parser = new LdifParser(new ClassPathResource("test.ldif")); @@ -71,13 +69,15 @@ public class LdifParserTest { public void openLdif() { try { parser.open(); - } catch (IOException e) { + } + catch (IOException e) { fail(e.getMessage()); } } /** - * Executes test: reads all records from LDIF file and validates an LdapAttributes object is successfully created. + * Executes test: reads all records from LDIF file and validates an LdapAttributes + * object is successfully created. */ @Test public void parseLdif() { @@ -95,7 +95,8 @@ public class LdifParserTest { assertThat(attributes.get("objectclass") != null).isTrue(); count++; } - } catch (InvalidAttributeFormatException e) { + } + catch (InvalidAttributeFormatException e) { log.error("Invalid attribute", e); if (count != 6) { fail(e.getMessage()); @@ -106,11 +107,13 @@ public class LdifParserTest { } log.info("record count: " + count); - //assertThat(count == 8).as("An incorrect number of records were parsed.").isTrue(); + // assertThat(count == 8).as("An incorrect number of records were + // parsed.").isTrue(); log.info("Done!"); - } catch (IOException e) { + } + catch (IOException e) { fail(e.getMessage()); } } @@ -122,8 +125,10 @@ public class LdifParserTest { public void closeLdif() { try { parser.close(); - } catch (IOException e) { + } + catch (IOException e) { fail(e.getMessage()); } } + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/core/OdmManager.java b/odm/src/main/java/org/springframework/ldap/odm/core/OdmManager.java index 8c1d4056..2bd82ae9 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/core/OdmManager.java +++ b/odm/src/main/java/org/springframework/ldap/odm/core/OdmManager.java @@ -23,110 +23,99 @@ import javax.naming.directory.SearchControls; import java.util.List; /** - * The OdmManager interface provides generic CRUD (create/read/update/delete) - * and searching operations against an LDAP directory. + * The OdmManager interface provides generic CRUD (create/read/update/delete) and + * searching operations against an LDAP directory. *

    * Each managed Java class must be appropriately annotated using - * {@link org.springframework.ldap.odm.annotations}. - * + * {@link org.springframework.ldap.odm.annotations}. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> * @author Mattias Hellborg Arthursson - * * @see org.springframework.ldap.odm.annotations.Entry * @see org.springframework.ldap.odm.annotations.Attribute * @see org.springframework.ldap.odm.annotations.Id * @see org.springframework.ldap.odm.annotations.Transient - * @deprecated This functionality is automatically available in LdapTemplate as of version 2.0 + * @deprecated This functionality is automatically available in LdapTemplate as of version + * 2.0 */ -public interface OdmManager { - - +public interface OdmManager { + /** * Read a named entry from the LDAP directory. - * * @param The Java type to return * @param clazz The Java type to return * @param dn The distinguished name of the entry to read from the LDAP directory. * @return The entry as read from the directory - * * @throws org.springframework.ldap.NamingException on error. */ T read(Class clazz, Name dn); /** * Create the given entry in the LDAP directory. - * - * @param entry The entry to be create, it must not already exist in the directory. - * + * @param entry The entry to be create, it must not already exist in the + * directory. * @throws org.springframework.ldap.NamingException on error. */ void create(Object entry); /** * Update the given entry in the LDAP directory. - * * @param entry The entry to update, it must already exist in the directory. - * * @throws org.springframework.ldap.NamingException on error. */ void update(Object entry); /** * Delete an entry from the LDAP directory. - * * @param entry The entry to delete, it must already exist in the directory. - * * @throws org.springframework.ldap.NamingException on error. */ void delete(Object entry); /** * Find all entries in the LDAP directory of a given type. - * * @param The Java type to return * @param clazz The Java type to return * @param base The root of the sub-tree at which to begin the search. * @param searchControls The scope of the search. - * @return All entries that are of the type represented by the given - * Java class - * + * @return All entries that are of the type represented by the given Java class * @throws org.springframework.ldap.NamingException on error. */ List findAll(Class clazz, Name base, SearchControls searchControls); /** - * Search for entries in the LDAP directory. + * Search for entries in the LDAP directory. *

    - * Only those entries that both match the given search filter and - * are represented by the given Java class are returned - * + * Only those entries that both match the given search filter and are represented by + * the given Java class are returned * @param The Java type to return * @param clazz The Java type to return * @param base The root of the sub-tree at which to begin the search. - * @param filter An LDAP search filter. + * @param filter An LDAP search filter. * @param searchControls The scope of the search. * @return All matching entries. - * * @throws org.springframework.ldap.NamingException on error. - * - * @see Sun's JNDI tutorial description of search filters. - * @see LDAP: String Representation of Search Filters RFC. + * + * @see Sun's + * JNDI tutorial description of search filters. + * @see LDAP: String + * Representation of Search Filters RFC. */ List search(Class clazz, Name base, String filter, SearchControls searchControls); /** * Search for entries in the LDAP directory. *

    - * Only those entries that both match the query search filter and - * are represented by the given Java class are returned. - * + * Only those entries that both match the query search filter and are represented by + * the given Java class are returned. * @param The Java type to return * @param clazz The Java type to return * @param query the LDAP query specification * @return All matching entries. - * * @throws org.springframework.ldap.NamingException on error. * @see org.springframework.ldap.query.LdapQueryBuilder */ List search(Class clazz, LdapQuery query); + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/core/impl/OdmManagerImpl.java b/odm/src/main/java/org/springframework/ldap/odm/core/impl/OdmManagerImpl.java index a29f1960..57c0504f 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/core/impl/OdmManagerImpl.java +++ b/odm/src/main/java/org/springframework/ldap/odm/core/impl/OdmManagerImpl.java @@ -32,32 +32,33 @@ import java.util.List; import java.util.Set; /** - * An implementation of {@link org.springframework.ldap.odm.core.OdmManager} which - * uses {@link org.springframework.ldap.odm.typeconversion.ConverterManager} to - * convert between Java and LDAP representations of attribute values. - * + * An implementation of {@link org.springframework.ldap.odm.core.OdmManager} which uses + * {@link org.springframework.ldap.odm.typeconversion.ConverterManager} to convert between + * Java and LDAP representations of attribute values. + * * @author Paul Harvey <paul.at.pauls-place.me.uk> * @author Mattias Hellborg Arthursson - * @deprecated This functionality is automatically available in LdapTemplate as of version 2.0 + * @deprecated This functionality is automatically available in LdapTemplate as of version + * 2.0 */ public final class OdmManagerImpl implements OdmManager { + // The link to the LDAP directory private final LdapTemplate ldapTemplate; private DefaultObjectDirectoryMapper objectDirectoryMapper; - public OdmManagerImpl(ConverterManager converterManager, - LdapOperations ldapOperations, - Set> managedClasses) { - this.ldapTemplate = (LdapTemplate)ldapOperations; + public OdmManagerImpl(ConverterManager converterManager, LdapOperations ldapOperations, + Set> managedClasses) { + this.ldapTemplate = (LdapTemplate) ldapOperations; objectDirectoryMapper = new DefaultObjectDirectoryMapper(); - if(converterManager != null) { + if (converterManager != null) { objectDirectoryMapper.setConverterManager(converterManager); } - if (managedClasses!=null) { - for (Class managedClass: managedClasses) { + if (managedClasses != null) { + for (Class managedClass : managedClasses) { addManagedClass(managedClass); } } @@ -65,21 +66,18 @@ public final class OdmManagerImpl implements OdmManager { this.ldapTemplate.setObjectDirectoryMapper(objectDirectoryMapper); } - public OdmManagerImpl(ConverterManager converterManager, - ContextSource contextSource, - Set> managedClasses) { + public OdmManagerImpl(ConverterManager converterManager, ContextSource contextSource, + Set> managedClasses) { this(converterManager, new LdapTemplate(contextSource), managedClasses); } - - public OdmManagerImpl(ConverterManager converterManager, - ContextSource contextSource) { + + public OdmManagerImpl(ConverterManager converterManager, ContextSource contextSource) { this(converterManager, contextSource, null); } /** * Adds an {@link org.springframework.ldap.odm.annotations} annotated class to the set * managed by this OdmManager. - * * @param managedClass The class to add to the managed set. */ public void addManagedClass(Class managedClass) { @@ -88,7 +86,7 @@ public final class OdmManagerImpl implements OdmManager { /* * (non-Javadoc) - * + * * @see org.springframework.ldap.odm.core.OdmManager#create(java.lang.Object) */ public T read(Class clazz, Name dn) { @@ -97,7 +95,7 @@ public final class OdmManagerImpl implements OdmManager { /* * (non-Javadoc) - * + * * @see org.springframework.ldap.odm.core.OdmManager#create(java.lang.Object) */ public void create(Object entry) { @@ -106,7 +104,7 @@ public final class OdmManagerImpl implements OdmManager { /* * (non-Javadoc) - * + * * @see org.springframework.ldap.odm.core.OdmManager#update(java.lang.Object, boolean) */ public void update(Object entry) { @@ -115,19 +113,22 @@ public final class OdmManagerImpl implements OdmManager { /* * (non-Javadoc) - * + * * @see org.springframework.ldap.odm.core.OdmManager#delete(javax.naming.Name) */ public void delete(Object entry) { ldapTemplate.delete(entry); } - /* (non-Javadoc) - * @see org.springframework.ldap.odm.core.OdmManager#search(java.lang.Class, javax.naming.Name, java.lang.String, javax.naming.directory.SearchControls) + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.odm.core.OdmManager#search(java.lang.Class, + * javax.naming.Name, java.lang.String, javax.naming.directory.SearchControls) */ public List search(Class managedClass, Name base, String filter, SearchControls scope) { Filter searchFilter = null; - if(StringUtils.hasText(filter)) { + if (StringUtils.hasText(filter)) { searchFilter = new HardcodedFilter(filter); } @@ -142,4 +143,5 @@ public final class OdmManagerImpl implements OdmManager { public List findAll(Class managedClass, Name base, SearchControls scope) { return ldapTemplate.findAll(base, scope, managedClass); } + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/core/impl/OdmManagerImplFactoryBean.java b/odm/src/main/java/org/springframework/ldap/odm/core/impl/OdmManagerImplFactoryBean.java index 22bea03a..9d68f483 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/core/impl/OdmManagerImplFactoryBean.java +++ b/odm/src/main/java/org/springframework/ldap/odm/core/impl/OdmManagerImplFactoryBean.java @@ -28,8 +28,7 @@ import java.util.Set; /** * A Spring Factory bean which creates {@link OdmManagerImpl} instances. *

    - * Typical configuration would appear as follows: - *

    + * Typical configuration would appear as follows: 
      *   <bean id="odmManager" class="org.springframework.ldap.odm.core.impl.OdmManagerImplFactoryBean">
      *	   <property name="converterManager" ref="converterManager" />
      *	   <property name="contextSource" ref="contextSource" />
    @@ -41,18 +40,21 @@ import java.util.Set;
      *	   </property>
      *   </bean>
      * 
    - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> - * @deprecated This functionality is automatically available in LdapTemplate as of version 2.0 + * @deprecated This functionality is automatically available in LdapTemplate as of version + * 2.0 */ public final class OdmManagerImplFactoryBean implements FactoryBean { + private LdapOperations ldapOperations = null; - private Set> managedClasses=null; - private ConverterManager converterManager=null; + + private Set> managedClasses = null; + + private ConverterManager converterManager = null; /** * Set the LdapOperations instance to use to interact with the LDAP directory. - * * @param ldapOperations the LdapOperations instance to use. */ public void setLdapOperations(LdapOperations ldapOperations) { @@ -66,53 +68,60 @@ public final class OdmManagerImplFactoryBean implements FactoryBean { public void setContextSource(ContextSource contextSource) { this.ldapOperations = new LdapTemplate(contextSource); } - + /** - * Set the list of {@link org.springframework.ldap.odm.annotations} - * annotated classes the OdmManager will process. + * Set the list of {@link org.springframework.ldap.odm.annotations} annotated classes + * the OdmManager will process. * @param managedClasses The list of classes to manage. */ public void setManagedClasses(Set> managedClasses) { - this.managedClasses=managedClasses; + this.managedClasses = managedClasses; } - + /** - * Set the ConverterManager to use to convert between LDAP - * and Java representations of attributes. + * Set the ConverterManager to use to convert between LDAP and Java representations of + * attributes. * @param converterManager The ConverterManager to use. */ public void setConverterManager(ConverterManager converterManager) { - this.converterManager=converterManager; + this.converterManager = converterManager; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.springframework.beans.factory.FactoryBean#getObject() */ public Object getObject() throws Exception { - if (ldapOperations==null) { + if (ldapOperations == null) { throw new FactoryBeanNotInitializedException("contextSource ldapOperations property has not been set"); } - if (managedClasses==null) { + if (managedClasses == null) { throw new FactoryBeanNotInitializedException("managedClasses property has not been set"); } - if (converterManager==null) { + if (converterManager == null) { throw new FactoryBeanNotInitializedException("converterManager property has not been set"); } - + return new OdmManagerImpl(converterManager, ldapOperations, managedClasses); } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.springframework.beans.factory.FactoryBean#getObjectType() */ public Class getObjectType() { return OdmManagerImpl.class; } - /* (non-Javadoc) + /* + * (non-Javadoc) + * * @see org.springframework.beans.factory.FactoryBean#isSingleton() */ public boolean isSingleton() { return true; } + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/tools/AttributeSchema.java b/odm/src/main/java/org/springframework/ldap/odm/tools/AttributeSchema.java index 2ce9b9ac..2a6a58f8 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/tools/AttributeSchema.java +++ b/odm/src/main/java/org/springframework/ldap/odm/tools/AttributeSchema.java @@ -19,14 +19,14 @@ package org.springframework.ldap.odm.tools; import org.springframework.util.StringUtils; /** - * Simple value class to hold the schema of an attribute. + * Simple value class to hold the schema of an attribute. *

    * It is only public to allow Freemarker access. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public final class AttributeSchema { - + private final String name; private final String syntax; @@ -55,7 +55,7 @@ public final class AttributeSchema { public boolean getIsArray() { return isArray; } - + public boolean getIsBinary() { return isBinary; } @@ -86,7 +86,7 @@ public final class AttributeSchema { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override @@ -96,7 +96,7 @@ public final class AttributeSchema { "{ name=%1$s, syntax=%2$s, isMultiValued=%3$s, isPrimitive=%4$s, isBinary=%5$s, isArray=%6$s, scalarType=%7$s }", name, syntax, isMultiValued, isPrimitive, isBinary, isArray, scalarType); } - + @Override public int hashCode() { final int prime = 31; @@ -131,17 +131,20 @@ public final class AttributeSchema { if (name == null) { if (other.name != null) return false; - } else if (!name.equals(other.name)) + } + else if (!name.equals(other.name)) return false; if (scalarType == null) { if (other.scalarType != null) return false; - } else if (!scalarType.equals(other.scalarType)) + } + else if (!scalarType.equals(other.scalarType)) return false; if (syntax == null) { if (other.syntax != null) return false; - } else if (!syntax.equals(other.syntax)) + } + else if (!syntax.equals(other.syntax)) return false; return true; } diff --git a/odm/src/main/java/org/springframework/ldap/odm/tools/ObjectSchema.java b/odm/src/main/java/org/springframework/ldap/odm/tools/ObjectSchema.java index e0b5f557..f44dab68 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/tools/ObjectSchema.java +++ b/odm/src/main/java/org/springframework/ldap/odm/tools/ObjectSchema.java @@ -24,10 +24,11 @@ import java.util.Set; * Simple value class to hold the schema of an object class *

    * It is public only to allow Freemarker access. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public final class ObjectSchema { + private final Set must = new HashSet(); private final Set may = new HashSet(); @@ -67,7 +68,7 @@ public final class ObjectSchema { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override @@ -97,18 +98,22 @@ public final class ObjectSchema { if (may == null) { if (other.may != null) return false; - } else if (!may.equals(other.may)) + } + else if (!may.equals(other.may)) return false; if (must == null) { if (other.must != null) return false; - } else if (!must.equals(other.must)) + } + else if (!must.equals(other.must)) return false; if (objectClass == null) { if (other.objectClass != null) return false; - } else if (!objectClass.equals(other.objectClass)) + } + else if (!objectClass.equals(other.objectClass)) return false; return true; } + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaReader.java b/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaReader.java index 89bcde86..a4ad4e46 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaReader.java +++ b/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaReader.java @@ -28,6 +28,7 @@ import java.util.Set; // Processes LDAP Schema /* package */ final class SchemaReader { + private final DirContext schemaContext; private final SyntaxToJavaClass syntaxToJavaClass; @@ -41,16 +42,17 @@ import java.util.Set; } // Get the object schema for the given object classes - public ObjectSchema getObjectSchema(Set objectClasses) - throws NamingException, ClassNotFoundException { - + public ObjectSchema getObjectSchema(Set objectClasses) throws NamingException, ClassNotFoundException { + ObjectSchema result = new ObjectSchema(); createObjectClass(objectClasses, schemaContext, result); return result; } private enum SchemaAttributeType { + SUP, MUST, MAY, UNKNOWN + } private SchemaAttributeType getSchemaAttributeType(String type) { @@ -58,10 +60,12 @@ import java.util.Set; if (type.equals("SUP")) { result = SchemaAttributeType.SUP; - } else { + } + else { if (type.equals("MUST")) { result = SchemaAttributeType.MUST; - } else { + } + else { if (type.equals("MAY")) { result = SchemaAttributeType.MAY; } @@ -71,31 +75,33 @@ import java.util.Set; } private AttributeSchema createAttributeSchema(String name, DirContext schemaContext) - throws NamingException, ClassNotFoundException { - + throws NamingException, ClassNotFoundException { + // Get the schema definition Attributes attributeSchema = schemaContext.getAttributes("AttributeDefinition/" + name); String syntax = null; - while(syntax == null) { + while (syntax == null) { Attribute syntaxAttribute = attributeSchema.get("SYNTAX"); - if(syntaxAttribute != null) { - syntax = ((String)syntaxAttribute.get()).split("\\{")[0]; - } else { + if (syntaxAttribute != null) { + syntax = ((String) syntaxAttribute.get()).split("\\{")[0]; + } + else { // Try to recursively retrieve syntax for super definition. Attribute supAttribute = attributeSchema.get("SUP"); - if(supAttribute == null) { + if (supAttribute == null) { // Well, at least we tried throw new IllegalArgumentException("Unable to get syntax definition for attribute " + name); - } else { + } + else { attributeSchema = schemaContext.getAttributes("AttributeDefinition/" + supAttribute.get()); } } } // Is it binary? - boolean isBinary=binarySet.contains(syntax); - + boolean isBinary = binarySet.contains(syntax); + // Use it to look up the required Java class ClassInfo classInfo = syntaxToJavaClass.getClassInfo(syntax); @@ -103,28 +109,29 @@ import java.util.Set; String javaClassName = null; boolean isPrimitive = false; boolean isArray = false; - - if (classInfo!=null) { - javaClassName=classInfo.getClassName(); - Class javaClass=Class.forName(classInfo.getFullClassName()); - javaClassName=javaClass.getSimpleName(); - isPrimitive=javaClass.isPrimitive(); - isArray=javaClass.isArray(); - } else { + + if (classInfo != null) { + javaClassName = classInfo.getClassName(); + Class javaClass = Class.forName(classInfo.getFullClassName()); + javaClassName = javaClass.getSimpleName(); + isPrimitive = javaClass.isPrimitive(); + isArray = javaClass.isArray(); + } + else { if (isBinary) { - javaClassName="byte[]"; - isPrimitive=false; - isArray=true; - } else { - javaClassName="String"; - isPrimitive=false; - isArray=false; + javaClassName = "byte[]"; + isPrimitive = false; + isArray = true; + } + else { + javaClassName = "String"; + isPrimitive = false; + isArray = false; } } - - return new AttributeSchema(name, syntax, - attributeSchema.get("SINGLE-VALUE") == null, - isPrimitive, isBinary, isArray, javaClassName); + + return new AttributeSchema(name, syntax, attributeSchema.get("SINGLE-VALUE") == null, isPrimitive, isBinary, + isArray, javaClassName); } // Recursively extract schema from the directory and process it @@ -138,7 +145,7 @@ import java.util.Set; for (String objectClass : objectClasses) { // Add to set of included object classes schema.addObjectClass(objectClass); - + // Grab the LDAP schema of the object class Attributes attributes = schemaContext.getAttributes("ClassDefinition/" + objectClass); NamingEnumeration valuesEnumeration = attributes.getAll(); @@ -149,32 +156,32 @@ import java.util.Set; // Get the attribute name and lower case it (as this is all case indep) String currentId = currentAttribute.getID().toUpperCase(); - + // Is this a MUST, MAY or SUP attribute SchemaAttributeType type = getSchemaAttributeType(currentId); // Loop through all the values NamingEnumeration currentValues = currentAttribute.getAll(); while (currentValues.hasMoreElements()) { - String currentValue = (String)currentValues.nextElement(); + String currentValue = (String) currentValues.nextElement(); switch (type) { - case SUP: - // Its a super class - String lowerCased=currentValue.toLowerCase(); - if (!schema.getObjectClass().contains(lowerCased)) { - supList.add(lowerCased); - } - break; - case MUST: - // Add must attribute - schema.addMust(createAttributeSchema(currentValue, schemaContext)); - break; - case MAY: - // Add may attribute - schema.addMay(createAttributeSchema(currentValue, schemaContext)); - break; - default: - // Nothing to do + case SUP: + // Its a super class + String lowerCased = currentValue.toLowerCase(); + if (!schema.getObjectClass().contains(lowerCased)) { + supList.add(lowerCased); + } + break; + case MUST: + // Add must attribute + schema.addMust(createAttributeSchema(currentValue, schemaContext)); + break; + case MAY: + // Add may attribute + schema.addMay(createAttributeSchema(currentValue, schemaContext)); + break; + default: + // Nothing to do } } } @@ -183,4 +190,5 @@ import java.util.Set; createObjectClass(supList, schemaContext, schema); } } + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaToJava.java b/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaToJava.java index 0ea71415..b7917678 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaToJava.java +++ b/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaToJava.java @@ -50,18 +50,17 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; /** - * This tool creates a Java class representation of a set of LDAP object classes for use + * This tool creates a Java class representation of a set of LDAP object classes for use * with {@link org.springframework.ldap.odm.core.OdmManager}. *

    - * The schema of a named list of object classes is read from an LDAP directory and used - * to generate a representative Java class. The Java class is automatically annotated with - * {@link org.springframework.ldap.odm.annotations} for use with + * The schema of a named list of object classes is read from an LDAP directory and used to + * generate a representative Java class. The Java class is automatically annotated with + * {@link org.springframework.ldap.odm.annotations} for use with * {@link org.springframework.ldap.odm.core.OdmManager}. *

    - * The mapping of LDAP attributes to their Java representations may be configured by supplying the - * -s flag or the equivalent --syntaxmap flag whose argument is - * the name of a file with the following structure: - *

    + * The mapping of LDAP attributes to their Java representations may be configured by
    + * supplying the -s flag or the equivalent --syntaxmap flag
    + * whose argument is the name of a file with the following structure: 
      * # List of attribute syntax to java class mappings
      *
      * # Syntax					   Java class
    @@ -71,52 +70,57 @@ import java.util.regex.Pattern;
      * 1.3.6.1.4.1.1466.115.121.1.40, some.other.Class
      * 
    *

    - * Syntaxes not included in this map will be represented as {@link java.lang.String} if they are returned as Strings by the - * JNDI LDAP provider and will be represented as byte[] if they are returned by the provider as byte[]. + * Syntaxes not included in this map will be represented as {@link java.lang.String} if + * they are returned as Strings by the JNDI LDAP provider and will be represented as + * byte[] if they are returned by the provider as byte[]. *

    * Command line flags are as follows: *

    *

      - *
    • -c,--class <class name> Name of the Java class to create. Mandatory.
    • - *
    • -s,--syntaxmap <map file> Configuration file of LDAP syntaxes to Java classes mappings. Optional.
    • - *
    • -h,--help Print this help message then exit.
    • - *
    • -k,--package <package name> Package to create the Java class in. Mandatory.
    • - *
    • -l,--url <ldap url> Ldap url of the directory service to bind to. Defaults to ldap://127.0.0.1:389. Optional.
    • - *
    • -o,--objectclasses <LDAP object class lists> Comma separated list of LDAP object classes. Mandatory.
    • - *
    • -u,--username <dn> DN to bind with. Defaults to "". Optional.
    • - *
    • -p,--password <password> Password to bind with. Defaults to "". Optional.
    • - *
    • -t,--outputdir <output directory> Base output directory, defaults to ".". Optional.
    • + *
    • -c,--class <class name> Name of the Java class to create. + * Mandatory.
    • + *
    • -s,--syntaxmap <map file> Configuration file of LDAP syntaxes to + * Java classes mappings. Optional.
    • + *
    • -h,--help Print this help message then exit.
    • + *
    • -k,--package <package name> Package to create the Java class in. + * Mandatory.
    • + *
    • -l,--url <ldap url> Ldap url of the directory service to bind + * to. Defaults to ldap://127.0.0.1:389. Optional.
    • + *
    • -o,--objectclasses <LDAP object class lists> Comma separated + * list of LDAP object classes. Mandatory.
    • + *
    • -u,--username <dn> DN to bind with. Defaults to "". + * Optional.
    • + *
    • -p,--password <password> Password to bind with. Defaults to "". + * Optional.
    • + *
    • -t,--outputdir <output directory> Base output directory, + * defaults to ".". Optional.
    • *
    - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public final class SchemaToJava { + private static final Logger LOG = LoggerFactory.getLogger(SchemaToJava.class); // Name of the FreeMarker template used to generate the Java code. private static final String TEMPLATE_FILE = "oc-to-java.ftl"; - - // Name of file containing the list of attributes syntaxes to + + // Name of file containing the list of attributes syntaxes to // returned as byte[] by the JNDI LDAP provider. private static final String BINARY_FILE = "binary-attributes.txt"; - + // Class to use a base for loading resources - private static final Class DEFAULT_LOADER_CLASS =SchemaToJava.class; - + private static final Class DEFAULT_LOADER_CLASS = SchemaToJava.class; + // Default LDAP Url to bind with - private static final String DEFAULT_URL="ldap://127.0.0.1:389"; - + private static final String DEFAULT_URL = "ldap://127.0.0.1:389"; + // Command line flags private enum Flag { - URL("l", "url"), - USERNAME("u", "username"), - PASSWORD("p", "password"), - OBJECTCLASS("o", "objectclasses"), - CLASS("c", "class"), - PACKAGE("k", "package"), - SYNTAX_MAP("s", "syntaxmap"), - OUTPUT_DIR("t", "outputdir"), - HELP("h", "help"); + + URL("l", "url"), USERNAME("u", "username"), PASSWORD("p", "password"), OBJECTCLASS("o", "objectclasses"), CLASS( + "c", "class"), PACKAGE("k", + "package"), SYNTAX_MAP("s", "syntaxmap"), OUTPUT_DIR("t", "outputdir"), HELP("h", "help"); private String shortName; @@ -139,18 +143,27 @@ public final class SchemaToJava { public String toString() { return String.format("short=%1$s, long=%2$s", shortName, longName); } + } private static final Options DEFAULT_OPTIONS = new Options(); static { - DEFAULT_OPTIONS.addOption(Flag.URL.getShort(), Flag.URL.getLong(), true, "Ldap url (defaults to " + DEFAULT_URL + ")"); - DEFAULT_OPTIONS.addOption(Flag.USERNAME.getShort(), Flag.USERNAME.getLong(), true, "DN to bind with (defaults to \"\""); - DEFAULT_OPTIONS.addOption(Flag.PASSWORD.getShort(), Flag.PASSWORD.getLong(), true, "Password to bind with (defaults to \"\""); - DEFAULT_OPTIONS.addOption(Flag.OBJECTCLASS.getShort(), Flag.OBJECTCLASS.getLong(), true, "Comma separated list of object classes"); - DEFAULT_OPTIONS.addOption(Flag.CLASS.getShort(), Flag.CLASS.getLong(), true, "Name of the Java class to create"); - DEFAULT_OPTIONS.addOption(Flag.PACKAGE.getShort(), Flag.PACKAGE.getLong(), true, "Package to create the Java class in"); - DEFAULT_OPTIONS.addOption(Flag.SYNTAX_MAP.getShort(), Flag.SYNTAX_MAP.getLong(), true, "Syntax map file (optional)"); - DEFAULT_OPTIONS.addOption(Flag.OUTPUT_DIR.getShort(), Flag.OUTPUT_DIR.getLong(), true, "Base output directory (defaults to .)"); + DEFAULT_OPTIONS.addOption(Flag.URL.getShort(), Flag.URL.getLong(), true, + "Ldap url (defaults to " + DEFAULT_URL + ")"); + DEFAULT_OPTIONS.addOption(Flag.USERNAME.getShort(), Flag.USERNAME.getLong(), true, + "DN to bind with (defaults to \"\""); + DEFAULT_OPTIONS.addOption(Flag.PASSWORD.getShort(), Flag.PASSWORD.getLong(), true, + "Password to bind with (defaults to \"\""); + DEFAULT_OPTIONS.addOption(Flag.OBJECTCLASS.getShort(), Flag.OBJECTCLASS.getLong(), true, + "Comma separated list of object classes"); + DEFAULT_OPTIONS.addOption(Flag.CLASS.getShort(), Flag.CLASS.getLong(), true, + "Name of the Java class to create"); + DEFAULT_OPTIONS.addOption(Flag.PACKAGE.getShort(), Flag.PACKAGE.getLong(), true, + "Package to create the Java class in"); + DEFAULT_OPTIONS.addOption(Flag.SYNTAX_MAP.getShort(), Flag.SYNTAX_MAP.getLong(), true, + "Syntax map file (optional)"); + DEFAULT_OPTIONS.addOption(Flag.OUTPUT_DIR.getShort(), Flag.OUTPUT_DIR.getLong(), true, + "Base output directory (defaults to .)"); DEFAULT_OPTIONS.addOption(Flag.HELP.getShort(), Flag.HELP.getLong(), false, "Print this help message"); } @@ -161,10 +174,9 @@ public final class SchemaToJava { } - // Read list of LDAP syntaxes that are returned as byte[] - private static Set readBinarySet(File binarySetFile) - throws IOException { - + // Read list of LDAP syntaxes that are returned as byte[] + private static Set readBinarySet(File binarySetFile) throws IOException { + Set result = new HashSet(); BufferedReader reader = null; @@ -182,7 +194,8 @@ public final class SchemaToJava { } } } - } finally { + } + finally { if (reader != null) { reader.close(); } @@ -192,9 +205,8 @@ public final class SchemaToJava { } // Read mappings of LDAP syntaxes to Java classes. - private static Map readSyntaxMap(File syntaxMapFile) - throws IOException { - + private static Map readSyntaxMap(File syntaxMapFile) throws IOException { + Map result = new HashMap(); BufferedReader reader = null; @@ -207,20 +219,19 @@ public final class SchemaToJava { if (trimmed.charAt(0) != '#') { String[] parts = trimmed.split(","); if (parts.length != 2) { - throw new IOException(String.format("Failed to parse line \"%1$s\"", - trimmed)); + throw new IOException(String.format("Failed to parse line \"%1$s\"", trimmed)); } String partOne = parts[0].trim(); String partTwo = parts[1].trim(); if (partOne.length() == 0 || partTwo.length() == 0) { - throw new IOException(String.format("Failed to parse line \"%1$s\"", - trimmed)); + throw new IOException(String.format("Failed to parse line \"%1$s\"", trimmed)); } result.put(partOne, partTwo); } } } - } finally { + } + finally { if (reader != null) { reader.close(); } @@ -230,11 +241,10 @@ public final class SchemaToJava { } // Bind to the directory, read and process the schema - private static ObjectSchema readSchema(String url, String user, String pass, - SyntaxToJavaClass syntaxToJavaClass, Set binarySet, Set objectClasses) - throws NamingException, ClassNotFoundException { - - // Set up environment + private static ObjectSchema readSchema(String url, String user, String pass, SyntaxToJavaClass syntaxToJavaClass, + Set binarySet, Set objectClasses) throws NamingException, ClassNotFoundException { + + // Set up environment Hashtable env = new Hashtable(); env.put(Context.PROVIDER_URL, url); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); @@ -249,19 +259,18 @@ public final class SchemaToJava { DirContext schemaContext = context.getSchema(""); SchemaReader reader = new SchemaReader(schemaContext, syntaxToJavaClass, binarySet); ObjectSchema schema = reader.getObjectSchema(objectClasses); - + if (LOG.isDebugEnabled()) { LOG.debug(String.format("Schema - %1$s", schema.toString())); } - - return schema; + + return schema; } - + // Create the Java - private static void createCode(String packageName, - String className, ObjectSchema schema, Set imports, File outputFile) - throws IOException, TemplateException { - + private static void createCode(String packageName, String className, ObjectSchema schema, + Set imports, File outputFile) throws IOException, TemplateException { + Configuration freeMarkerConfiguration = new Configuration(); freeMarkerConfiguration.setClassForTemplateLoading(DEFAULT_LOADER_CLASS, ""); @@ -272,57 +281,59 @@ public final class SchemaToJava { model.put("package", packageName); model.put("class", className); model.put("schema", schema); - model.put("imports", imports); - + model.put("imports", imports); + // Have FreeMarker process the model with the template Template template = freeMarkerConfiguration.getTemplate(TEMPLATE_FILE); - + if (LOG.isDebugEnabled()) { Writer out = new OutputStreamWriter(System.out); template.process(model, out); out.flush(); } - + LOG.debug(String.format("Writing java to: %1$s", outputFile.getAbsolutePath())); - - FileOutputStream outputStream=new FileOutputStream(outputFile); + + FileOutputStream outputStream = new FileOutputStream(outputFile); Writer out = new OutputStreamWriter(outputStream); template.process(model, out); - out.flush(); - out.close(); + out.flush(); + out.close(); } - - // Create the output file for the generated code along with all intervening directories - private static File makeOutputFile(String outputDir, String packageName, String className) - throws IOException { - + + // Create the output file for the generated code along with all intervening + // directories + private static File makeOutputFile(String outputDir, String packageName, String className) throws IOException { + // Convert the package name to a path - Pattern pattern=Pattern.compile("\\."); - Matcher matcher=pattern.matcher(packageName); - String sepToUse=File.separator; + Pattern pattern = Pattern.compile("\\."); + Matcher matcher = pattern.matcher(packageName); + String sepToUse = File.separator; if (sepToUse.equals("\\")) { - sepToUse="\\\\"; + sepToUse = "\\\\"; } // Try to create the necessary directories - String directoryPath=outputDir+File.separator+matcher.replaceAll(sepToUse); - File directory=new File(directoryPath); - File outputFile=new File(directory, className+".java"); - + String directoryPath = outputDir + File.separator + matcher.replaceAll(sepToUse); + File directory = new File(directoryPath); + File outputFile = new File(directory, className + ".java"); + LOG.debug(String.format("Attempting to create output file at %1$s", outputFile.getAbsolutePath())); - + try { directory.mkdirs(); outputFile.createNewFile(); - } catch (SecurityException se) { + } + catch (SecurityException se) { throw new IOException(String.format("Can't write to output file %1$s", outputFile.getAbsoluteFile()), se); - } catch (IOException ioe) { + } + catch (IOException ioe) { throw new IOException(String.format("Can't write to output file %1$s", outputFile.getAbsoluteFile()), ioe); } - + return outputFile; } - + private static Set parseObjectClassesFlag(String objectClassesFlag) { Set objectClasses = new HashSet(); @@ -334,12 +345,12 @@ public final class SchemaToJava { return objectClasses; } - + private static void error(String message) { System.err.println(String.format("%1$s: %2$s", SchemaToJava.class.getSimpleName(), message)); System.exit(1); } - + public static void main(String[] argv) { CommandLineParser parser = new PosixParser(); CommandLine cmd = null; @@ -347,97 +358,104 @@ public final class SchemaToJava { // Parse out the command line options try { cmd = parser.parse(DEFAULT_OPTIONS, argv); - } catch (ParseException e) { + } + catch (ParseException e) { error(e.toString()); } - // If the help flag is specified ignore other flags, print a usage message and exit + // If the help flag is specified ignore other flags, print a usage message and + // exit if (cmd.hasOption(Flag.HELP.getShort())) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, SchemaToJava.class.getSimpleName(), null, DEFAULT_OPTIONS, null, true); System.exit(0); } - + // Class name flag String className = cmd.getOptionValue(Flag.CLASS.getShort()); if (className == null) { error("You must specify the name of a Java class to create"); } - + // Package name flag String packageName = cmd.getOptionValue(Flag.PACKAGE.getShort()); if (packageName == null) { error("You must specifiy a package name"); } - - // Output base directory + + // Output base directory String outputDir = cmd.getOptionValue(Flag.OUTPUT_DIR.getShort(), "."); File outputFile = null; try { outputFile = makeOutputFile(outputDir, packageName, className); - } catch (IOException e) { + } + catch (IOException e) { error(e.toString()); } - + // Get the flags we need to bind to the directory String url = cmd.getOptionValue(Flag.URL.getShort(), DEFAULT_URL); String user = cmd.getOptionValue(Flag.USERNAME.getShort()); String pass = cmd.getOptionValue(Flag.PASSWORD.getShort()); - + // Parse out object classes String objectClassesFlag = cmd.getOptionValue(Flag.OBJECTCLASS.getShort()); - if (objectClassesFlag==null) { + if (objectClassesFlag == null) { error("You must specificy a package name"); } Set objectClasses = parseObjectClassesFlag(objectClassesFlag); - if (objectClasses.size()==0) { + if (objectClasses.size() == 0) { error("You must specificy a package name"); } // Look for the optional syntax to Java class mapping file String syntaxMapFileName = cmd.getOptionValue(Flag.SYNTAX_MAP.getShort(), null); - SyntaxToJavaClass syntaxToJavaClass=new SyntaxToJavaClass(new HashMap()); - if (syntaxMapFileName!=null) { - File syntaxMapFile=new File(syntaxMapFileName); + SyntaxToJavaClass syntaxToJavaClass = new SyntaxToJavaClass(new HashMap()); + if (syntaxMapFileName != null) { + File syntaxMapFile = new File(syntaxMapFileName); if (syntaxMapFile.canRead()) { try { syntaxToJavaClass = new SyntaxToJavaClass(readSyntaxMap(syntaxMapFile)); - } catch (IOException e) { - error(String.format("Error reading syntax map file %1$s - %2$s", - syntaxMapFile.getAbsolutePath(), e.toString())); } - } else { - error(String.format("Cannot read syntax map file %s$1", - syntaxMapFile.getAbsolutePath())); + catch (IOException e) { + error(String.format("Error reading syntax map file %1$s - %2$s", syntaxMapFile.getAbsolutePath(), + e.toString())); + } } - } - + else { + error(String.format("Cannot read syntax map file %s$1", syntaxMapFile.getAbsolutePath())); + } + } + // Read binary mapping file - URL binarySetUrl= DEFAULT_LOADER_CLASS.getResource(BINARY_FILE); - if (binarySetUrl==null) { + URL binarySetUrl = DEFAULT_LOADER_CLASS.getResource(BINARY_FILE); + if (binarySetUrl == null) { error(String.format("Can't locatate binary mappings file %1$s", BINARY_FILE)); } - File binarySetFile=new File(binarySetUrl.getFile()); + File binarySetFile = new File(binarySetUrl.getFile()); if (!binarySetFile.canRead()) { error(String.format("Can't read from binary mappings file %1$s", BINARY_FILE)); } Set binarySet = null; try { binarySet = readBinarySet(binarySetFile); - } catch (IOException e) { + } + catch (IOException e) { error(String.format("Error reading binary set file %1$s - %2$s", binarySetFile.getAbsolutePath(), e)); } - + // Read schema from the directory - ObjectSchema schema=null; + ObjectSchema schema = null; try { - schema=readSchema(url, user, pass, syntaxToJavaClass, binarySet, objectClasses); - } catch (NamingException ne) { + schema = readSchema(url, user, pass, syntaxToJavaClass, binarySet, objectClasses); + } + catch (NamingException ne) { error(String.format("Error processing schema - %1$s", ne)); - } catch (ClassNotFoundException cnfe) { + } + catch (ClassNotFoundException cnfe) { error(String.format("Error processing schema - %1$s", cnfe)); } - + // Work out what imports we need Set imports = new HashSet(); for (AttributeSchema attributeSchema : schema.getMay()) { @@ -453,10 +471,13 @@ public final class SchemaToJava { // Create the Java code try { createCode(packageName, className, schema, imports, outputFile); - } catch (TemplateException te) { + } + catch (TemplateException te) { error(String.format("Error generating code - %1$s", te.toString())); - } catch (IOException ioe) { + } + catch (IOException ioe) { error(String.format("Error generatign code - %1$s", ioe.toString())); } } + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaViewer.java b/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaViewer.java index 9897220f..3da87d0d 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaViewer.java +++ b/odm/src/main/java/org/springframework/ldap/odm/tools/SchemaViewer.java @@ -26,32 +26,32 @@ import java.util.Hashtable; *

    * SchemaViewer takes the following flags: *

      - *
    • -h,--help< Print this help message
    • - *
    • -l,--url <arg> Ldap url of directory to bind to (defaults to ldap://127.0.0.1:389)
    • - *
    • -u,--username <arg> DN to bind with (defaults to "")
    • - *
    • -p,--password <arg> Password to bind with (defaults to "")
    • - *
    • -o,--objectclass <arg> Object class name or ? for all. Print object class schema
    • - *
    • -a,--attribute <arg> Attribute name or ? for all. Print attribute schema
    • - *
    • -s,--syntax <arg> Syntax or ? for all. Print syntax
    • + *
    • -h,--help< Print this help message
    • + *
    • -l,--url <arg> Ldap url of directory to bind to (defaults to + * ldap://127.0.0.1:389)
    • + *
    • -u,--username <arg> DN to bind with (defaults to "")
    • + *
    • -p,--password <arg> Password to bind with (defaults to "")
    • + *
    • -o,--objectclass <arg> Object class name or ? for all. Print + * object class schema
    • + *
    • -a,--attribute <arg> Attribute name or ? for all. Print + * attribute schema
    • + *
    • -s,--syntax <arg> Syntax or ? for all. Print syntax
    • *
    - * + * * Only one of -a, -o and -s should be specified. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> * */ public final class SchemaViewer { - private static final String DEFAULT_URL="ldap://127.0.0.1:389"; - + + private static final String DEFAULT_URL = "ldap://127.0.0.1:389"; + private enum Flag { - URL("l", "url"), - USERNAME("u", "username"), - PASSWORD("p", "password"), - OBJECTCLASS("o", "objectclass"), - ATTRIBUTE("a", "attribute"), - SYNTAX("s", "syntax"), - HELP("h", "help"), - ERROR("e", "error"); + + URL("l", "url"), USERNAME("u", "username"), PASSWORD("p", "password"), OBJECTCLASS("o", + "objectclass"), ATTRIBUTE("a", + "attribute"), SYNTAX("s", "syntax"), HELP("h", "help"), ERROR("e", "error"); private String shortName; @@ -74,9 +74,11 @@ public final class SchemaViewer { public String toString() { return String.format("short=%1$s, long=%2$s", shortName, longName); } + } private enum SchemaContext { + OBJECTCLASS("ClassDefinition"), ATTRIBUTE("AttributeDefinition"), SYNTAX("SyntaxDefinition"); private String value; @@ -93,13 +95,17 @@ public final class SchemaViewer { public String toString() { return String.format("value=%1$s", value); } + } private static final Options DEFAULT_OPTIONS = new Options(); static { - DEFAULT_OPTIONS.addOption(Flag.URL.getShort(), Flag.URL.getLong(), true, "Ldap url (defaults to " + DEFAULT_URL + ")"); - DEFAULT_OPTIONS.addOption(Flag.USERNAME.getShort(), Flag.USERNAME.getLong(), true, "DN to bind with (defaults to \"\")"); - DEFAULT_OPTIONS.addOption(Flag.PASSWORD.getShort(), Flag.PASSWORD.getLong(), true, "Password to bind with defaults to \"\")"); + DEFAULT_OPTIONS.addOption(Flag.URL.getShort(), Flag.URL.getLong(), true, + "Ldap url (defaults to " + DEFAULT_URL + ")"); + DEFAULT_OPTIONS.addOption(Flag.USERNAME.getShort(), Flag.USERNAME.getLong(), true, + "DN to bind with (defaults to \"\")"); + DEFAULT_OPTIONS.addOption(Flag.PASSWORD.getShort(), Flag.PASSWORD.getLong(), true, + "Password to bind with defaults to \"\")"); DEFAULT_OPTIONS.addOption(Flag.OBJECTCLASS.getShort(), Flag.OBJECTCLASS.getLong(), true, "Object class name or ? for all. Print object class schema"); DEFAULT_OPTIONS.addOption(Flag.ATTRIBUTE.getShort(), Flag.ATTRIBUTE.getLong(), true, @@ -133,14 +139,14 @@ public final class SchemaViewer { private static void printObject(String contextName, String schemaName, DirContext schemaContext) throws NameNotFoundException, NamingException { - DirContext oContext = (DirContext)schemaContext.lookup(contextName + "/" + schemaName); + DirContext oContext = (DirContext) schemaContext.lookup(contextName + "/" + schemaName); outstream.println("NAME:" + schemaName); printAttrs(oContext.getAttributes("")); } - - private static void printSchema(String contextName, DirContext schemaContext) throws NameNotFoundException, - NamingException { + + private static void printSchema(String contextName, DirContext schemaContext) + throws NameNotFoundException, NamingException { outstream.println(); @@ -161,12 +167,14 @@ public final class SchemaViewer { if (optionValue.equals(WILDCARD)) { printSchema(contextName, schemaContext); - } else { + } + else { printObject(contextName, optionValue, schemaContext); } } - private static PrintStream outstream=System.out; + private static PrintStream outstream = System.out; + private final static String WILDCARD = "?"; public static void main(String[] argv) { @@ -175,7 +183,8 @@ public final class SchemaViewer { try { cmd = parser.parse(DEFAULT_OPTIONS, argv); - } catch (ParseException e) { + } + catch (ParseException e) { System.out.println(e.getMessage()); System.exit(1); } @@ -188,9 +197,9 @@ public final class SchemaViewer { } if (cmd.hasOption(Flag.ERROR.getShort())) { - outstream=System.err; + outstream = System.err; } - + String url = cmd.getOptionValue(Flag.URL.getShort(), DEFAULT_URL); String user = cmd.getOptionValue(Flag.USERNAME.getShort(), ""); String pass = cmd.getOptionValue(Flag.PASSWORD.getShort(), ""); @@ -226,14 +235,19 @@ public final class SchemaViewer { print(cmd.getOptionValue(Flag.SYNTAX.getShort()), SchemaContext.SYNTAX.getValue(), schemaContext); } - } catch (AuthenticationException e) { + } + catch (AuthenticationException e) { System.err.println(String.format("Failed to bind to ldap server at %1$s", url)); - } catch (CommunicationException e) { + } + catch (CommunicationException e) { System.err.println(String.format("Failed to contact ldap server at %1$s", url)); - } catch (NameNotFoundException e) { + } + catch (NameNotFoundException e) { System.err.println(String.format("Can't find object %1$s", e.getMessage())); - } catch (NamingException e) { + } + catch (NamingException e) { System.err.println(e.toString()); } } + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/tools/SyntaxToJavaClass.java b/odm/src/main/java/org/springframework/ldap/odm/tools/SyntaxToJavaClass.java index 2bde69ff..0ecdd17b 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/tools/SyntaxToJavaClass.java +++ b/odm/src/main/java/org/springframework/ldap/odm/tools/SyntaxToJavaClass.java @@ -6,11 +6,13 @@ import java.util.Map.Entry; /** * A map from an LDAP syntax to the Java class used to represent it. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ /* package */ final class SyntaxToJavaClass { + public static final class ClassInfo { + private final String className; private final String packageName; @@ -27,16 +29,18 @@ import java.util.Map.Entry; public String getPackageName() { return packageName; } - + public String getFullClassName() { - StringBuilder result=new StringBuilder(); - if (packageName!=null) { + StringBuilder result = new StringBuilder(); + if (packageName != null) { result.append(packageName).append(".").append(className); - } else { + } + else { result.append(className); } return result.toString(); } + } private final Map mapSyntaxToClassInfo = new HashMap(); @@ -50,7 +54,8 @@ import java.util.Map.Entry; if (lastDotIndex != -1) { className = fullClassName.substring(lastDotIndex + 1); packageName = fullClassName.substring(0, lastDotIndex); - } else { + } + else { className = fullClassName; } mapSyntaxToClassInfo.put(syntaxAndClass.getKey(), new ClassInfo(className, packageName)); @@ -60,4 +65,5 @@ import java.util.Map.Entry; public ClassInfo getClassInfo(String syntax) { return mapSyntaxToClassInfo.get(syntax); } + } diff --git a/odm/src/main/java/org/springframework/ldap/odm/tools/package-info.java b/odm/src/main/java/org/springframework/ldap/odm/tools/package-info.java index e065dbb1..fafb0a43 100755 --- a/odm/src/main/java/org/springframework/ldap/odm/tools/package-info.java +++ b/odm/src/main/java/org/springframework/ldap/odm/tools/package-info.java @@ -1,7 +1,7 @@ /** * Provides a tool to create a Java class representation of a set of LDAP object classes * and a simple tool to view LDAP schema. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/OrganizationalUnit.java b/odm/src/test/java/org/springframework/ldap/odm/test/OrganizationalUnit.java index 250d0eac..1c79a9c3 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/OrganizationalUnit.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/OrganizationalUnit.java @@ -27,8 +27,8 @@ import java.util.HashSet; import java.util.List; /** - * Automatically generated to represent the LDAP object classes - * "organizationalunit", "top". + * Automatically generated to represent the LDAP object classes "organizationalunit", + * "top". */ @Entry(objectClasses = { "organizationalUnit", "top" }) public final class OrganizationalUnit { @@ -58,12 +58,12 @@ public final class OrganizationalUnit { objectClass.add("top"); objectClass.add("organizationalUnit"); - int size = dn.size(); if (size > 1) { ou = dn.get(size - 1).split("=")[1]; - } else { + } + else { ou = ""; } @@ -99,8 +99,8 @@ public final class OrganizationalUnit { @Override public String toString() { - return String.format("objectClasses=%1$s | dn=%2$s | ou=%3$s | street=%4$s | description=%5$s", objectClass, - dn, ou, street, description); + return String.format("objectClasses=%1$s | dn=%2$s | ou=%3$s | street=%4$s | description=%5$s", objectClass, dn, + ou, street, description); } @Override @@ -127,30 +127,35 @@ public final class OrganizationalUnit { if (description == null) { if (other.description != null) return false; - } else if (!description.equals(other.description)) + } + else if (!description.equals(other.description)) return false; if (dn == null) { if (other.dn != null) return false; - } else if (!dn.equals(other.dn)) + } + else if (!dn.equals(other.dn)) return false; if (objectClass == null) { if (other.objectClass != null) return false; - } else - if (objectClass.size()!=other.objectClass.size() || - !(new HashSet(objectClass)).equals(new HashSet(other.objectClass))) - return false; + } + else if (objectClass.size() != other.objectClass.size() + || !(new HashSet(objectClass)).equals(new HashSet(other.objectClass))) + return false; if (ou == null) { if (other.ou != null) return false; - } else if (!ou.equals(other.ou)) + } + else if (!ou.equals(other.ou)) return false; if (street == null) { if (other.street != null) return false; - } else if (!street.equals(other.street)) + } + else if (!street.equals(other.street)) return false; return true; } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/Person.java b/odm/src/test/java/org/springframework/ldap/odm/test/Person.java index ec8d1ef8..fc6f02d5 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/Person.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/Person.java @@ -28,13 +28,14 @@ import java.util.Arrays; import java.util.HashSet; import java.util.List; -// Simple LDAP entry for testing +// Simple LDAP entry for testing @Entry(objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }) public final class Person { + public Person() { } - public Person(Name dn, String surname, List desc, int telephoneNumber, byte[] jpegPhoto) { + public Person(Name dn, String surname, List desc, int telephoneNumber, byte[] jpegPhoto) { this.dn = dn; this.surname = surname; this.desc = desc; @@ -48,7 +49,8 @@ public final class Person { int size = dn.size(); if (size > 1) { cn = dn.get(size - 1).split("=")[1]; - } else { + } + else { cn = ""; } } @@ -71,7 +73,8 @@ public final class Person { @Attribute(name = "sn") private String surname; - // Everything should be sets and in search operations also as results can be in any order + // Everything should be sets and in search operations also as results can be in any + // order @Attribute(name = "description") private List desc; @@ -135,13 +138,13 @@ public final class Person { @Override public String toString() { - StringBuilder jpegString=new StringBuilder(); - if (jpegPhoto!=null) { - for (byte b:jpegPhoto) { + StringBuilder jpegString = new StringBuilder(); + if (jpegPhoto != null) { + for (byte b : jpegPhoto) { jpegString.append(Byte.toString(b)); } } - + return String.format( "objectClasses=%1$s | dn=%2$s | cn=%3$s | sn=%4$s | desc=%5$s | telephoneNumber=%6$s | jpegPhoto=%7$s", objectClasses, dn, cn, surname, desc, telephoneNumber, jpegString); @@ -175,42 +178,52 @@ public final class Person { if (cn == null) { if (other.cn != null) return false; - } else if (!cn.equals(other.cn)) + } + else if (!cn.equals(other.cn)) return false; if (desc == null) { if (other.desc != null) return false; - } else if (desc.size()!=other.desc.size() || !(new HashSet(desc)).equals(new HashSet(other.desc))) + } + else if (desc.size() != other.desc.size() + || !(new HashSet(desc)).equals(new HashSet(other.desc))) return false; if (dn == null) { if (other.dn != null) return false; - } else if (!dn.equals(other.dn)) + } + else if (!dn.equals(other.dn)) return false; if (!Arrays.equals(jpegPhoto, other.jpegPhoto)) return false; if (objectClasses == null) { if (other.objectClasses != null) return false; - } else if (objectClasses.size()!=other.objectClasses.size() || !(new HashSet(objectClasses)).equals(new HashSet(other.objectClasses))) + } + else if (objectClasses.size() != other.objectClasses.size() + || !(new HashSet(objectClasses)).equals(new HashSet(other.objectClasses))) return false; if (someRandomField == null) { if (other.someRandomField != null) return false; - } else if (!someRandomField.equals(other.someRandomField)) + } + else if (!someRandomField.equals(other.someRandomField)) return false; if (someRandomList == null) { if (other.someRandomList != null) return false; - } else if (!someRandomList.equals(other.someRandomList)) + } + else if (!someRandomList.equals(other.someRandomList)) return false; if (surname == null) { if (other.surname != null) return false; - } else if (!surname.equals(other.surname)) + } + else if (!surname.equals(other.surname)) return false; if (telephoneNumber != other.telephoneNumber) return false; return true; } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/PlainPerson.java b/odm/src/test/java/org/springframework/ldap/odm/test/PlainPerson.java index 993b7841..e63dddfb 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/PlainPerson.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/PlainPerson.java @@ -24,9 +24,10 @@ import javax.naming.Name; import java.util.ArrayList; import java.util.List; -// Simple LDAP entry for testing +// Simple LDAP entry for testing @Entry(objectClasses = { "person", "top" }) public final class PlainPerson { + public PlainPerson() { } @@ -77,16 +78,21 @@ public final class PlainPerson { @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) + return true; + if (o == null || getClass() != o.getClass()) + return false; PlainPerson that = (PlainPerson) o; - if (cn != null ? !cn.equals(that.cn) : that.cn != null) return false; - if (dn != null ? !dn.equals(that.dn) : that.dn != null) return false; + if (cn != null ? !cn.equals(that.cn) : that.cn != null) + return false; + if (dn != null ? !dn.equals(that.dn) : that.dn != null) + return false; if (objectClasses != null ? !objectClasses.equals(that.objectClasses) : that.objectClasses != null) return false; - if (surname != null ? !surname.equals(that.surname) : that.surname != null) return false; + if (surname != null ? !surname.equals(that.surname) : that.surname != null) + return false; return true; } @@ -99,4 +105,5 @@ public final class PlainPerson { result = 31 * result + (surname != null ? surname.hashCode() : 0); return result; } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/TestConverterManager.java b/odm/src/test/java/org/springframework/ldap/odm/test/TestConverterManager.java index de30332e..b7cf31d2 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/TestConverterManager.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/TestConverterManager.java @@ -17,6 +17,7 @@ import org.springframework.ldap.odm.typeconversion.impl.converters.FromStringCon import org.springframework.ldap.odm.typeconversion.impl.converters.ToStringConverter; public final class TestConverterManager { + private ConverterManagerImpl converterManager; @Before @@ -50,8 +51,9 @@ public final class TestConverterManager { public void tearDown() { converterManager = null; } - + private static class ConverterTestData { + public final Class destClass; public final Object sourceData; @@ -76,16 +78,17 @@ public final class TestConverterManager { return String.format("sourceData=%1$s | syntax=%2$s | destClass=%3$s | expectedValue=%4$s", sourceData, syntax, destClass, expectedValue); } + } // Class to Class conversion without any syntaxes @Test public void basicTypeConverion() throws Exception { final ConverterTestData[] primitiveTypeTests = new ConverterTestData[] { - new ConverterTestData("33", Byte.class, Byte.valueOf((byte)33)), - new ConverterTestData("-88", Byte.class, Byte.valueOf((byte)-88)), - new ConverterTestData("666", Short.class, Short.valueOf((short)666)), - new ConverterTestData("-123", Short.class, Short.valueOf((short)-123)), + new ConverterTestData("33", Byte.class, Byte.valueOf((byte) 33)), + new ConverterTestData("-88", Byte.class, Byte.valueOf((byte) -88)), + new ConverterTestData("666", Short.class, Short.valueOf((short) 666)), + new ConverterTestData("-123", Short.class, Short.valueOf((short) -123)), new ConverterTestData("123", Integer.class, Integer.valueOf(123)), new ConverterTestData("-500", Integer.class, Integer.valueOf(-500)), new ConverterTestData("123456", Long.class, Long.valueOf(123456)), @@ -98,34 +101,35 @@ public final class TestConverterManager { new ConverterTestData("TRUE", Boolean.class, Boolean.TRUE), new ConverterTestData("This is a string", String.class, "This is a string"), new ConverterTestData("This is another String", String.class, "This is another String"), - new ConverterTestData((byte)66, String.class, "66"), - new ConverterTestData((int)1234, String.class, "1234"), - new ConverterTestData((int)-9876, String.class, "-9876"), + new ConverterTestData((byte) 66, String.class, "66"), + new ConverterTestData((int) 1234, String.class, "1234"), + new ConverterTestData((int) -9876, String.class, "-9876"), new ConverterTestData("https://google.com/", URI.class, new URI("https://google.com/")), - new ConverterTestData("https://apache.org/index.html", URI.class, new URI( - "https://apache.org/index.html")), + new ConverterTestData("https://apache.org/index.html", URI.class, + new URI("https://apache.org/index.html")), new ConverterTestData(new URI("https://google.com/"), String.class, "https://google.com/"), new ConverterTestData(new URI("https://apache.org/index.html"), String.class, "https://apache.org/index.html") }; new ExecuteRunnable>().runTests(new RunnableTest>() { public void runTest(ConverterTestData testData) { - assertEquals(testData.expectedValue, converterManager.convert(testData.sourceData, "", - testData.destClass)); + assertEquals(testData.expectedValue, + converterManager.convert(testData.sourceData, "", testData.destClass)); } }, primitiveTypeTests); } private static class SquaredConverter implements Converter { + public T convert(Object source, Class toClass) throws Exception { Integer intSource = null; if (source.getClass() == String.class) { - intSource = new Integer((String)source); + intSource = new Integer((String) source); } else { if (source.getClass() == Integer.class) { - intSource = (Integer)source; + intSource = (Integer) source; } } @@ -136,18 +140,20 @@ public final class TestConverterManager { return toClass.cast(result); } + } private static class CubedConverter implements Converter { + public T convert(Object source, Class toClass) throws Exception { Integer intSource = null; if (source.getClass() == String.class) { - intSource = new Integer((String)source); + intSource = new Integer((String) source); } else { if (source.getClass() == Integer.class) { - intSource = (Integer)source; + intSource = (Integer) source; } } @@ -158,6 +164,7 @@ public final class TestConverterManager { return toClass.cast(result); } + } // Tests using syntaxes for "finer grained" mapping @@ -186,8 +193,8 @@ public final class TestConverterManager { new ExecuteRunnable>().runTests(new RunnableTest>() { public void runTest(ConverterTestData testData) { - assertEquals(testData.expectedValue, converterManager.convert(testData.sourceData, testData.syntax, - testData.destClass)); + assertEquals(testData.expectedValue, + converterManager.convert(testData.sourceData, testData.syntax, testData.destClass)); } }, syntaxTests); @@ -204,4 +211,5 @@ public final class TestConverterManager { public void invalidSyntax() throws Exception { converterManager.convert(String.class, "not a uri", URI.class); } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/TestLdap.java b/odm/src/test/java/org/springframework/ldap/odm/test/TestLdap.java index cb97a2a7..52fa5f2f 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/TestLdap.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/TestLdap.java @@ -73,6 +73,7 @@ import static org.springframework.ldap.query.LdapQueryBuilder.query; // Tests all OdmManager functions public final class TestLdap { + private static final Logger LOG = LoggerFactory.getLogger(TestLdap.class); // Base DN for test data @@ -82,18 +83,13 @@ public final class TestLdap { private static int port; // Maximum number of objects to return in testing - private static final long COUNT_LIMIT=20; + private static final long COUNT_LIMIT = 20; // Maximum time to wait for results in testing (ms) - private static final int TIME_LIMIT=60000; + private static final int TIME_LIMIT = 60000; - private SearchControls searchControls = - new SearchControls(SearchControls.SUBTREE_SCOPE, - COUNT_LIMIT, - TIME_LIMIT, - null, - true, - false); + private SearchControls searchControls = new SearchControls(SearchControls.SUBTREE_SCOPE, COUNT_LIMIT, TIME_LIMIT, + null, true, false); private ConverterManagerImpl converterManager; @@ -105,30 +101,31 @@ public final class TestLdap { private static byte[] photo; static { try { - String photoString="/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS"+ - "Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRg"+ - "yIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wA"+ - "ARCAAnABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAA"+ - "gEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcY"+ - "GRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipK"+ - "TlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8v"+ - "P09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFB"+ - "AQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygp"+ - "KjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJm"+ - "aoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9"+ - "oADAMBAAIRAxEAPwDx2z0mK6gV/tSo2SCpUHGD9Qa2vDvgGfX7+eI3ot4EOEmEefMOOcZPQdOvW"+ - "s3VLGzsWiihUvM0ayONxATPIHXk4wfxFdd4L1aw0rw3eS3V3GHWRswkgugwCpVSckEk9OhB9azu"+ - "2ro6lCKnyyZwmvaHcaBrV1plxKkkluw+dRkMCAQfbgjiqi27sob1GfuVc1q9n1XVL3UdqxJI/wD"+ - "q/MXIXGAMd+B2HWoUZ1jUbZeABwKqzMJWT0Ld3cfaJ5ZFYtnCg+oUBf6V2XhvwVpcvhxfFXibVF"+ - "tNK3lEgjJ3yMGK7SRzkkHhRnHORXJQ6exVXB2r1K9Cfx7V0UWpeD7S3WJ9N1TUPLYssV7cBYkZg"+ - "AxAU4zwOcZ4HoKtppWQ4tSk5SNPx14o8M3/AITXT/D2kRRxB1jE4RIyuOc7ME84PzcHr2PPmX2y"+ - "YcZX8q37fQxPpqzsH8xvuqAeeuO/0H3e9Zn2dxwbK5JHXCH/AOJqNOhdSM1ZzVjRNwRbjGRxxzn"+ - "FdRouijV9Pi1C6toEMqn7MsK7SqBiCxOSSSVI5J4x6miiliW1FMzpbszreUw3H2VcuscpGT3UE9"+ - "Rn0HStE+IrZSQbEuRxvU4De4yc0UVFKCnuerms2vZryP/Z"; + String photoString = "/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkS" + + "Ew8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRg" + + "yIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wA" + + "ARCAAnABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAA" + + "gEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcY" + + "GRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipK" + + "TlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8v" + + "P09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFB" + + "AQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygp" + + "KjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJm" + + "aoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9" + + "oADAMBAAIRAxEAPwDx2z0mK6gV/tSo2SCpUHGD9Qa2vDvgGfX7+eI3ot4EOEmEefMOOcZPQdOvW" + + "s3VLGzsWiihUvM0ayONxATPIHXk4wfxFdd4L1aw0rw3eS3V3GHWRswkgugwCpVSckEk9OhB9azu" + + "2ro6lCKnyyZwmvaHcaBrV1plxKkkluw+dRkMCAQfbgjiqi27sob1GfuVc1q9n1XVL3UdqxJI/wD" + + "q/MXIXGAMd+B2HWoUZ1jUbZeABwKqzMJWT0Ld3cfaJ5ZFYtnCg+oUBf6V2XhvwVpcvhxfFXibVF" + + "tNK3lEgjJ3yMGK7SRzkkHhRnHORXJQ6exVXB2r1K9Cfx7V0UWpeD7S3WJ9N1TUPLYssV7cBYkZg" + + "AxAU4zwOcZ4HoKtppWQ4tSk5SNPx14o8M3/AITXT/D2kRRxB1jE4RIyuOc7ME84PzcHr2PPmX2y" + + "YcZX8q37fQxPpqzsH8xvuqAeeuO/0H3e9Zn2dxwbK5JHXCH/AOJqNOhdSM1ZzVjRNwRbjGRxxzn" + + "FdRouijV9Pi1C6toEMqn7MsK7SqBiCxOSSSVI5J4x6miiliW1FMzpbszreUw3H2VcuscpGT3UE9" + + "Rn0HStE+IrZSQbEuRxvU4De4yc0UVFKCnuerms2vZryP/Z"; - byte[] photoBytes=photoString.getBytes("US-ASCII"); - photo=Base64.getDecoder().decode(photoBytes); - } catch (IOException e) { + byte[] photoBytes = photoString.getBytes("US-ASCII"); + photo = Base64.getDecoder().decode(photoBytes); + } + catch (IOException e) { throw new RuntimeException("Problem decoding photo", e); } } @@ -137,7 +134,7 @@ public final class TestLdap { public static void setUpClass() throws Exception { // Added because the close down of Apache DS on Linux does // not seem to free up its port. - port=GetFreePort.getFreePort(); + port = GetFreePort.getFreePort(); // Start an LDAP server and import test data LdapTestUtils.startEmbeddedServer(port, baseName.toString(), "odm-test"); @@ -190,7 +187,7 @@ public final class TestLdap { LdapTestUtils.cleanAndSetup(contextSource, baseName, new ClassPathResource("testdata.ldif")); // Create our OdmManager - Set> managedClasses=new HashSet>(); + Set> managedClasses = new HashSet>(); managedClasses.add(Person.class); managedClasses.add(PlainPerson.class); managedClasses.add(OrganizationalUnit.class); @@ -206,12 +203,13 @@ public final class TestLdap { public void tearDown() throws Exception { LdapTestUtils.clearSubContexts(contextSource, baseName); - odmManager=null; - contextSource=null; - converterManager=null; + odmManager = null; + contextSource = null; + converterManager = null; } private enum PersonName { + WILLIAM(0), PATRICK(1), JON(2), TOM(3), PETER(4), DAVROS(5), DALEKS(6), MASTER(7); private int index; @@ -223,26 +221,26 @@ public final class TestLdap { public int getIndex() { return index; } + } - private Person[] personTestData=new Person[] { - new Person(LdapUtils.newLdapName("cn=William Hartnell,ou=Doctors,o=Whoniverse"), "Hartnell", Arrays - .asList(new String[] { "First Doctor", "Grumpy" }), 1, null), - new Person(LdapUtils.newLdapName("cn=Patrick Troughton,ou=Doctors,o=Whoniverse"), "Troughton", Arrays - .asList(new String[] { "Second Doctor", "Clown" }), 2, null), - new Person(LdapUtils.newLdapName("cn=Jon Pertwee,ou=Doctors,o=Whoniverse"), "Pertwee", Arrays - .asList(new String[] { "Third Doctor", "Dandy" }), 3, null), - new Person(LdapUtils.newLdapName("cn=Tom Baker,ou=Doctors,o=Whoniverse"), "Baker", Arrays - .asList(new String[] { "Fourth Doctor", "The one and only!" }), 4, null), - new Person(LdapUtils.newLdapName("cn=Peter Davison,ou=Doctors,o=Whoniverse"), "Davison", Arrays - .asList(new String[] { "Fifth Doctor" }), 5, null), - new Person(LdapUtils.newLdapName("cn=Davros,ou=Enemies,o=Whoniverse"), "Unknown", Arrays - .asList(new String[] { "Creator of the Daleks", "Kaled head scientist" }), 0, null), - new Person(LdapUtils.newLdapName("cn=Daleks,ou=Enemies,o=Whoniverse"), "NA", Arrays - .asList(new String[] { "The Doctor's greatest foe" }), 0, null), - new Person(LdapUtils.newLdapName("cn=Master,ou=Enemies,o=Whoniverse"), "Unknown", Arrays - .asList(new String[] { "An evil Time Lord" }), 0, photo), }; - + private Person[] personTestData = new Person[] { + new Person(LdapUtils.newLdapName("cn=William Hartnell,ou=Doctors,o=Whoniverse"), "Hartnell", + Arrays.asList(new String[] { "First Doctor", "Grumpy" }), 1, null), + new Person(LdapUtils.newLdapName("cn=Patrick Troughton,ou=Doctors,o=Whoniverse"), "Troughton", + Arrays.asList(new String[] { "Second Doctor", "Clown" }), 2, null), + new Person(LdapUtils.newLdapName("cn=Jon Pertwee,ou=Doctors,o=Whoniverse"), "Pertwee", + Arrays.asList(new String[] { "Third Doctor", "Dandy" }), 3, null), + new Person(LdapUtils.newLdapName("cn=Tom Baker,ou=Doctors,o=Whoniverse"), "Baker", + Arrays.asList(new String[] { "Fourth Doctor", "The one and only!" }), 4, null), + new Person(LdapUtils.newLdapName("cn=Peter Davison,ou=Doctors,o=Whoniverse"), "Davison", + Arrays.asList(new String[] { "Fifth Doctor" }), 5, null), + new Person(LdapUtils.newLdapName("cn=Davros,ou=Enemies,o=Whoniverse"), "Unknown", + Arrays.asList(new String[] { "Creator of the Daleks", "Kaled head scientist" }), 0, null), + new Person(LdapUtils.newLdapName("cn=Daleks,ou=Enemies,o=Whoniverse"), "NA", + Arrays.asList(new String[] { "The Doctor's greatest foe" }), 0, null), + new Person(LdapUtils.newLdapName("cn=Master,ou=Enemies,o=Whoniverse"), "Unknown", + Arrays.asList(new String[] { "An evil Time Lord" }), 0, photo), }; // Read various entries from the sample data set and check they are what we'd expect. @Test @@ -259,6 +257,7 @@ public final class TestLdap { } private static class SearchTestData { + private String search; private SearchControls searchScope; @@ -270,25 +269,21 @@ public final class TestLdap { this.searchScope = searchScope; this.people = people; } + } private SearchTestData[] searchTestData = { - new SearchTestData("(sn=Unknown)", - searchControls, - new Person[] { - personTestData[PersonName.DAVROS.getIndex()], - personTestData[PersonName.MASTER.getIndex()] }), - new SearchTestData("(description=*Doctor)", - searchControls, - new Person[] { - personTestData[PersonName.WILLIAM.getIndex()], - personTestData[PersonName.PATRICK.getIndex()], - personTestData[PersonName.JON.getIndex()], - personTestData[PersonName.TOM.getIndex()], - personTestData[PersonName.PETER.getIndex()] }), - }; + new SearchTestData("(sn=Unknown)", searchControls, + new Person[] { personTestData[PersonName.DAVROS.getIndex()], + personTestData[PersonName.MASTER.getIndex()] }), + new SearchTestData("(description=*Doctor)", searchControls, + new Person[] { personTestData[PersonName.WILLIAM.getIndex()], + personTestData[PersonName.PATRICK.getIndex()], personTestData[PersonName.JON.getIndex()], + personTestData[PersonName.TOM.getIndex()], + personTestData[PersonName.PETER.getIndex()] }), }; - // Carry out various searches against the test data set and check the results are what we'd expect. + // Carry out various searches against the test data set and check the results are what + // we'd expect. @Test public void search() throws Exception { new ExecuteRunnable().runTests(new RunnableTest() { @@ -303,6 +298,7 @@ public final class TestLdap { } private enum OrganizationalName { + ENEMIES(0), ASSISTANTS(1), DOCTORS(2); private int index; @@ -314,30 +310,34 @@ public final class TestLdap { public int getIndex() { return index; } + } - private static OrganizationalUnit ouTestData[]=new OrganizationalUnit[] { - new OrganizationalUnit(LdapUtils.newLdapName("ou=Enemies,o=Whoniverse"), "Acacia Avenue", "The bad guys"), - new OrganizationalUnit(LdapUtils.newLdapName("ou=Assistants,o=Whoniverse"), "Somewhere in space", "The plucky helpers"), - new OrganizationalUnit(LdapUtils.newLdapName("ou=Doctors,o=Whoniverse"), "Somewhere in time", "Our hero"), - }; + private static OrganizationalUnit ouTestData[] = new OrganizationalUnit[] { + new OrganizationalUnit(LdapUtils.newLdapName("ou=Enemies,o=Whoniverse"), "Acacia Avenue", "The bad guys"), + new OrganizationalUnit(LdapUtils.newLdapName("ou=Assistants,o=Whoniverse"), "Somewhere in space", + "The plucky helpers"), + new OrganizationalUnit(LdapUtils.newLdapName("ou=Doctors,o=Whoniverse"), "Somewhere in time", + "Our hero"), }; // Check everything works OK with a second managed class @Test public void testSecondOc() { LOG.debug("Reading all organizatinalUnits"); - List allOus=odmManager.findAll(OrganizationalUnit.class, baseName, searchControls); + List allOus = odmManager.findAll(OrganizationalUnit.class, baseName, searchControls); LOG.debug(String.format("Found - %1$s", allOus)); - assertEquals(new HashSet(Arrays.asList(ouTestData)), new HashSet(allOus)); + assertEquals(new HashSet(Arrays.asList(ouTestData)), + new HashSet(allOus)); - OrganizationalUnit testOu=ouTestData[OrganizationalName.ASSISTANTS.getIndex()]; + OrganizationalUnit testOu = ouTestData[OrganizationalName.ASSISTANTS.getIndex()]; LOG.debug(String.format("Reading - %1$s", testOu.getDn())); - OrganizationalUnit ou=odmManager.read(OrganizationalUnit.class, testOu.getDn()); + OrganizationalUnit ou = odmManager.read(OrganizationalUnit.class, testOu.getDn()); LOG.debug(String.format("Found - %1$s", ou)); assertEquals(testOu, ou); } - // Find all entries managed by the OdmManager in the test data set and check they are what we expect. + // Find all entries managed by the OdmManager in the test data set and check they are + // what we expect. @Test public void findAll() throws Exception { LOG.debug("finding all people"); @@ -356,7 +356,8 @@ public final class TestLdap { @Test public void verifySearchOnPlainPerson() { - List result = odmManager.search(PlainPerson.class, baseName, "(cn=William Hartnell)", searchControls); + List result = odmManager.search(PlainPerson.class, baseName, "(cn=William Hartnell)", + searchControls); assertEquals(1, result.size()); PlainPerson foundPerson = result.get(0); @@ -366,7 +367,8 @@ public final class TestLdap { @Test public void verifySearchWithLdapQuery() { - List result = odmManager.search(Person.class, query().base(baseName).where("cn").is("William Hartnell")); + List result = odmManager.search(Person.class, + query().base(baseName).where("cn").is("William Hartnell")); assertEquals(1, result.size()); Person foundPerson = result.get(0); @@ -376,7 +378,8 @@ public final class TestLdap { @Test public void updatePlainPerson() { - List result = odmManager.search(PlainPerson.class, baseName, "(cn=William Hartnell)", searchControls); + List result = odmManager.search(PlainPerson.class, baseName, "(cn=William Hartnell)", + searchControls); assertEquals(1, result.size()); PlainPerson foundPerson = result.get(0); @@ -389,12 +392,12 @@ public final class TestLdap { } private Person[] createTestData = { - new Person(LdapUtils.newLdapName("cn=Colin Baker,ou=Doctors,o=Whoniverse"), "Baker", Arrays - .asList(new String[] { "Sixth Doctor" }), 6, null), - new Person(LdapUtils.newLdapName("cn=Sylvester McCoy,ou=Doctors,o=Whoniverse"), "McCoy", Arrays - .asList(new String[] { "Seventh Doctor" }), 7, null), - new Person(LdapUtils.newLdapName("cn=Paul McGann,ou=Doctors,o=Whoniverse"), "McGann", Arrays - .asList(new String[] { "Eigth Doctor" }), 8, photo), }; + new Person(LdapUtils.newLdapName("cn=Colin Baker,ou=Doctors,o=Whoniverse"), "Baker", + Arrays.asList(new String[] { "Sixth Doctor" }), 6, null), + new Person(LdapUtils.newLdapName("cn=Sylvester McCoy,ou=Doctors,o=Whoniverse"), "McCoy", + Arrays.asList(new String[] { "Seventh Doctor" }), 7, null), + new Person(LdapUtils.newLdapName("cn=Paul McGann,ou=Doctors,o=Whoniverse"), "McGann", + Arrays.asList(new String[] { "Eigth Doctor" }), 8, photo), }; // Create some entries, read them back and check they are what we'd expect. @Test @@ -415,7 +418,8 @@ public final class TestLdap { }, createTestData); } - // Update an entry from the test data set, read it back and check it is what we'd expect. + // Update an entry from the test data set, read it back and check it is what we'd + // expect. @Test public void update() throws Exception { Person william = personTestData[PersonName.WILLIAM.getIndex()]; @@ -426,16 +430,15 @@ public final class TestLdap { assertEquals(william, readWilliam); } - private Person[] deleteData = { - personTestData[PersonName.JON.getIndex()], + private Person[] deleteData = { personTestData[PersonName.JON.getIndex()], personTestData[PersonName.TOM.getIndex()], personTestData[PersonName.DAVROS.getIndex()], }; - private Person[] whatsLeft = { - personTestData[PersonName.WILLIAM.getIndex()], + private Person[] whatsLeft = { personTestData[PersonName.WILLIAM.getIndex()], personTestData[PersonName.PATRICK.getIndex()], personTestData[PersonName.PETER.getIndex()], personTestData[PersonName.DALEKS.getIndex()], personTestData[PersonName.MASTER.getIndex()], }; - // Delete a some entries from the the test data set and check what's left is what we'd expect + // Delete a some entries from the the test data set and check what's left is what we'd + // expect @Test public void delete() throws Exception { for (Person toDelete : deleteData) { @@ -460,29 +463,33 @@ public final class TestLdap { } private final static class NoEntry { + @SuppressWarnings("unused") @Id Name id; + } // Every class to be managed must be annotated @Entry @Test(expected = MetaDataException.class) public void noEntryAnnotation() { - ((OdmManagerImpl)odmManager).addManagedClass(NoEntry.class); + ((OdmManagerImpl) odmManager).addManagedClass(NoEntry.class); } - @Entry(objectClasses="test") + @Entry(objectClasses = "test") private final static class NoId { + } // There must be a field with the @Id annotation @Test(expected = MetaDataException.class) public void noId() { - ((OdmManagerImpl)odmManager).addManagedClass(NoId.class); + ((OdmManagerImpl) odmManager).addManagedClass(NoId.class); } - @Entry(objectClasses="test") + @Entry(objectClasses = "test") private final static class TwoIds { + @SuppressWarnings("unused") @Id private Name firstId; @@ -494,88 +501,100 @@ public final class TestLdap { @SuppressWarnings("unused") public TwoIds() { } + } // Only one field may be annotated @Id @Test(expected = MetaDataException.class) public void twoIds() { - ((OdmManagerImpl)odmManager).addManagedClass(TwoIds.class); + ((OdmManagerImpl) odmManager).addManagedClass(TwoIds.class); } - @Entry(objectClasses="test") + @Entry(objectClasses = "test") public final static class NoConstructor { + @SuppressWarnings("unused") @Id private Name id; public NoConstructor(String aValue) { } + } // All Entry annotated classes must have a zero argument public constructor @Test(expected = InvalidEntryException.class) public void noConstructor() { - ((OdmManagerImpl)odmManager).addManagedClass(NoConstructor.class); + ((OdmManagerImpl) odmManager).addManagedClass(NoConstructor.class); } - @Entry(objectClasses="test") + @Entry(objectClasses = "test") public final static class AttributeOnId { + @SuppressWarnings("unused") @Id @Attribute private Name id; + } // It is illegal put put both the Id and the Attribute annotation on the same field @Test(expected = MetaDataException.class) public void attributeOnId() { - ((OdmManagerImpl)odmManager).addManagedClass(AttributeOnId.class); + ((OdmManagerImpl) odmManager).addManagedClass(AttributeOnId.class); } - @Entry(objectClasses="test") + @Entry(objectClasses = "test") public final static class IdIsNotAName { + @SuppressWarnings("unused") @Id private String id; + } // The field annotation with @Id must be of type javax.naming.Name @Test(expected = MetaDataException.class) public void idIsNotAName() { - ((OdmManagerImpl)odmManager).addManagedClass(IdIsNotAName.class); + ((OdmManagerImpl) odmManager).addManagedClass(IdIsNotAName.class); } - @Entry(objectClasses="test") + @Entry(objectClasses = "test") public final static class MissingConverter { + @SuppressWarnings("unused") @Id private Name id; @SuppressWarnings("unused") private BufferedImage image; + } // The OdmManager should flag any missing converters when it is instantiated @Test(expected = InvalidEntryException.class) public void missingConverter() { - ((OdmManagerImpl)odmManager).addManagedClass(MissingConverter.class); + ((OdmManagerImpl) odmManager).addManagedClass(MissingConverter.class); } - @Entry(objectClasses="test") + @Entry(objectClasses = "test") public final static class WrongClassForOc { + @SuppressWarnings("unused") @Id private Name id; @SuppressWarnings("unused") - @Attribute(name="objectClass") + @Attribute(name = "objectClass") private int ocs; + } - // The OdmManager should flag if the objectClass attribute is not of the appropriate type + // The OdmManager should flag if the objectClass attribute is not of the appropriate + // type @Test(expected = MetaDataException.class) public void wrongClassForOc() { - ((OdmManagerImpl)odmManager).addManagedClass(WrongClassForOc.class); + ((OdmManagerImpl) odmManager).addManagedClass(WrongClassForOc.class); } // The OdmManager should flag any attempt to use a "unmanaged" class @@ -595,12 +614,11 @@ public final class TestLdap { } private enum Flag { - URL("l", "url"), - USERNAME("u", "username"), - PASSWORD("p", "password"), - HELP("h", "help"); + + URL("l", "url"), USERNAME("u", "username"), PASSWORD("p", "password"), HELP("h", "help"); private String shortName; + private String longName; private Flag(String shortName, String longName) { @@ -620,32 +638,38 @@ public final class TestLdap { public String toString() { return String.format("short=%1$s, long=%2$s", shortName, longName); } + } - private static final String DEFAULT_LDAP_URL="ldap://localhost:389"; - private static final String DEFAULT_USERNAME=""; - private static final String DEFAULT_PASSWORD=""; + private static final String DEFAULT_LDAP_URL = "ldap://localhost:389"; + + private static final String DEFAULT_USERNAME = ""; + + private static final String DEFAULT_PASSWORD = ""; private static final Options options = new Options(); static { - options.addOption(Flag.URL.getShort(), Flag.URL.getLong(), true, "Ldap url to bind to, defaults to "+DEFAULT_LDAP_URL); - options.addOption(Flag.USERNAME.getShort(), Flag.USERNAME.getLong(), true, "DN to bind with, defaults to "+DEFAULT_USERNAME); - options.addOption(Flag.PASSWORD.getShort(), Flag.PASSWORD.getLong(), true, "Password to bind with defaults to "+DEFAULT_PASSWORD); + options.addOption(Flag.URL.getShort(), Flag.URL.getLong(), true, + "Ldap url to bind to, defaults to " + DEFAULT_LDAP_URL); + options.addOption(Flag.USERNAME.getShort(), Flag.USERNAME.getLong(), true, + "DN to bind with, defaults to " + DEFAULT_USERNAME); + options.addOption(Flag.PASSWORD.getShort(), Flag.PASSWORD.getLong(), true, + "Password to bind with defaults to " + DEFAULT_PASSWORD); options.addOption(Flag.HELP.getShort(), Flag.HELP.getLong(), false, "Print this help message"); } + private static void runLdapTestCases(String url, String username, String password, String[] testCases) + throws Exception { - private static void runLdapTestCases(String url, String username, String password, String[] testCases) throws Exception { - - for (String testCase:testCases) { + for (String testCase : testCases) { LOG.debug(String.format("Starting ldap test case %1$s", testCase)); // Set up - TestLdap testLdap=new TestLdap(); + TestLdap testLdap = new TestLdap(); testLdap.setUp(url, username, password); // Run the test - Method testMethod=testLdap.getClass().getMethod(testCase); + Method testMethod = testLdap.getClass().getMethod(testCase); testMethod.invoke(testLdap); // Tear down @@ -660,9 +684,7 @@ public final class TestLdap { * * Three flags are required: * - * -l ldap url of target server - * -u dn to bind with - * -p password to bind with + * -l ldap url of target server -u dn to bind with -p password to bind with * * The organisation o=Whoniverse must already exists and the bound user must have * write permission. @@ -674,7 +696,8 @@ public final class TestLdap { try { cmd = parser.parse(options, argv); - } catch (ParseException e) { + } + catch (ParseException e) { System.out.println(e.getMessage()); System.exit(1); } @@ -686,11 +709,13 @@ public final class TestLdap { System.exit(0); } - String url=cmd.getOptionValue(Flag.URL.getShort(), DEFAULT_LDAP_URL); - String username=cmd.getOptionValue(Flag.USERNAME.getShort(), DEFAULT_USERNAME); - String password=cmd.getOptionValue(Flag.PASSWORD.getShort(), DEFAULT_PASSWORD); + String url = cmd.getOptionValue(Flag.URL.getShort(), DEFAULT_LDAP_URL); + String username = cmd.getOptionValue(Flag.USERNAME.getShort(), DEFAULT_USERNAME); + String password = cmd.getOptionValue(Flag.PASSWORD.getShort(), DEFAULT_PASSWORD); // Run all the tests - runLdapTestCases(url, username, password, new String[] { "create", "delete", "findAll", "read", "search", "update", "testSecondOc" } ); + runLdapTestCases(url, username, password, + new String[] { "create", "delete", "findAll", "read", "search", "update", "testSecondOc" }); } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/TestManagerConverterFactory.java b/odm/src/test/java/org/springframework/ldap/odm/test/TestManagerConverterFactory.java index a2e8666c..844ff2ef 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/TestManagerConverterFactory.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/TestManagerConverterFactory.java @@ -14,60 +14,73 @@ import org.springframework.ldap.odm.typeconversion.impl.Converter; import org.springframework.ldap.odm.typeconversion.impl.ConverterManagerFactoryBean; public class TestManagerConverterFactory { + private static class NullConverter implements Converter { + public T convert(Object source, Class toClass) throws Exception { return null; } + } - private static final Converter nullConverter=new NullConverter(); - + + private static final Converter nullConverter = new NullConverter(); + private static class ConverterConfigTestData { + private Class[] fromClasses; + private String syntax; + private Class[] toClasses; private ConverterConfigTestData(Class[] fromClasses, String syntax, Class[] toClasses) { - this.fromClasses=fromClasses; - this.syntax=syntax; - this.toClasses=toClasses; + this.fromClasses = fromClasses; + this.syntax = syntax; + this.toClasses = toClasses; } + } - - private static ConverterConfigTestData[] converterConfigTestData=new ConverterConfigTestData[] { - new ConverterConfigTestData(new Class[] { String.class }, "", new Class[] { Integer.class }), - new ConverterConfigTestData(new Class[] { Byte.class, java.lang.Integer.class }, "", new Class[] { String.class, Long.class }), - new ConverterConfigTestData(new Class[] { String.class }, "123", new Class[] { java.net.URI.class }), - }; + + private static ConverterConfigTestData[] converterConfigTestData = new ConverterConfigTestData[] { + new ConverterConfigTestData(new Class[] { String.class }, "", new Class[] { Integer.class }), + new ConverterConfigTestData(new Class[] { Byte.class, java.lang.Integer.class }, "", + new Class[] { String.class, Long.class }), + new ConverterConfigTestData(new Class[] { String.class }, "123", + new Class[] { java.net.URI.class }), }; private static class ConverterTestData { + private final Class fromClass; + private final String syntax; + private final Class toClass; + private final boolean canConvert; - + private ConverterTestData(Class fromClass, String syntax, Class toClass, boolean canConvert) { - this.fromClass=fromClass; - this.syntax=syntax; - this.toClass=toClass; - this.canConvert=canConvert; + this.fromClass = fromClass; + this.syntax = syntax; + this.toClass = toClass; + this.canConvert = canConvert; } + } - - private ConverterTestData[] converterTestData=new ConverterTestData[] { + + private ConverterTestData[] converterTestData = new ConverterTestData[] { new ConverterTestData(java.lang.String.class, "", java.lang.Integer.class, true), new ConverterTestData(java.lang.Byte.class, "", java.lang.Long.class, true), new ConverterTestData(java.lang.Integer.class, "444", java.lang.String.class, true), new ConverterTestData(java.lang.String.class, "123", java.net.URI.class, true), new ConverterTestData(java.lang.String.class, "123", java.lang.Byte.class, false), - new ConverterTestData(java.lang.Byte.class, "", java.lang.Integer.class, false) - }; - + new ConverterTestData(java.lang.Byte.class, "", java.lang.Integer.class, false) }; + @Test public void testConverterFactory() throws Exception { - ConverterManagerFactoryBean converterManagerFactory=new ConverterManagerFactoryBean(); - Set configList=new HashSet(); - for (ConverterConfigTestData config:converterConfigTestData) { - ConverterManagerFactoryBean.ConverterConfig converterConfig=new ConverterManagerFactoryBean.ConverterConfig(); + ConverterManagerFactoryBean converterManagerFactory = new ConverterManagerFactoryBean(); + Set configList = new HashSet(); + for (ConverterConfigTestData config : converterConfigTestData) { + ConverterManagerFactoryBean.ConverterConfig converterConfig = new ConverterManagerFactoryBean.ConverterConfig(); converterConfig.setFromClasses(new HashSet>(Arrays.asList(config.fromClasses))); converterConfig.setSyntax(config.syntax); converterConfig.setToClasses(new HashSet>(Arrays.asList(config.toClasses))); @@ -75,13 +88,14 @@ public class TestManagerConverterFactory { configList.add(converterConfig); } converterManagerFactory.setConverterConfig(configList); - final ConverterManager converterManager=(ConverterManager)converterManagerFactory.getObject(); - + final ConverterManager converterManager = (ConverterManager) converterManagerFactory.getObject(); + new ExecuteRunnable().runTests(new RunnableTest() { public void runTest(ConverterTestData testData) { - assertEquals(testData.canConvert, + assertEquals(testData.canConvert, converterManager.canConvert(testData.fromClass, testData.syntax, testData.toClass)); } }, converterTestData); } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/TestSchemaToJava.java b/odm/src/test/java/org/springframework/ldap/odm/test/TestSchemaToJava.java index d539bcac..6431f1ac 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/TestSchemaToJava.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/TestSchemaToJava.java @@ -50,11 +50,12 @@ import static org.junit.Assert.assertEquals; // Tests the generation of entry Java classes from LDAP schema public final class TestSchemaToJava { + private static final Logger LOG = LoggerFactory.getLogger(TestLdap.class); private static final LdapName baseName = LdapUtils.newLdapName("o=Whoniverse"); - private static final String tempDir=System.getProperty("java.io.tmpdir"); + private static final String tempDir = System.getProperty("java.io.tmpdir"); // These unit tests require this port to free on localhost private static int port; @@ -67,7 +68,7 @@ public final class TestSchemaToJava { public static void setUpClass() throws Exception { // Added because the close down of Apache DS on Linux does // not seem to free up its port. - port=GetFreePort.getFreePort(); + port = GetFreePort.getFreePort(); // Start an in process LDAP server LdapTestUtils.startEmbeddedServer(port, baseName.toString(), "odm-test"); @@ -118,52 +119,48 @@ public final class TestSchemaToJava { public void tearDown() throws Exception { LdapTestUtils.shutdownEmbeddedServer(); - contextSource=null; - converterManager=null; + contextSource = null; + converterManager = null; } // Figure out the path of the created Java file private static String calculateOutputDirectory(String outputDir, String packageName) { // Convert the package name to a path - Pattern pattern=Pattern.compile("\\."); - Matcher matcher=pattern.matcher(packageName); - String sepToUse=File.separator; + Pattern pattern = Pattern.compile("\\."); + Matcher matcher = pattern.matcher(packageName); + String sepToUse = File.separator; if (sepToUse.equals("\\")) { - sepToUse="\\\\"; + sepToUse = "\\\\"; } - return outputDir+File.separator+matcher.replaceAll(sepToUse); + return outputDir + File.separator + matcher.replaceAll(sepToUse); } // Due of the nature of the code under test this unit test is a little unusual: // // 1) Generate an entry class corresponding to objects classes - // "inetorgperson, organizationalperson, person, top" - // using the SchemaToJavaTool + // "inetorgperson, organizationalperson, person, top" + // using the SchemaToJavaTool // 2) Compile the generated code // 3) Create an OdmManager to managing the newly created - // entry class. + // entry class. // 4) Use this OdmManager to read an entry from LDAP and check the results. // @Test public void generate() throws Exception { - final String className="Person"; - final String packageName="org.springframework.ldap.odm.testclasses"; + final String className = "Person"; + final String packageName = "org.springframework.ldap.odm.testclasses"; File tempFile = File.createTempFile("test-odm-syntax-to-class-map", ".txt"); FileUtils.copyInputStreamToFile(new ClassPathResource("/syntax-to-class-map.txt").getInputStream(), tempFile); // Add classes dir to class path - needed for compilation System.setProperty("java.class.path", - System.getProperty("java.class.path")+File.pathSeparator+"target/classes"); + System.getProperty("java.class.path") + File.pathSeparator + "target/classes"); - String[] flags=new String[] { - "--url", "ldap://127.0.0.1:"+port, - "--objectclasses", "organizationalperson", - "--syntaxmap", tempFile.getAbsolutePath(), - "--class", className, - "--package", packageName, - "--outputdir", tempDir }; + String[] flags = new String[] { "--url", "ldap://127.0.0.1:" + port, "--objectclasses", "organizationalperson", + "--syntaxmap", tempFile.getAbsolutePath(), "--class", className, "--package", packageName, + "--outputdir", tempDir }; // Generate the code using SchemaToJava SchemaToJava.main(flags); @@ -173,44 +170,45 @@ public final class TestSchemaToJava { // Java 5 - we'll use the Java 6 Compiler API once we can drop support for Java 5. String javaDir = calculateOutputDirectory(tempDir, packageName); - CompilerInterface.compile(javaDir, className+".java"); + CompilerInterface.compile(javaDir, className + ".java"); // Java 5 // OK it compiles so lets load our new class URL[] urls = new URL[] { new File(tempDir).toURI().toURL() }; URLClassLoader ucl = new URLClassLoader(urls, getClass().getClassLoader()); - Class clazz = ucl.loadClass(packageName+"."+className); + Class clazz = ucl.loadClass(packageName + "." + className); // Create our OdmManager using our new class OdmManagerImpl odmManager = new OdmManagerImpl(converterManager, contextSource); odmManager.addManagedClass(clazz); // And try reading from the directory using it - LdapName testDn= LdapUtils.newLdapName(baseName); + LdapName testDn = LdapUtils.newLdapName(baseName); testDn.addAll(LdapUtils.newLdapName("cn=William Hartnell,ou=Doctors")); - Object fromDirectory=odmManager.read(clazz, testDn); + Object fromDirectory = odmManager.read(clazz, testDn); LOG.debug(String.format("Read - %1$s", fromDirectory)); // Check some returned values - Method getDnMethod=clazz.getMethod("getDn"); - Object dn=getDnMethod.invoke(fromDirectory); + Method getDnMethod = clazz.getMethod("getDn"); + Object dn = getDnMethod.invoke(fromDirectory); assertEquals(testDn, dn); - Method getCnIteratorMethod=clazz.getMethod("getCnIterator"); + Method getCnIteratorMethod = clazz.getMethod("getCnIterator"); @SuppressWarnings("unchecked") - Iterator cnIterator=(Iterator)getCnIteratorMethod.invoke(fromDirectory); - int cnCount=0; + Iterator cnIterator = (Iterator) getCnIteratorMethod.invoke(fromDirectory); + int cnCount = 0; while (cnIterator.hasNext()) { cnCount++; assertEquals("William Hartnell", cnIterator.next()); } assertEquals(1, cnCount); - Method telephoneNumberIteratorMethod=clazz.getMethod("getTelephoneNumberIterator"); + Method telephoneNumberIteratorMethod = clazz.getMethod("getTelephoneNumberIterator"); @SuppressWarnings("unchecked") - Iterator telephoneNumberIterator=(Iterator)telephoneNumberIteratorMethod.invoke(fromDirectory); - int telephoneNumberCount=0; + Iterator telephoneNumberIterator = (Iterator) telephoneNumberIteratorMethod + .invoke(fromDirectory); + int telephoneNumberCount = 0; while (telephoneNumberIterator.hasNext()) { telephoneNumberCount++; assertEquals(Integer.valueOf(1), telephoneNumberIterator.next()); @@ -218,8 +216,9 @@ public final class TestSchemaToJava { assertEquals(1, telephoneNumberCount); // Reread and check whether equals and hashCode are at least sane - Object fromDirectory2=odmManager.read(clazz, testDn); + Object fromDirectory2 = odmManager.read(clazz, testDn); assertEquals(fromDirectory, fromDirectory2); assertEquals(fromDirectory.hashCode(), fromDirectory2.hashCode()); } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/TestSchemaViewer.java b/odm/src/test/java/org/springframework/ldap/odm/test/TestSchemaViewer.java index de6c11fe..dcdf84e1 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/TestSchemaViewer.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/TestSchemaViewer.java @@ -38,26 +38,25 @@ import java.util.List; import static org.junit.Assert.assertEquals; public final class TestSchemaViewer { + // Base DN for test data private static final LdapName baseName = LdapUtils.newLdapName("o=Whoniverse"); - private static final String lineSeparator = System.getProperty ("line.separator"); - + private static final String lineSeparator = System.getProperty("line.separator"); + private static int port; - + private static String[] commonFlags; + @BeforeClass public static void setUpClass() throws Exception { // Added because the close down of Apache DS on Linux does // not seem to free up its port. - port=GetFreePort.getFreePort(); - - commonFlags=new String[] { - "--url", "ldap://127.0.0.1:"+port, - "--username", "", - "--password", "", - "--error"}; - + port = GetFreePort.getFreePort(); + + commonFlags = new String[] { "--url", "ldap://127.0.0.1:" + port, "--username", "", "--password", "", + "--error" }; + // Start an in process LDAP server LdapTestUtils.startEmbeddedServer(port, baseName.toString(), "odm-test"); } @@ -66,7 +65,7 @@ public final class TestSchemaViewer { public static void tearDownClass() throws Exception { LdapTestUtils.shutdownEmbeddedServer(); } - + @Before public void setUp() throws Exception { } @@ -74,63 +73,67 @@ public final class TestSchemaViewer { @After public void tearDown() throws Exception { } - + private static String runSchemaViewer(String... flags) { - String result=null; - PrintStream originalOut=System.out; + String result = null; + PrintStream originalOut = System.out; ByteArrayOutputStream output = new ByteArrayOutputStream(); - try { + try { System.setErr(new PrintStream(output)); - List commandFlags= - new ArrayList(Arrays.asList(commonFlags)); + List commandFlags = new ArrayList(Arrays.asList(commonFlags)); commandFlags.addAll(Arrays.asList(flags)); - + SchemaViewer.main(commandFlags.toArray(new String[0])); - + // Turn end of lines into | for portability - result=output.toString().trim().replace(lineSeparator, "|"); - - } finally { + result = output.toString().trim().replace(lineSeparator, "|"); + + } + finally { System.setErr(originalOut); } - + return result; } - + private static class TestData { + private final String flag; + private final String value; + private final String result; - + public TestData(String flag, String value, String result) { - this.flag=flag; - this.value=value; - this.result=result; + this.flag = flag; + this.value = value; + this.result = result; } + } - - // This makes the test dependent on the order in which the data is returned - it is invalid to assume that this will not change - private static TestData[] viewerTestData=new TestData[] { - new TestData("-o", "top", - "NAME:top|MUST:objectClass |X-SCHEMA:system |NAME:top |NUMERICOID:2.5.6.0 |DESC:top of the superclass chain |ABSTRACT:true"), - new TestData("-o", "country", - "NAME:country|MUST:c |X-SCHEMA:core |SUP:top |NAME:country |STRUCTURAL:true |NUMERICOID:2.5.6.2 |DESC:RFC2256: a country |MAY:searchGuide description"), - new TestData("-a", "sn", - "NAME:sn|NAME:sn surname |SUBSTR:caseIgnoreSubstringsMatch |X-SCHEMA:core |SYNTAX:1.3.6.1.4.1.1466.115.121.1.15 |NUMERICOID:2.5.4.4 |SUP:name |DESC:RFC2256: last (family) name(s) for which the entity is known by |USAGE:userApplications |EQUALITY:caseIgnoreMatch"), - new TestData("-a", "jpegPhoto", - "NAME:jpegPhoto|X-SCHEMA:inetorgperson |SYNTAX:1.3.6.1.4.1.1466.115.121.1.28 |NAME:jpegPhoto |USAGE:userApplications |NUMERICOID:0.9.2342.19200300.100.1.60 |DESC:RFC2798: a JPEG image"), - }; - + + // This makes the test dependent on the order in which the data is returned - it is + // invalid to assume that this will not change + private static TestData[] viewerTestData = new TestData[] { new TestData("-o", "top", + "NAME:top|MUST:objectClass |X-SCHEMA:system |NAME:top |NUMERICOID:2.5.6.0 |DESC:top of the superclass chain |ABSTRACT:true"), + new TestData("-o", "country", + "NAME:country|MUST:c |X-SCHEMA:core |SUP:top |NAME:country |STRUCTURAL:true |NUMERICOID:2.5.6.2 |DESC:RFC2256: a country |MAY:searchGuide description"), + new TestData("-a", "sn", + "NAME:sn|NAME:sn surname |SUBSTR:caseIgnoreSubstringsMatch |X-SCHEMA:core |SYNTAX:1.3.6.1.4.1.1466.115.121.1.15 |NUMERICOID:2.5.4.4 |SUP:name |DESC:RFC2256: last (family) name(s) for which the entity is known by |USAGE:userApplications |EQUALITY:caseIgnoreMatch"), + new TestData("-a", "jpegPhoto", + "NAME:jpegPhoto|X-SCHEMA:inetorgperson |SYNTAX:1.3.6.1.4.1.1466.115.121.1.28 |NAME:jpegPhoto |USAGE:userApplications |NUMERICOID:0.9.2342.19200300.100.1.60 |DESC:RFC2798: a JPEG image"), }; + // Very simple test - mainly just to exercise the code and to // ensure we get representative test coverage @Test public void testSchemaViewer() throws Exception { new ExecuteRunnable().runTests(new RunnableTest() { public void runTest(TestData testData) { - String result=runSchemaViewer(testData.flag, testData.value); + String result = runSchemaViewer(testData.flag, testData.value); assertEquals(testData.result, result); } }, viewerTestData); } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/TestsWithJdepend.java b/odm/src/test/java/org/springframework/ldap/odm/test/TestsWithJdepend.java index 31cd08c3..d8e614f2 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/TestsWithJdepend.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/TestsWithJdepend.java @@ -25,6 +25,7 @@ import java.io.IOException; import static org.junit.Assert.assertEquals; public class TestsWithJdepend { + private JDepend jdepend; @Before @@ -32,7 +33,7 @@ public class TestsWithJdepend { jdepend = new JDepend(); jdepend.addDirectory("build/classes/java/main"); } - + @Test public void testAllPackages() { jdepend.analyze(); diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/UriConverter.java b/odm/src/test/java/org/springframework/ldap/odm/test/UriConverter.java index beaf99a1..843a7dd9 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/UriConverter.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/UriConverter.java @@ -6,19 +6,23 @@ import org.springframework.ldap.odm.typeconversion.impl.Converter; /** * A bi-directional converter between {@link java.net.URI} and {@link java.lang.String}. - * + * * @author Paul Harvey <paul.at.pauls-place.me.uk> */ public class UriConverter implements Converter { - /* (non-Javadoc) - * @see org.springframework.ldap.odm.typeconversion.impl.Converter#convert(java.lang.Object, java.lang.Class) + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.odm.typeconversion.impl.Converter#convert(java.lang. + * Object, java.lang.Class) */ public T convert(Object source, Class toClass) throws Exception { T result = null; if (String.class.isAssignableFrom(source.getClass()) && toClass == URI.class) { - result = toClass.cast(new URI((String)source)); - } else { + result = toClass.cast(new URI((String) source)); + } + else { if (URI.class.isAssignableFrom(source.getClass()) && toClass == String.class) { result = toClass.cast(source.toString()); } @@ -26,4 +30,5 @@ public class UriConverter implements Converter { return result; } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/utils/CompilerInterface.java b/odm/src/test/java/org/springframework/ldap/odm/test/utils/CompilerInterface.java index 72ab922b..6c959f63 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/utils/CompilerInterface.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/utils/CompilerInterface.java @@ -9,16 +9,18 @@ import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; public class CompilerInterface { + // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API public static void compile(String directory, String file) throws Exception { File toCompile = new File(directory, file); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); - Iterable javaFileObjects = - fileManager.getJavaFileObjectsFromFiles(Arrays.asList(toCompile)); + Iterable javaFileObjects = fileManager + .getJavaFileObjectsFromFiles(Arrays.asList(toCompile)); compiler.getTask(null, fileManager, null, null, null, javaFileObjects).call(); fileManager.close(); } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/utils/ExecuteRunnable.java b/odm/src/test/java/org/springframework/ldap/odm/test/utils/ExecuteRunnable.java index b7f37843..780d1a15 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/utils/ExecuteRunnable.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/utils/ExecuteRunnable.java @@ -4,9 +4,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; // Simple utility class to run a given test over a set of test data -public final class ExecuteRunnable { +public final class ExecuteRunnable { - public void runTests(RunnableTest runnableTest, U[] testData) throws Exception { + public void runTests(RunnableTest runnableTest, U[] testData) throws Exception { StackTraceElement ste = Thread.currentThread().getStackTrace()[2]; Logger LOG = LoggerFactory.getLogger(ste.getClassName()); for (U testDatum : testData) { @@ -16,4 +16,5 @@ public final class ExecuteRunnable { runnableTest.runTest(testDatum); } } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/utils/GetFreePort.java b/odm/src/test/java/org/springframework/ldap/odm/test/utils/GetFreePort.java index af4bbf93..b3908f0e 100755 --- a/odm/src/test/java/org/springframework/ldap/odm/test/utils/GetFreePort.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/utils/GetFreePort.java @@ -9,16 +9,17 @@ import org.slf4j.LoggerFactory; // Added because the close down of the embedded Apache DS used // for unit testing does not seem to free up its port. public class GetFreePort { - private static Logger LOG=LoggerFactory.getLogger(GetFreePort.class); - - public static int getFreePort() - throws IOException { + + private static Logger LOG = LoggerFactory.getLogger(GetFreePort.class); + + public static int getFreePort() throws IOException { ServerSocket server = new ServerSocket(0); int port = server.getLocalPort(); server.close(); - + LOG.debug(String.format("Port number: %1$s", port)); - + return port; } + } diff --git a/odm/src/test/java/org/springframework/ldap/odm/test/utils/RunnableTest.java b/odm/src/test/java/org/springframework/ldap/odm/test/utils/RunnableTest.java index 3c8355c4..5a76d4b2 100644 --- a/odm/src/test/java/org/springframework/ldap/odm/test/utils/RunnableTest.java +++ b/odm/src/test/java/org/springframework/ldap/odm/test/utils/RunnableTest.java @@ -2,5 +2,7 @@ package org.springframework.ldap.odm.test.utils; // Interface to implement for tests to be run by ExecuteRunnable public interface RunnableTest { + void runTest(T testData) throws Exception; + } diff --git a/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlAggregateDirContextProcessor.java b/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlAggregateDirContextProcessor.java index 099d7293..da0f58c8 100644 --- a/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlAggregateDirContextProcessor.java +++ b/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlAggregateDirContextProcessor.java @@ -18,37 +18,33 @@ package org.springframework.ldap.control; import org.springframework.ldap.core.support.AggregateDirContextProcessor; /** - * AggregateDirContextProcessor implementation for managing a virtual list view - * by aggregating DirContextProcessor implementations for a VirtualListViewControl - * and its required companion SortControl. + * AggregateDirContextProcessor implementation for managing a virtual list view by + * aggregating DirContextProcessor implementations for a VirtualListViewControl and its + * required companion SortControl. * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg * @author Marius Scurtescu */ -public class VirtualListViewControlAggregateDirContextProcessor extends AggregateDirContextProcessor -{ +public class VirtualListViewControlAggregateDirContextProcessor extends AggregateDirContextProcessor { + private SortControlDirContextProcessor _sortControlDirContextProcessor; + private VirtualListViewControlDirContextProcessor _virtualListViewControlDirContextProcessor; - public VirtualListViewControlAggregateDirContextProcessor(String sortKey, int pageSize) - { - this( - new SortControlDirContextProcessor(sortKey), - new VirtualListViewControlDirContextProcessor(pageSize) - ); + public VirtualListViewControlAggregateDirContextProcessor(String sortKey, int pageSize) { + this(new SortControlDirContextProcessor(sortKey), new VirtualListViewControlDirContextProcessor(pageSize)); } - public VirtualListViewControlAggregateDirContextProcessor(String sortKey, int pageSize, int targetOffset, int listSize, VirtualListViewResultsCookie cookie) - { - this( - new SortControlDirContextProcessor(sortKey), - new VirtualListViewControlDirContextProcessor(pageSize, targetOffset, listSize, cookie) - ); + public VirtualListViewControlAggregateDirContextProcessor(String sortKey, int pageSize, int targetOffset, + int listSize, VirtualListViewResultsCookie cookie) { + this(new SortControlDirContextProcessor(sortKey), + new VirtualListViewControlDirContextProcessor(pageSize, targetOffset, listSize, cookie)); } - public VirtualListViewControlAggregateDirContextProcessor(SortControlDirContextProcessor sortControlDirContextProcessor, VirtualListViewControlDirContextProcessor virtualListViewControlDirContextProcessor) - { + public VirtualListViewControlAggregateDirContextProcessor( + SortControlDirContextProcessor sortControlDirContextProcessor, + VirtualListViewControlDirContextProcessor virtualListViewControlDirContextProcessor) { _sortControlDirContextProcessor = sortControlDirContextProcessor; _virtualListViewControlDirContextProcessor = virtualListViewControlDirContextProcessor; @@ -59,4 +55,5 @@ public class VirtualListViewControlAggregateDirContextProcessor extends Aggregat public VirtualListViewResultsCookie getCookie() { return _virtualListViewControlDirContextProcessor.getCookie(); } + } diff --git a/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessor.java b/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessor.java index 633dd882..d0a9bd21 100644 --- a/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessor.java +++ b/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessor.java @@ -65,11 +65,15 @@ import java.lang.reflect.Method; * * @author Ulrik Sandberg * @author Marius Scurtescu - * @see LDAP Extensions for Scrolling View Browsing of Search Results + * @see LDAP + * Extensions for Scrolling View Browsing of Search Results */ -public class VirtualListViewControlDirContextProcessor extends AbstractFallbackRequestAndResponseControlDirContextProcessor -{ - private static final String DEFAULT_REQUEST_CONTROL = "com.sun.jndi.ldap.ctl.VirtualListViewControl"; +public class VirtualListViewControlDirContextProcessor + extends AbstractFallbackRequestAndResponseControlDirContextProcessor { + + private static final String DEFAULT_REQUEST_CONTROL = "com.sun.jndi.ldap.ctl.VirtualListViewControl"; + private static final String DEFAULT_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.VirtualListViewResponseControl"; private static final boolean CRITICAL_CONTROL = true; @@ -90,16 +94,16 @@ public class VirtualListViewControlDirContextProcessor extends AbstractFallbackR this(pageSize, 1, 0, null); } - public VirtualListViewControlDirContextProcessor(int pageSize, - int targetOffset, int listSize, VirtualListViewResultsCookie cookie) { + public VirtualListViewControlDirContextProcessor(int pageSize, int targetOffset, int listSize, + VirtualListViewResultsCookie cookie) { this.pageSize = pageSize; this.targetOffset = targetOffset; this.listSize = listSize; this.cookie = cookie; - defaultRequestControl = DEFAULT_REQUEST_CONTROL; - defaultResponseControl = DEFAULT_RESPONSE_CONTROL; - fallbackRequestControl = DEFAULT_REQUEST_CONTROL; + defaultRequestControl = DEFAULT_REQUEST_CONTROL; + defaultResponseControl = DEFAULT_RESPONSE_CONTROL; + fallbackRequestControl = DEFAULT_REQUEST_CONTROL; fallbackResponseControl = DEFAULT_RESPONSE_CONTROL; loadControlClasses(); @@ -126,98 +130,62 @@ public class VirtualListViewControlDirContextProcessor extends AbstractFallbackR } /** - * Set whether the targetOffset should be interpreted as - * percentage of the list or an offset into the list. + * Set whether the targetOffset should be interpreted as percentage of + * the list or an offset into the list. * @param isPercentage true if targetOffset is a percentage */ public void setOffsetPercentage(boolean isPercentage) { this.offsetPercentage = isPercentage; } - public boolean isOffsetPercentage() - { + public boolean isOffsetPercentage() { return offsetPercentage; } /* - * @see org.springframework.ldap.control.AbstractRequestControlDirContextProcessor#createRequestControl() + * @see org.springframework.ldap.control.AbstractRequestControlDirContextProcessor# + * createRequestControl() */ - public Control createRequestControl() - { + public Control createRequestControl() { Control control; - if (offsetPercentage) - { - control = super.createRequestControl( - new Class[] { - int.class, - int.class, - boolean.class - }, - new Object[] { - Integer.valueOf(targetOffset), - Integer.valueOf(pageSize), - Boolean.valueOf(CRITICAL_CONTROL) - } - ); + if (offsetPercentage) { + control = super.createRequestControl(new Class[] { int.class, int.class, boolean.class }, new Object[] { + Integer.valueOf(targetOffset), Integer.valueOf(pageSize), Boolean.valueOf(CRITICAL_CONTROL) }); } - else - { + else { control = super.createRequestControl( - new Class[] { - int.class, - int.class, - int.class, - int.class, - boolean.class - }, - new Object[] { - Integer.valueOf(targetOffset), - Integer.valueOf(listSize), - Integer.valueOf(0), - Integer.valueOf(pageSize - 1), - Boolean.valueOf(CRITICAL_CONTROL) - } - ); + new Class[] { int.class, int.class, int.class, int.class, boolean.class }, + new Object[] { Integer.valueOf(targetOffset), Integer.valueOf(listSize), Integer.valueOf(0), + Integer.valueOf(pageSize - 1), Boolean.valueOf(CRITICAL_CONTROL) }); } - if (cookie != null) - { - invokeMethod( - "setContextID", - requestControlClass, - control, - new Class[] {byte[].class}, - new Object[] {cookie.getCookie()} - ); + if (cookie != null) { + invokeMethod("setContextID", requestControlClass, control, new Class[] { byte[].class }, + new Object[] { cookie.getCookie() }); } return control; } - protected void handleResponse(Object control) - { - byte[] result = (byte[]) invokeMethod("getContextID", - responseControlClass, control); - Integer listSize = (Integer) invokeMethod("getListSize", - responseControlClass, control); - Integer targetOffset = (Integer) invokeMethod( - "getTargetOffset", responseControlClass, control); - this.exception = (NamingException) invokeMethod("getException", - responseControlClass, control); + protected void handleResponse(Object control) { + byte[] result = (byte[]) invokeMethod("getContextID", responseControlClass, control); + Integer listSize = (Integer) invokeMethod("getListSize", responseControlClass, control); + Integer targetOffset = (Integer) invokeMethod("getTargetOffset", responseControlClass, control); + this.exception = (NamingException) invokeMethod("getException", responseControlClass, control); - this.cookie = new VirtualListViewResultsCookie(result, - targetOffset.intValue(), listSize.intValue()); + this.cookie = new VirtualListViewResultsCookie(result, targetOffset.intValue(), listSize.intValue()); if (exception != null) { throw LdapUtils.convertLdapException(exception); } } - protected static Object invokeMethod(String methodName, Class clazz, Object control, Class[] paramTypes, Object[] paramValues) - { + protected static Object invokeMethod(String methodName, Class clazz, Object control, Class[] paramTypes, + Object[] paramValues) { Method method = ReflectionUtils.findMethod(clazz, methodName, paramTypes); return ReflectionUtils.invokeMethod(method, control, paramValues); } + } diff --git a/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewResultsCookie.java b/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewResultsCookie.java index a75ae7d6..281fe2ca 100644 --- a/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewResultsCookie.java +++ b/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewResultsCookie.java @@ -19,7 +19,7 @@ package org.springframework.ldap.control; /** * Wrapper class for the cookie returned when using the * {@link com.sun.jndi.ldap.ctl.VirtualListViewControl}. - * + * * @author Ulrik Sandberg */ public class VirtualListViewResultsCookie { @@ -32,9 +32,7 @@ public class VirtualListViewResultsCookie { /** * Constructor. - * - * @param cookie - * the cookie returned by a VirtualListViewResponseControl. + * @param cookie the cookie returned by a VirtualListViewResponseControl. * @param targetPosition TODO * @param contentCount TODO */ @@ -46,7 +44,6 @@ public class VirtualListViewResultsCookie { /** * Get the cookie. - * * @return the cookie. */ public byte[] getCookie() { @@ -60,4 +57,5 @@ public class VirtualListViewResultsCookie { public int getTargetPosition() { return targetPosition; } + } diff --git a/sandbox/src/test/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessorTest.java b/sandbox/src/test/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessorTest.java index 77cc75bf..440e8bf7 100644 --- a/sandbox/src/test/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessorTest.java +++ b/sandbox/src/test/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessorTest.java @@ -58,11 +58,9 @@ public class VirtualListViewControlDirContextProcessorTest { int pageSize = 5; int targetOffset = 25; int listSize = 1000; - VirtualListViewControlDirContextProcessor tested = new VirtualListViewControlDirContextProcessor( - pageSize, targetOffset, listSize, - new VirtualListViewResultsCookie(new byte[0], 0, 0)); - VirtualListViewControl result = (VirtualListViewControl) tested - .createRequestControl(); + VirtualListViewControlDirContextProcessor tested = new VirtualListViewControlDirContextProcessor(pageSize, + targetOffset, listSize, new VirtualListViewResultsCookie(new byte[0], 0, 0)); + VirtualListViewControl result = (VirtualListViewControl) tested.createRequestControl(); assertThat(result).isNotNull(); assertThat(result.getID()).isEqualTo(OID_REQUEST); @@ -71,23 +69,19 @@ public class VirtualListViewControlDirContextProcessorTest { int expectedAfterCount = 4; int expectedOffset = 25; int expectedContentCount = listSize; - assertEncodedRequest(result.getEncodedValue(), expectedBeforeCount, - expectedAfterCount, expectedOffset, expectedContentCount, - new byte[0]); + assertEncodedRequest(result.getEncodedValue(), expectedBeforeCount, expectedAfterCount, expectedOffset, + expectedContentCount, new byte[0]); } @Test - public void testCreateRequestControlWithTargetAsPercentage() - throws Exception { + public void testCreateRequestControlWithTargetAsPercentage() throws Exception { int pageSize = 5; int targetPercentage = 25; int listSize = 1000; - VirtualListViewControlDirContextProcessor tested = new VirtualListViewControlDirContextProcessor( - pageSize, targetPercentage, listSize, - new VirtualListViewResultsCookie(new byte[0], 0, 0)); + VirtualListViewControlDirContextProcessor tested = new VirtualListViewControlDirContextProcessor(pageSize, + targetPercentage, listSize, new VirtualListViewResultsCookie(new byte[0], 0, 0)); tested.setOffsetPercentage(true); - VirtualListViewControl result = (VirtualListViewControl) tested - .createRequestControl(); + VirtualListViewControl result = (VirtualListViewControl) tested.createRequestControl(); assertThat(result).isNotNull(); assertThat(result.getID()).isEqualTo(OID_REQUEST); @@ -97,9 +91,8 @@ public class VirtualListViewControlDirContextProcessorTest { // the VLVControl requests 25 out of an expected 100 int expectedOffset = 25; int expectedContentCount = 100; - assertEncodedRequest(result.getEncodedValue(), expectedBeforeCount, - expectedAfterCount, expectedOffset, expectedContentCount, - new byte[0]); + assertEncodedRequest(result.getEncodedValue(), expectedBeforeCount, expectedAfterCount, expectedOffset, + expectedContentCount, new byte[0]); } @Test @@ -107,16 +100,13 @@ public class VirtualListViewControlDirContextProcessorTest { int pageSize = 5; int targetOffset = 25; int listSize = 1000; - VirtualListViewControlDirContextProcessor tested = new VirtualListViewControlDirContextProcessor( - pageSize, targetOffset, listSize, - new VirtualListViewResultsCookie(new byte[0], 0, 0)); + VirtualListViewControlDirContextProcessor tested = new VirtualListViewControlDirContextProcessor(pageSize, + targetOffset, listSize, new VirtualListViewResultsCookie(new byte[0], 0, 0)); int virtualListViewResult = 53; // unwilling to perform - byte[] encoded = encodeResponseValue(10, listSize, - virtualListViewResult); - VirtualListViewResponseControl control = new VirtualListViewResponseControl( - OID_RESPONSE, false, encoded); - when(ldapContextMock.getResponseControls()).thenReturn(new Control[]{control}); + byte[] encoded = encodeResponseValue(10, listSize, virtualListViewResult); + VirtualListViewResponseControl control = new VirtualListViewResponseControl(OID_RESPONSE, false, encoded); + when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); try { tested.postProcess(ldapContextMock); @@ -138,12 +128,11 @@ public class VirtualListViewControlDirContextProcessorTest { byte[] encoded = encodeResponseValue(10, 1000, virtualListViewResult); int expectedLength = 14; - assertEncodedResponse(encoded, expectedLength, 10, 1000, 53, - new byte[0]); + assertEncodedResponse(encoded, expectedLength, 10, 1000, 53, new byte[0]); } - private byte[] encodeResponseValue(int targetPosition, int contentCount, - int virtualListViewResult) throws IOException { + private byte[] encodeResponseValue(int targetPosition, int contentCount, int virtualListViewResult) + throws IOException { // build the ASN.1 encoding BerEncoder ber = new BerEncoder(10); @@ -159,10 +148,8 @@ public class VirtualListViewControlDirContextProcessorTest { return ber.getTrimmedBuf(); } - private void assertEncodedRequest(byte[] encodedValue, - int expectedBeforeCount, int expectedAfterCount, - int expectedOffset, int expectedContentCount, - byte[] expectedContextId) throws Exception { + private void assertEncodedRequest(byte[] encodedValue, int expectedBeforeCount, int expectedAfterCount, + int expectedOffset, int expectedContentCount, byte[] expectedContextId) throws Exception { dumpEncodedValue("VirtualListViewRequest\n", encodedValue); BerDecoder ber = new BerDecoder(encodedValue, 0, encodedValue.length); ber.parseSeq(null); @@ -184,19 +171,16 @@ public class VirtualListViewControlDirContextProcessorTest { break; case 1: // greaterThanOrEqual - throw new AssertionFailedError( - "CHOICE value greaterThanOrEqual not supported"); + throw new AssertionFailedError("CHOICE value greaterThanOrEqual not supported"); default: - throw new AssertionFailedError("illegal CHOICE value: " - + targetType); + throw new AssertionFailedError("illegal CHOICE value: " + targetType); } byte[] bs = ber.parseOctetString(Ber.ASN_OCTET_STR, null); assertContextId(expectedContextId, bs); } - private void assertContextId(byte[] expectedContextId, - byte[] actualContextId) { + private void assertContextId(byte[] expectedContextId, byte[] actualContextId) { if (expectedContextId == null && actualContextId == null) { return; } @@ -209,10 +193,8 @@ public class VirtualListViewControlDirContextProcessorTest { assertThat(actualContextId.length).isEqualTo(expectedContextId.length); } - private void assertEncodedResponse(byte[] encodedValue, - int expectedEncodingLength, int expectedTargetPosition, - int expectedContentCount, int expectedVirtualListViewResult, - byte[] expectedContextId) throws Exception { + private void assertEncodedResponse(byte[] encodedValue, int expectedEncodingLength, int expectedTargetPosition, + int expectedContentCount, int expectedVirtualListViewResult, byte[] expectedContextId) throws Exception { dumpEncodedValue("VirtualListViewResponse\n", encodedValue); assertThat(encodedValue.length).isEqualTo(expectedEncodingLength); BerDecoder ber = new BerDecoder(encodedValue, 0, encodedValue.length); @@ -231,4 +213,5 @@ public class VirtualListViewControlDirContextProcessorTest { private void dumpEncodedValue(String message, byte[] encodedValue) { Ber.dumpBER(System.out, message, encodedValue, 0, encodedValue.length); } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/AbstractEc2InstanceLaunchingFactoryBean.java b/test-support/src/main/java/org/springframework/ldap/test/AbstractEc2InstanceLaunchingFactoryBean.java index f8ccfbd0..c379e831 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/AbstractEc2InstanceLaunchingFactoryBean.java +++ b/test-support/src/main/java/org/springframework/ldap/test/AbstractEc2InstanceLaunchingFactoryBean.java @@ -27,20 +27,24 @@ import org.springframework.util.Assert; import java.util.Collections; /** - * Abstract FactoryBean superclass to use for automatically launching an EC2 instance before creating the actual target object. - * This approach is particularly useful for integration testing purposes - the idea is to have particular EC2 images prepared - * for running integration tests against certain server configurations, enabling integration tests aimed at e.g. a particluar - * DB server to run transparently at the computer of each individual developer without having to have the actual server software - * installed on their computers. + * Abstract FactoryBean superclass to use for automatically launching an EC2 instance + * before creating the actual target object. This approach is particularly useful for + * integration testing purposes - the idea is to have particular EC2 images prepared for + * running integration tests against certain server configurations, enabling integration + * tests aimed at e.g. a particluar DB server to run transparently at the computer of each + * individual developer without having to have the actual server software installed on + * their computers. *

    - * Public AMIs will need to be created, bundled and registered for each server setup. A subclass of this FactoryBean - * is then added to create the actual target object (e.g. a DataSource), implementing the {link #doCreateInstance} method. - * This method will be supplied the IP address of the instance that was created, enabling the subclass to configure the - * created instance appropriately. - * + * Public AMIs will need to be created, bundled and registered for each server setup. A + * subclass of this FactoryBean is then added to create the actual target object (e.g. a + * DataSource), implementing the {link #doCreateInstance} method. This method will be + * supplied the IP address of the instance that was created, enabling the subclass to + * configure the created instance appropriately. + * * @author Mattias Hellborg Arthursson */ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFactoryBean { + private static final int INSTANCE_START_SLEEP_TIME = 1000; private static final long DEFAULT_PREPARATION_SLEEP_TIME = 30000; @@ -63,7 +67,6 @@ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFa /** * Set the name of the AMI image to be launched. - * * @param imageName the AMI image name. */ public void setImageName(String imageName) { @@ -72,7 +75,6 @@ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFa /** * Set the AWS key. - * * @param awsKey the AWS key. */ public void setAwsKey(String awsKey) { @@ -81,7 +83,6 @@ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFa /** * Set the AWS secret key. - * * @param awsSecretKey the aws secret key. */ public void setAwsSecretKey(String awsSecretKey) { @@ -90,7 +91,6 @@ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFa /** * Set the name of the keypair. - * * @param keypairName The keypair name. */ public void setKeypairName(String keypairName) { @@ -98,8 +98,8 @@ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFa } /** - * Set the name of the access group. This group should be configured with the appropriate ports open for this test case to execute. - * + * Set the name of the access group. This group should be configured with the + * appropriate ports open for this test case to execute. * @param groupName the group name. */ public void setGroupName(String groupName) { @@ -138,7 +138,8 @@ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFa LOG.info("Instance prepared - proceeding"); } return doCreateInstance(instance.getDnsName()); - } else { + } + else { throw new IllegalStateException("Failed to start a new instance"); } @@ -146,7 +147,6 @@ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFa /** * Implement to create the actual target object. - * * @param ip the ip address of the launched EC2 image. * @return the object to be returned by this FactoryBean. * @throws Exception if an error occurs during initialization. @@ -162,4 +162,5 @@ public abstract class AbstractEc2InstanceLaunchingFactoryBean extends AbstractFa } } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/AttributeCheckAttributesMapper.java b/test-support/src/main/java/org/springframework/ldap/test/AttributeCheckAttributesMapper.java index 55c96346..7f109ff1 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/AttributeCheckAttributesMapper.java +++ b/test-support/src/main/java/org/springframework/ldap/test/AttributeCheckAttributesMapper.java @@ -24,26 +24,29 @@ import javax.naming.directory.Attributes; import java.util.Arrays; /** - * Dummy AttributesMapper for testing purposes to check that the received - * Attributes are the expected ones. - * + * Dummy AttributesMapper for testing purposes to check that the received Attributes are + * the expected ones. + * * @author Mattias Hellborg Arthursson */ public class AttributeCheckAttributesMapper implements AttributesMapper { + private String[] expectedAttributes = new String[0]; - private String[] expectedValues = new String[0];; + private String[] expectedValues = new String[0]; - private String[] absentAttributes = new String[0];; + ; - public Object mapFromAttributes(Attributes attributes) - throws NamingException { - Assert.assertEquals("Values and attributes need to have the same length ", - expectedAttributes.length, expectedValues.length); + private String[] absentAttributes = new String[0]; + + ; + + public Object mapFromAttributes(Attributes attributes) throws NamingException { + Assert.assertEquals("Values and attributes need to have the same length ", expectedAttributes.length, + expectedValues.length); for (int i = 0; i < expectedAttributes.length; i++) { Attribute attribute = attributes.get(expectedAttributes[i]); - Assert.assertNotNull("Attribute " + expectedAttributes[i] - + " was not present", attribute); + Assert.assertNotNull("Attribute " + expectedAttributes[i] + " was not present", attribute); Assert.assertEquals(expectedValues[i], attribute.get()); } @@ -65,4 +68,5 @@ public class AttributeCheckAttributesMapper implements AttributesMapper public void setExpectedValues(String[] expectedValues) { this.expectedValues = Arrays.copyOf(expectedValues, expectedValues.length); } + } \ No newline at end of file diff --git a/test-support/src/main/java/org/springframework/ldap/test/AttributeCheckContextMapper.java b/test-support/src/main/java/org/springframework/ldap/test/AttributeCheckContextMapper.java index 33e09cd9..428c6ee7 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/AttributeCheckContextMapper.java +++ b/test-support/src/main/java/org/springframework/ldap/test/AttributeCheckContextMapper.java @@ -23,12 +23,13 @@ import org.springframework.ldap.core.DirContextAdapter; import java.util.Arrays; /** - * Dummy ContextMapper for testing purposes to check that the received - * Attributes are the expected ones. - * + * Dummy ContextMapper for testing purposes to check that the received Attributes are the + * expected ones. + * * @author Mattias Hellborg Arthursson */ public class AttributeCheckContextMapper implements ContextMapper { + private String[] expectedAttributes = new String[0]; private String[] expectedValues = new String[0]; @@ -37,13 +38,11 @@ public class AttributeCheckContextMapper implements ContextMapper search(Name name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { + public NamingEnumeration search(Name name, Attributes matchingAttributes, String[] attributesToReturn) + throws NamingException { throw new UnsupportedOperationException(); } @Override - public NamingEnumeration search(String name, Attributes matchingAttributes, String[] attributesToReturn) throws NamingException { + public NamingEnumeration search(String name, Attributes matchingAttributes, + String[] attributesToReturn) throws NamingException { throw new UnsupportedOperationException(); } @@ -145,22 +148,26 @@ public class DummyDirContext implements DirContext { } @Override - public NamingEnumeration search(Name name, String filter, SearchControls cons) throws NamingException { + public NamingEnumeration search(Name name, String filter, SearchControls cons) + throws NamingException { throw new UnsupportedOperationException(); } @Override - public NamingEnumeration search(String name, String filter, SearchControls cons) throws NamingException { + public NamingEnumeration search(String name, String filter, SearchControls cons) + throws NamingException { throw new UnsupportedOperationException(); } @Override - public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { + public NamingEnumeration search(Name name, String filterExpr, Object[] filterArgs, + SearchControls cons) throws NamingException { throw new UnsupportedOperationException(); } @Override - public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, SearchControls cons) throws NamingException { + public NamingEnumeration search(String name, String filterExpr, Object[] filterArgs, + SearchControls cons) throws NamingException { throw new UnsupportedOperationException(); } @@ -308,4 +315,5 @@ public class DummyDirContext implements DirContext { public String getNameInNamespace() throws NamingException { throw new UnsupportedOperationException(); } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/EmbeddedLdapServer.java b/test-support/src/main/java/org/springframework/ldap/test/EmbeddedLdapServer.java index 9e224ab4..8bebfa07 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/EmbeddedLdapServer.java +++ b/test-support/src/main/java/org/springframework/ldap/test/EmbeddedLdapServer.java @@ -34,18 +34,20 @@ import java.io.File; * @since 1.3.2 */ public final class EmbeddedLdapServer { + private final DirectoryService directoryService; + private final LdapServer ldapServer; + private static File workingDirectory; - private EmbeddedLdapServer(DirectoryService directoryService, - LdapServer ldapServer) { + private EmbeddedLdapServer(DirectoryService directoryService, LdapServer ldapServer) { this.directoryService = directoryService; this.ldapServer = ldapServer; } - public static EmbeddedLdapServer newEmbeddedServer(String defaultPartitionName, String defaultPartitionSuffix, int port) - throws Exception{ + public static EmbeddedLdapServer newEmbeddedServer(String defaultPartitionName, String defaultPartitionSuffix, + int port) throws Exception { workingDirectory = new File(System.getProperty("java.io.tmpdir") + "/apacheds-test1"); FileUtils.deleteDirectory(workingDirectory); @@ -54,7 +56,7 @@ public final class EmbeddedLdapServer { directoryService.setAllowAnonymousAccess(true); directoryService.setWorkingDirectory(workingDirectory); - directoryService.getChangeLog().setEnabled( false ); + directoryService.getChangeLog().setEnabled(false); JdbmPartition partition = new JdbmPartition(); partition.setId(defaultPartitionName); @@ -64,19 +66,18 @@ public final class EmbeddedLdapServer { directoryService.startup(); // Inject the apache root entry if it does not already exist - if ( !directoryService.getAdminSession().exists( partition.getSuffixDn() ) ) - { + if (!directoryService.getAdminSession().exists(partition.getSuffixDn())) { ServerEntry entry = directoryService.newEntry(new LdapDN(defaultPartitionSuffix)); entry.add("objectClass", "top", "domain", "extensibleObject"); entry.add("dc", defaultPartitionName); - directoryService.getAdminSession().add( entry ); + directoryService.getAdminSession().add(entry); } LdapServer ldapServer = new LdapServer(); ldapServer.setDirectoryService(directoryService); TcpTransport ldapTransport = new TcpTransport(port); - ldapServer.setTransports( ldapTransport ); + ldapServer.setTransports(ldapTransport); ldapServer.start(); return new EmbeddedLdapServer(directoryService, ldapServer); @@ -88,4 +89,5 @@ public final class EmbeddedLdapServer { FileUtils.deleteDirectory(workingDirectory); } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/EmbeddedLdapServerFactoryBean.java b/test-support/src/main/java/org/springframework/ldap/test/EmbeddedLdapServerFactoryBean.java index 4e22fddc..cbc4f34d 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/EmbeddedLdapServerFactoryBean.java +++ b/test-support/src/main/java/org/springframework/ldap/test/EmbeddedLdapServerFactoryBean.java @@ -22,8 +22,11 @@ import org.springframework.beans.factory.config.AbstractFactoryBean; * @author Mattias Hellborg Arthursson */ public class EmbeddedLdapServerFactoryBean extends AbstractFactoryBean { + private int port; + private String partitionName; + private String partitionSuffix; @Override @@ -52,4 +55,5 @@ public class EmbeddedLdapServerFactoryBean extends AbstractFactoryBeannull. + * @param port the port on which the server will be listening. + * @param defaultPartitionSuffix The default base suffix that will be used for the + * LDAP server. + * @param defaultPartitionName The name to use in the directory server configuration + * for the default base suffix. + * @param principal The principal to use when starting the directory server. + * @param credentials The credentials to use when starting the directory server. + * @param extraSchemas Set of extra schemas to add to the bootstrap schemas of + * ApacheDS. May be null. * @return An unusable DirContext instance. * @throws NamingException If anything goes wrong when starting the server. * @deprecated use {@link #startEmbeddedServer(int, String, String)} instead. */ public static DirContext startApacheDirectoryServer(int port, String defaultPartitionSuffix, - String defaultPartitionName, String principal, String credentials, Set extraSchemas) throws NamingException { + String defaultPartitionName, String principal, String credentials, Set extraSchemas) + throws NamingException { startEmbeddedServer(port, defaultPartitionSuffix, defaultPartitionName); return new DummyDirContext(); } /** - * Start an embedded Apache Directory Server. Only one embedded server will be permitted in the same JVM. - * - * @param port the port on which the server will be listening. - * @param defaultPartitionSuffix The default base suffix that will be used - * for the LDAP server. - * @param defaultPartitionName The name to use in the directory server - * configuration for the default base suffix. - * + * Start an embedded Apache Directory Server. Only one embedded server will be + * permitted in the same JVM. + * @param port the port on which the server will be listening. + * @param defaultPartitionSuffix The default base suffix that will be used for the + * LDAP server. + * @param defaultPartitionName The name to use in the directory server configuration + * for the default base suffix. * @throws IllegalStateException if an embedded server is already started. * @since 1.3.2 */ public static void startEmbeddedServer(int port, String defaultPartitionSuffix, String defaultPartitionName) { - if(embeddedServer != null) { + if (embeddedServer != null) { throw new IllegalStateException("An embedded server is already started"); } try { embeddedServer = EmbeddedLdapServer.newEmbeddedServer(defaultPartitionName, defaultPartitionSuffix, port); - } catch (Exception e) { + } + catch (Exception e) { throw new UncategorizedLdapException("Failed to start embedded server", e); } } @@ -112,20 +111,19 @@ public final class LdapTestUtils { * @deprecated use {@link #startEmbeddedServer(int, String, String)} instead. */ public static DirContext startApacheDirectoryServer(int port, String defaultPartitionSuffix, - String defaultPartitionName, String principal, String credentials) throws NamingException { + String defaultPartitionName, String principal, String credentials) throws NamingException { return LdapTestUtils.startApacheDirectoryServer(port, defaultPartitionSuffix, defaultPartitionName, principal, credentials, null); } /** - * Shuts down the embedded server, if there is one. If no server was previously started in this JVM - * this is silently ignored. - * + * Shuts down the embedded server, if there is one. If no server was previously + * started in this JVM this is silently ignored. * @throws Exception * @since 1.3.2 */ public static void shutdownEmbeddedServer() throws Exception { - if(embeddedServer != null) { + if (embeddedServer != null) { embeddedServer.shutdown(); embeddedServer = null; } @@ -133,8 +131,7 @@ public final class LdapTestUtils { /** * Shut down the in-process Apache Directory Server. - * - * @param principal the principal to be used for authentication. + * @param principal the principal to be used for authentication. * @param credentials the credentials to be used for authentication. * @throws Exception If anything goes wrong when shutting down the server. * @deprecated use {@link #shutdownEmbeddedServer()} instead. @@ -144,11 +141,10 @@ public final class LdapTestUtils { } /** - * Clear the directory sub-tree starting with the node represented by the - * supplied distinguished name. - * + * Clear the directory sub-tree starting with the node represented by the supplied + * distinguished name. * @param contextSource the ContextSource to use for getting a DirContext. - * @param name the distinguished name of the root node. + * @param name the distinguished name of the root node. * @throws NamingException if anything goes wrong removing the sub-tree. */ public static void clearSubContexts(ContextSource contextSource, Name name) throws NamingException { @@ -156,20 +152,21 @@ public final class LdapTestUtils { try { ctx = contextSource.getReadWriteContext(); clearSubContexts(ctx, name); - } finally { + } + finally { try { ctx.close(); - } catch (Exception e) { + } + catch (Exception e) { // Never mind this } } } /** - * Clear the directory sub-tree starting with the node represented by the - * supplied distinguished name. - * - * @param ctx The DirContext to use for cleaning the tree. + * Clear the directory sub-tree starting with the node represented by the supplied + * distinguished name. + * @param ctx The DirContext to use for cleaning the tree. * @param name the distinguished name of the root node. * @throws NamingException if anything goes wrong removing the sub-tree. */ @@ -185,17 +182,21 @@ public final class LdapTestUtils { try { ctx.unbind(childName); - } catch (ContextNotEmptyException e) { + } + catch (ContextNotEmptyException e) { clearSubContexts(ctx, childName); ctx.unbind(childName); } } - } catch (NamingException e) { + } + catch (NamingException e) { LOGGER.debug("Error cleaning sub-contexts", e); - } finally { + } + finally { try { enumeration.close(); - } catch (Exception e) { + } + catch (Exception e) { // Never mind this } } @@ -203,20 +204,21 @@ public final class LdapTestUtils { /** * Load an Ldif file into an LDAP server. - * - * @param contextSource ContextSource to use for getting a DirContext to - * interact with the LDAP server. - * @param ldifFile a Resource representing a valid LDIF file. + * @param contextSource ContextSource to use for getting a DirContext to interact with + * the LDAP server. + * @param ldifFile a Resource representing a valid LDIF file. * @throws IOException if the Resource cannot be read. */ public static void loadLdif(ContextSource contextSource, Resource ldifFile) throws IOException { DirContext context = contextSource.getReadWriteContext(); try { loadLdif(context, ldifFile); - } finally { + } + finally { try { context.close(); - } catch (Exception e) { + } + catch (Exception e) { // This is not the exception we are interested in. } } @@ -235,8 +237,7 @@ public final class LdapTestUtils { private static void loadLdif(DirContext context, Name rootNode, Resource ldifFile) { try { - LdapName baseDn = (LdapName) - context.getEnvironment().get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY); + LdapName baseDn = (LdapName) context.getEnvironment().get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY); LdifParser parser = new LdifParser(ldifFile); parser.open(); @@ -245,16 +246,17 @@ public final class LdapTestUtils { LdapName dn = record.getName(); - if(baseDn != null) { + if (baseDn != null) { dn = LdapUtils.removeFirst(dn, baseDn); } - if(!rootNode.isEmpty()) { + if (!rootNode.isEmpty()) { dn = LdapUtils.prepend(dn, rootNode); } context.bind(dn, null, record); } - } catch (Exception e) { + } + catch (Exception e) { throw new UncategorizedLdapException("Failed to populate LDIF", e); } } @@ -266,12 +268,15 @@ public final class LdapTestUtils { IOUtils.copy(inputStream, new FileOutputStream(tempFile)); LdifFileLoader fileLoader = new LdifFileLoader(directoryService.getSession(), tempFile.getAbsolutePath()); fileLoader.execute(); - } finally { + } + finally { try { tempFile.delete(); - } catch (Exception e) { + } + catch (Exception e) { // Ignore this } } } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/LdifPopulator.java b/test-support/src/main/java/org/springframework/ldap/test/LdifPopulator.java index 4def65c3..315f8fd2 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/LdifPopulator.java +++ b/test-support/src/main/java/org/springframework/ldap/test/LdifPopulator.java @@ -34,11 +34,15 @@ import java.util.List; * @since 2.0 */ public class LdifPopulator implements InitializingBean { + private Resource resource; + private ContextSource contextSource; private String base = ""; + private boolean clean = false; + private String defaultBase; public void setContextSource(ContextSource contextSource) { @@ -66,7 +70,7 @@ public class LdifPopulator implements InitializingBean { Assert.notNull(contextSource, "ContextSource must be specified"); Assert.notNull(resource, "Resource must be specified"); - if(!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(defaultBase))) { + if (!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(defaultBase))) { List lines = IOUtils.readLines(resource.getInputStream()); StringWriter sw = new StringWriter(); @@ -79,10 +83,11 @@ public class LdifPopulator implements InitializingBean { resource = new ByteArrayResource(sw.toString().getBytes("UTF8")); } - if(clean) { + if (clean) { LdapTestUtils.clearSubContexts(contextSource, LdapUtils.emptyLdapName()); } LdapTestUtils.loadLdif(contextSource, resource); } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/TestContextSourceFactoryBean.java b/test-support/src/main/java/org/springframework/ldap/test/TestContextSourceFactoryBean.java index c572c797..6b4f899e 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/TestContextSourceFactoryBean.java +++ b/test-support/src/main/java/org/springframework/ldap/test/TestContextSourceFactoryBean.java @@ -28,6 +28,7 @@ import org.springframework.ldap.support.LdapUtils; * @author Mattias Hellborg Arthursson */ public class TestContextSourceFactoryBean extends AbstractFactoryBean { + private int port; private String defaultPartitionSuffix; @@ -142,4 +143,5 @@ public class TestContextSourceFactoryBean extends AbstractFactoryBean { super.destroyInstance(instance); LdapTestUtils.shutdownEmbeddedServer(); } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServer.java b/test-support/src/main/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServer.java index ba86a578..81e5a01c 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServer.java +++ b/test-support/src/main/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServer.java @@ -36,10 +36,9 @@ public final class EmbeddedLdapServer { this.directoryServer = directoryServer; } - public static EmbeddedLdapServer newEmbeddedServer(String defaultPartitionName, - String defaultPartitionSuffix, int port) throws Exception { - InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig( - defaultPartitionSuffix); + public static EmbeddedLdapServer newEmbeddedServer(String defaultPartitionName, String defaultPartitionSuffix, + int port) throws Exception { + InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig(defaultPartitionSuffix); config.addAdditionalBindCredentials("uid=admin,ou=system", "secret"); config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", port)); @@ -60,4 +59,5 @@ public final class EmbeddedLdapServer { public void shutdown() throws Exception { this.directoryServer.shutDown(true); } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServerFactoryBean.java b/test-support/src/main/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServerFactoryBean.java index 52d612db..b5f24404 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServerFactoryBean.java +++ b/test-support/src/main/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServerFactoryBean.java @@ -22,8 +22,11 @@ import org.springframework.beans.factory.config.AbstractFactoryBean; * @author Mattias Hellborg Arthursson */ public class EmbeddedLdapServerFactoryBean extends AbstractFactoryBean { + private int port; + private String partitionName; + private String partitionSuffix; @Override @@ -52,4 +55,5 @@ public class EmbeddedLdapServerFactoryBean extends AbstractFactoryBean lines = IOUtils.readLines(resource.getInputStream()); StringWriter sw = new StringWriter(); @@ -80,10 +84,11 @@ public class LdifPopulator implements InitializingBean { resource = new ByteArrayResource(sw.toString().getBytes("UTF8")); } - if(clean) { + if (clean) { LdapTestUtils.clearSubContexts(contextSource, LdapUtils.emptyLdapName()); } LdapTestUtils.loadLdif(contextSource, resource); } + } diff --git a/test-support/src/main/java/org/springframework/ldap/test/unboundid/TestContextSourceFactoryBean.java b/test-support/src/main/java/org/springframework/ldap/test/unboundid/TestContextSourceFactoryBean.java index cf87b043..9e890c7a 100644 --- a/test-support/src/main/java/org/springframework/ldap/test/unboundid/TestContextSourceFactoryBean.java +++ b/test-support/src/main/java/org/springframework/ldap/test/unboundid/TestContextSourceFactoryBean.java @@ -98,8 +98,7 @@ public class TestContextSourceFactoryBean extends AbstractFactoryBean list = ldapTemplate.search( - LdapQueryBuilder.query().where("objectclass").is("person"), + List list = ldapTemplate.search(LdapQueryBuilder.query().where("objectclass").is("person"), new AttributesMapper() { - public String mapFromAttributes(Attributes attrs) - throws NamingException { + public String mapFromAttributes(Attributes attrs) throws NamingException { return (String) attrs.get("cn").get(); } }); diff --git a/test-support/src/test/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServerFactoryBeanTest.java b/test-support/src/test/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServerFactoryBeanTest.java index e4108614..5417b7e0 100644 --- a/test-support/src/test/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServerFactoryBeanTest.java +++ b/test-support/src/test/java/org/springframework/ldap/test/unboundid/EmbeddedLdapServerFactoryBeanTest.java @@ -32,11 +32,12 @@ import org.springframework.ldap.query.LdapQueryBuilder; import static org.assertj.core.api.Assertions.assertThat; public class EmbeddedLdapServerFactoryBeanTest { + ClassPathXmlApplicationContext ctx; @After public void setup() { - if(ctx != null) { + if (ctx != null) { ctx.close(); } } @@ -47,11 +48,9 @@ public class EmbeddedLdapServerFactoryBeanTest { LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class); assertThat(ldapTemplate).isNotNull(); - List list = ldapTemplate.search( - LdapQueryBuilder.query().where("objectclass").is("person"), + List list = ldapTemplate.search(LdapQueryBuilder.query().where("objectclass").is("person"), new AttributesMapper() { - public String mapFromAttributes(Attributes attrs) - throws NamingException { + public String mapFromAttributes(Attributes attrs) throws NamingException { return (String) attrs.get("cn").get(); } }); diff --git a/test-support/src/test/java/org/springframework/ldap/test/unboundid/TestContextSourceFactoryBeanTest.java b/test-support/src/test/java/org/springframework/ldap/test/unboundid/TestContextSourceFactoryBeanTest.java index d1979ce4..25d9e070 100644 --- a/test-support/src/test/java/org/springframework/ldap/test/unboundid/TestContextSourceFactoryBeanTest.java +++ b/test-support/src/test/java/org/springframework/ldap/test/unboundid/TestContextSourceFactoryBeanTest.java @@ -32,11 +32,12 @@ import org.springframework.ldap.query.LdapQueryBuilder; import static org.assertj.core.api.Assertions.assertThat; public class TestContextSourceFactoryBeanTest { + ClassPathXmlApplicationContext ctx; @After public void setup() { - if(ctx != null) { + if (ctx != null) { ctx.close(); } } @@ -47,11 +48,9 @@ public class TestContextSourceFactoryBeanTest { LdapTemplate ldapTemplate = ctx.getBean(LdapTemplate.class); assertThat(ldapTemplate).isNotNull(); - List list = ldapTemplate.search( - LdapQueryBuilder.query().where("objectclass").is("person"), + List list = ldapTemplate.search(LdapQueryBuilder.query().where("objectclass").is("person"), new AttributesMapper() { - public String mapFromAttributes(Attributes attrs) - throws NamingException { + public String mapFromAttributes(Attributes attrs) throws NamingException { return (String) attrs.get("cn").get(); } }); diff --git a/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/CompilerInterface.java b/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/CompilerInterface.java index 7669c6d3..3b00a4e4 100755 --- a/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/CompilerInterface.java +++ b/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/CompilerInterface.java @@ -21,14 +21,14 @@ import java.io.InputStream; import java.io.InputStreamReader; public class CompilerInterface { + // Compile the given file - when we can drop Java 5 we'll use the Java 6 compiler API public static void compile(String directory, String file) throws Exception { - ProcessBuilder pb = new ProcessBuilder( - new String[] { "javac", - "-cp", "."+File.pathSeparatorChar+"target"+File.separatorChar+"classes"+ - File.pathSeparatorChar+System.getProperty("java.class.path"), - directory+File.separatorChar+file }); + ProcessBuilder pb = new ProcessBuilder(new String[] { + "javac", "-cp", "." + File.pathSeparatorChar + "target" + File.separatorChar + "classes" + + File.pathSeparatorChar + System.getProperty("java.class.path"), + directory + File.separatorChar + file }); pb.redirectErrorStream(true); Process proc = pb.start(); @@ -41,11 +41,12 @@ public class CompilerInterface { while ((count = isr.read(buf)) > 0) { builder.append(buf, 0, count); } - + boolean ok = proc.waitFor() == 0; if (!ok) { throw new RuntimeException(builder.toString()); } } + } diff --git a/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/IncrementalAttributeMapperITest.java b/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/IncrementalAttributeMapperITest.java index 014af151..8e94bb6c 100644 --- a/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/IncrementalAttributeMapperITest.java +++ b/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/IncrementalAttributeMapperITest.java @@ -50,8 +50,11 @@ import static org.assertj.core.api.Assertions.fail; public class IncrementalAttributeMapperITest extends AbstractJUnit4SpringContextTests { private static final DistinguishedName BASE_DN = new DistinguishedName("ou=dummy,dc=261consulting,dc=local"); + private static final DistinguishedName OU_DN = new DistinguishedName("ou=dummy"); + private static final DistinguishedName GROUP_DN = new DistinguishedName(OU_DN).append("cn", "testgroup"); + private static final String DEFAULT_PASSWORD = "ahcoophah5Oi4oh"; @Autowired @@ -132,7 +135,8 @@ public class IncrementalAttributeMapperITest extends AbstractJUnit4SpringContext public void cleanup() { try { ldapTemplate.lookup(OU_DN); - } catch (NameNotFoundException e) { + } + catch (NameNotFoundException e) { // Nothing to cleanup return; } @@ -142,22 +146,24 @@ public class IncrementalAttributeMapperITest extends AbstractJUnit4SpringContext ldapTemplate.unbind(OU_DN, true); // Everything is deleted return; - } catch (SizeLimitExceededException e) { + } + catch (SizeLimitExceededException e) { // There's more to delete } } } - @Test public void verifyRetrievalOfLotsOfAttributeValues() { DistinguishedName testgroupDn = new DistinguishedName(OU_DN).append("cn", "testgroup"); - // The 'member' attribute consists of > 1500 entries and will not be returned without range specifier. + // The 'member' attribute consists of > 1500 entries and will not be returned + // without range specifier. DirContextOperations ctx = ldapTemplate.lookupContext(testgroupDn); assertThat(ctx.getStringAttribute("member")).isNull(); - DefaultIncrementalAttributesMapper attributeMapper = new DefaultIncrementalAttributesMapper(new String[]{"member", "cn"}); + DefaultIncrementalAttributesMapper attributeMapper = new DefaultIncrementalAttributesMapper( + new String[] { "member", "cn" }); assertThat(attributeMapper.hasMore()).as("There should be more results to get").isTrue(); String[] attributesArray = attributeMapper.getAttributesForLookup(); @@ -165,7 +171,8 @@ public class IncrementalAttributeMapperITest extends AbstractJUnit4SpringContext assertThat(attributesArray[0]).isEqualTo("member"); assertThat(attributesArray[1]).isEqualTo("cn"); - // First iteration - there should now be more members left, but all cn values should have been collected. + // First iteration - there should now be more members left, but all cn values + // should have been collected. ldapTemplate.lookup(testgroupDn, attributesArray, attributeMapper); assertThat(attributeMapper.hasMore()).as("There should be more results to get").isTrue(); @@ -195,10 +202,9 @@ public class IncrementalAttributeMapperITest extends AbstractJUnit4SpringContext transactionTemplate.execute(new TransactionCallback() { @Override public Object doInTransaction(TransactionStatus status) { - ModificationItem modificationItem = new ModificationItem( - DirContext.ADD_ATTRIBUTE, + ModificationItem modificationItem = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("member", buildUserRefDn("test" + 1501))); - ldapTemplate.modifyAttributes(GROUP_DN, new ModificationItem[]{modificationItem}); + ldapTemplate.modifyAttributes(GROUP_DN, new ModificationItem[] { modificationItem }); // The below should cause a rollback throw new RuntimeException("Simulate some failure"); @@ -206,16 +212,19 @@ public class IncrementalAttributeMapperITest extends AbstractJUnit4SpringContext }); fail("RuntimeException expected"); - } catch (RuntimeException expected) { - DefaultIncrementalAttributesMapper attributeMapper = new DefaultIncrementalAttributesMapper(new String[]{"member"}); + } + catch (RuntimeException expected) { + DefaultIncrementalAttributesMapper attributeMapper = new DefaultIncrementalAttributesMapper( + new String[] { "member" }); while (attributeMapper.hasMore()) { ldapTemplate.lookup(GROUP_DN, attributeMapper.getAttributesForLookup(), attributeMapper); } // LDAP-234: After rollback the attribute values were cleared after rollback assertThat( - DefaultIncrementalAttributesMapper.lookupAttributeValues( - ldapTemplate, GROUP_DN, "member").size()).isEqualTo(1501); + DefaultIncrementalAttributesMapper.lookupAttributeValues(ldapTemplate, GROUP_DN, "member").size()) + .isEqualTo(1501); } } + } diff --git a/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/SchemaToJavaAdITest.java b/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/SchemaToJavaAdITest.java index e62f8b28..b546b4c5 100644 --- a/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/SchemaToJavaAdITest.java +++ b/test/integration-tests-ad/src/test/java/org/springframework/ldap/itest/ad/SchemaToJavaAdITest.java @@ -46,12 +46,15 @@ import static org.assertj.core.api.Assertions.assertThat; // Tests the generation of entry Java classes from LDAP schema public final class SchemaToJavaAdITest { + private static final Logger LOG = LoggerFactory.getLogger(SchemaToJavaAdITest.class); private static final DistinguishedName baseName = new DistinguishedName("dc=261consulting,dc=local"); - private static final String tempDir=System.getProperty("java.io.tmpdir"); + private static final String tempDir = System.getProperty("java.io.tmpdir"); + private static final String USER_DN = "CN=ldaptest,CN=Users,DC=261consulting,DC=local"; + private static final String PASSWORD = "Buc8xe6AZiewoh7"; // These unit tests require this port to free on localhost @@ -60,6 +63,7 @@ public final class SchemaToJavaAdITest { private ConverterManagerImpl converterManager; private LdapContextSource contextSource; + private LdapTemplate ldapTemplate; @Before @@ -92,9 +96,12 @@ public final class SchemaToJavaAdITest { contextSource.setPassword(PASSWORD); contextSource.setPooled(false); contextSource.setBase("dc=261consulting,dc=local"); - HashMap baseEnvironment = new HashMap() {{ - put("java.naming.ldap.attributes.binary", "thumbnailLogo replPropertyMetaData partialAttributeSet registeredAddress userPassword telexNumber partialAttributeDeletionList mS-DS-ConsistencyGuid attributeCertificateAttribute thumbnailPhoto teletexTerminalIdentifier replUpToDateVector dSASignature objectGUID"); - }}; + HashMap baseEnvironment = new HashMap() { + { + put("java.naming.ldap.attributes.binary", + "thumbnailLogo replPropertyMetaData partialAttributeSet registeredAddress userPassword telexNumber partialAttributeDeletionList mS-DS-ConsistencyGuid attributeCertificateAttribute thumbnailPhoto teletexTerminalIdentifier replUpToDateVector dSASignature objectGUID"); + } + }; contextSource.setBaseEnvironmentProperties(baseEnvironment); contextSource.afterPropertiesSet(); @@ -103,7 +110,8 @@ public final class SchemaToJavaAdITest { cleanup(); DirContextAdapter ctx = new DirContextAdapter("cn=William Hartnell,cn=Users"); - ctx.setAttributeValues("objectclass", new String[]{"person","inetorgperson","organizationalperson","top"}); + ctx.setAttributeValues("objectclass", + new String[] { "person", "inetorgperson", "organizationalperson", "top" }); ctx.setAttributeValue("cn", "William Hartnell"); ctx.addAttributeValue("description", "First Doctor"); ctx.addAttributeValue("description", "Grumpy"); @@ -121,47 +129,41 @@ public final class SchemaToJavaAdITest { // Figure out the path of the created Java file private static String calculateOutputDirectory(String outputDir, String packageName) { // Convert the package name to a path - Pattern pattern=Pattern.compile("\\."); - Matcher matcher=pattern.matcher(packageName); - String sepToUse=File.separator; + Pattern pattern = Pattern.compile("\\."); + Matcher matcher = pattern.matcher(packageName); + String sepToUse = File.separator; if (sepToUse.equals("\\")) { - sepToUse="\\\\"; + sepToUse = "\\\\"; } - return outputDir+File.separator+matcher.replaceAll(sepToUse); + return outputDir + File.separator + matcher.replaceAll(sepToUse); } // Due of the nature of the code under test this unit test is a little unusual: // // 1) Generate an entry class corresponding to objects classes - // "inetorgperson, organizationalperson, person, top" - // using the SchemaToJavaTool + // "inetorgperson, organizationalperson, person, top" + // using the SchemaToJavaTool // 2) Compile the generated code // 3) Create an OdmManager to managing the newly created - // entry class. + // entry class. // 4) Use this OdmManager to read an entry from LDAP and check the results. // @Test public void verifySchemaToJavaOnAd() throws Exception { - final String className="Person"; - final String packageName="org.springframework.ldap.odm.testclasses"; + final String className = "Person"; + final String packageName = "org.springframework.ldap.odm.testclasses"; File tempFile = File.createTempFile("test-odm-syntax-to-class-map", ".txt"); FileUtils.copyInputStreamToFile(new ClassPathResource("/syntax-to-class-map.txt").getInputStream(), tempFile); // Add classes dir to class path - needed for compilation System.setProperty("java.class.path", - System.getProperty("java.class.path")+File.pathSeparator+"target/classes"); + System.getProperty("java.class.path") + File.pathSeparator + "target/classes"); - String[] flags=new String[] { - "--url", "ldaps://127.0.0.1:" + port, - "--objectclasses", "organizationalperson", - "--syntaxmap", tempFile.getAbsolutePath(), - "--class", className, - "--package", packageName, - "--outputdir", tempDir, - "--username", USER_DN, - "--password", PASSWORD}; + String[] flags = new String[] { "--url", "ldaps://127.0.0.1:" + port, "--objectclasses", "organizationalperson", + "--syntaxmap", tempFile.getAbsolutePath(), "--class", className, "--package", packageName, + "--outputdir", tempDir, "--username", USER_DN, "--password", PASSWORD }; // Generate the code using SchemaToJava SchemaToJava.main(flags); @@ -171,42 +173,43 @@ public final class SchemaToJavaAdITest { // Java 5 - we'll use the Java 6 Compiler API once we can drop support for Java 5. String javaDir = calculateOutputDirectory(tempDir, packageName); - CompilerInterface.compile(javaDir, className+".java"); + CompilerInterface.compile(javaDir, className + ".java"); // Java 5 // OK it compiles so lets load our new class URL[] urls = new URL[] { new File(tempDir).toURI().toURL() }; URLClassLoader ucl = new URLClassLoader(urls, getClass().getClassLoader()); - Class clazz = ucl.loadClass(packageName+"."+className); + Class clazz = ucl.loadClass(packageName + "." + className); // Create our OdmManager using our new class OdmManagerImpl odmManager = new OdmManagerImpl(converterManager, contextSource); odmManager.addManagedClass(clazz); // And try reading from the directory using it - DistinguishedName testDn=new DistinguishedName("cn=William Hartnell,cn=Users"); - Object fromDirectory=odmManager.read(clazz, testDn); + DistinguishedName testDn = new DistinguishedName("cn=William Hartnell,cn=Users"); + Object fromDirectory = odmManager.read(clazz, testDn); LOG.debug(String.format("Read - %1$s", fromDirectory)); // Check some returned values - Method getDnMethod=clazz.getMethod("getDn"); - Object dn=getDnMethod.invoke(fromDirectory); + Method getDnMethod = clazz.getMethod("getDn"); + Object dn = getDnMethod.invoke(fromDirectory); assertThat(dn).isEqualTo(testDn); - Method getCnIteratorMethod=clazz.getMethod("getCn"); + Method getCnIteratorMethod = clazz.getMethod("getCn"); @SuppressWarnings("unchecked") - String cn=(String)getCnIteratorMethod.invoke(fromDirectory); + String cn = (String) getCnIteratorMethod.invoke(fromDirectory); assertThat(cn).isEqualTo("William Hartnell"); - Method telephoneNumberIteratorMethod=clazz.getMethod("getTelephoneNumber"); + Method telephoneNumberIteratorMethod = clazz.getMethod("getTelephoneNumber"); @SuppressWarnings("unchecked") - String telephoneNumber=(String)telephoneNumberIteratorMethod.invoke(fromDirectory); + String telephoneNumber = (String) telephoneNumberIteratorMethod.invoke(fromDirectory); assertThat(telephoneNumber).isEqualTo("1"); // Reread and check whether equals and hashCode are at least sane - Object fromDirectory2=odmManager.read(clazz, testDn); + Object fromDirectory2 = odmManager.read(clazz, testDn); assertThat(fromDirectory2).isEqualTo(fromDirectory); assertThat(fromDirectory2.hashCode()).isEqualTo(fromDirectory.hashCode()); } + } diff --git a/test/integration-tests-openldap/src/main/java/org/springframework/ldap/AllMatchHostnameVerifier.java b/test/integration-tests-openldap/src/main/java/org/springframework/ldap/AllMatchHostnameVerifier.java index 45bc66b9..064644ec 100644 --- a/test/integration-tests-openldap/src/main/java/org/springframework/ldap/AllMatchHostnameVerifier.java +++ b/test/integration-tests-openldap/src/main/java/org/springframework/ldap/AllMatchHostnameVerifier.java @@ -23,8 +23,10 @@ import javax.net.ssl.SSLSession; * @author Mattias Hellborg Arthursson */ public class AllMatchHostnameVerifier implements HostnameVerifier { + @Override public boolean verify(String s, SSLSession sslSession) { return true; } + } diff --git a/test/integration-tests-openldap/src/main/java/org/springframework/ldap/DigestMd5ContextSourceEc2InstanceLaunchingFactoryBean.java b/test/integration-tests-openldap/src/main/java/org/springframework/ldap/DigestMd5ContextSourceEc2InstanceLaunchingFactoryBean.java index a06f77b9..1dd0ac1a 100644 --- a/test/integration-tests-openldap/src/main/java/org/springframework/ldap/DigestMd5ContextSourceEc2InstanceLaunchingFactoryBean.java +++ b/test/integration-tests-openldap/src/main/java/org/springframework/ldap/DigestMd5ContextSourceEc2InstanceLaunchingFactoryBean.java @@ -24,20 +24,23 @@ import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.ContextSourceEc2InstanceLaunchingFactoryBean; /** - * FactoryBean for testing LDAP TLS connections on an Amazon EC2 image launched by superclass. + * FactoryBean for testing LDAP TLS connections on an Amazon EC2 image launched by + * superclass. */ -public class DigestMd5ContextSourceEc2InstanceLaunchingFactoryBean extends ContextSourceEc2InstanceLaunchingFactoryBean { - +public class DigestMd5ContextSourceEc2InstanceLaunchingFactoryBean + extends ContextSourceEc2InstanceLaunchingFactoryBean { + protected void setAdditionalContextSourceProperties(LdapContextSource ctx, final String dnsName) { DigestMd5DirContextAuthenticationStrategy authenticationStrategy = new DigestMd5DirContextAuthenticationStrategy(); - -// authenticationStrategy.setHostnameVerifier(new HostnameVerifier() { -// public boolean verify(String hostname, SSLSession session) { -// return hostname.equals(dnsName); -// } -// }); + + // authenticationStrategy.setHostnameVerifier(new HostnameVerifier() { + // public boolean verify(String hostname, SSLSession session) { + // return hostname.equals(dnsName); + // } + // }); ctx.setAuthenticationStrategy(authenticationStrategy); ctx.setPooled(false); } + } diff --git a/test/integration-tests-openldap/src/main/java/org/springframework/ldap/TlsContextSourceEc2InstanceLaunchingFactoryBean.java b/test/integration-tests-openldap/src/main/java/org/springframework/ldap/TlsContextSourceEc2InstanceLaunchingFactoryBean.java index 400aaeaa..2b76a791 100644 --- a/test/integration-tests-openldap/src/main/java/org/springframework/ldap/TlsContextSourceEc2InstanceLaunchingFactoryBean.java +++ b/test/integration-tests-openldap/src/main/java/org/springframework/ldap/TlsContextSourceEc2InstanceLaunchingFactoryBean.java @@ -23,13 +23,14 @@ import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.ContextSourceEc2InstanceLaunchingFactoryBean; /** - * FactoryBean for testing LDAP TLS connections on an Amazon EC2 image launched by superclass. + * FactoryBean for testing LDAP TLS connections on an Amazon EC2 image launched by + * superclass. */ public class TlsContextSourceEc2InstanceLaunchingFactoryBean extends ContextSourceEc2InstanceLaunchingFactoryBean { - + protected void setAdditionalContextSourceProperties(LdapContextSource ctx, final String dnsName) { DefaultTlsDirContextAuthenticationStrategy authenticationStrategy = new DefaultTlsDirContextAuthenticationStrategy(); - + authenticationStrategy.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return hostname.equals(dnsName); @@ -39,4 +40,5 @@ public class TlsContextSourceEc2InstanceLaunchingFactoryBean extends ContextSour ctx.setAuthenticationStrategy(authenticationStrategy); ctx.setPooled(false); } + } diff --git a/test/integration-tests-openldap/src/main/java/org/springframework/ldap/control/Person.java b/test/integration-tests-openldap/src/main/java/org/springframework/ldap/control/Person.java index 95143717..5df091ee 100644 --- a/test/integration-tests-openldap/src/main/java/org/springframework/ldap/control/Person.java +++ b/test/integration-tests-openldap/src/main/java/org/springframework/ldap/control/Person.java @@ -22,83 +22,82 @@ import org.apache.commons.lang.builder.ToStringStyle; /** * Simple class representing a single person. - * + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ public class Person { - private String fullName; - private String lastName; + private String fullName; - private String description; + private String lastName; - private String country; + private String description; - private String company; + private String country; - private String phone; + private String company; - public String getDescription() { - return description; - } + private String phone; - public void setDescription(String description) { - this.description = description; - } + public String getDescription() { + return description; + } - public String getFullName() { - return fullName; - } + public void setDescription(String description) { + this.description = description; + } - public void setFullName(String fullName) { - this.fullName = fullName; - } + public String getFullName() { + return fullName; + } - public String getLastName() { - return lastName; - } + public void setFullName(String fullName) { + this.fullName = fullName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public String getLastName() { + return lastName; + } - public String getCompany() { - return company; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } - public void setCompany(String company) { - this.company = company; - } + public String getCompany() { + return company; + } - public String getCountry() { - return country; - } + public void setCompany(String company) { + this.company = company; + } - public void setCountry(String country) { - this.country = country; - } + public String getCountry() { + return country; + } - public String getPhone() { - return phone; - } + public void setCountry(String country) { + this.country = country; + } - public void setPhone(String phone) { - this.phone = phone; - } + public String getPhone() { + return phone; + } - public boolean equals(Object obj) { - return EqualsBuilder.reflectionEquals( - this, obj); - } + public void setPhone(String phone) { + this.phone = phone; + } - public int hashCode() { - return HashCodeBuilder - .reflectionHashCode(this); - } + public boolean equals(Object obj) { + return EqualsBuilder.reflectionEquals(this, obj); + } + + public int hashCode() { + return HashCodeBuilder.reflectionHashCode(this); + } + + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } - public String toString() { - return ToStringBuilder.reflectionToString( - this, ToStringStyle.MULTI_LINE_STYLE); - } } diff --git a/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/control/PagedSearchITest.java b/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/control/PagedSearchITest.java index d7329962..9a4358e6 100644 --- a/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/control/PagedSearchITest.java +++ b/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/control/PagedSearchITest.java @@ -58,9 +58,7 @@ public class PagedSearchITest extends AbstractJUnit4SpringContextTests { @Before public void prepareTestedData() throws IOException, NamingException { - LdapTestUtils.cleanAndSetup( - contextSource, - LdapUtils.newLdapName("ou=People"), + LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.newLdapName("ou=People"), new ClassPathResource("/setup_data.ldif")); } @@ -74,41 +72,25 @@ public class PagedSearchITest extends AbstractJUnit4SpringContextTests { final SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); - // There should be three pages of three entries, and one final page with one entry + // There should be three pages of three entries, and one final page with one entry final PagedResultsDirContextProcessor processor = new PagedResultsDirContextProcessor(3); SingleContextSource.doWithSingleContext(contextSource, new LdapOperationsCallback() { @Override public Object doWithLdapOperations(LdapOperations operations) { - List result = operations.search( - "ou=People", - "(&(objectclass=person))", - searchControls, - CN_ATTRIBUTES_MAPPER, + List result = operations.search("ou=People", "(&(objectclass=person))", searchControls, + CN_ATTRIBUTES_MAPPER, processor); + assertThat(result).hasSize(3); + + result = operations.search("ou=People", "(&(objectclass=person))", searchControls, CN_ATTRIBUTES_MAPPER, processor); assertThat(result).hasSize(3); - result = operations.search( - "ou=People", - "(&(objectclass=person))", - searchControls, - CN_ATTRIBUTES_MAPPER, + result = operations.search("ou=People", "(&(objectclass=person))", searchControls, CN_ATTRIBUTES_MAPPER, processor); assertThat(result).hasSize(3); - result = operations.search( - "ou=People", - "(&(objectclass=person))", - searchControls, - CN_ATTRIBUTES_MAPPER, - processor); - assertThat(result).hasSize(3); - - result = operations.search( - "ou=People", - "(&(objectclass=person))", - searchControls, - CN_ATTRIBUTES_MAPPER, + result = operations.search("ou=People", "(&(objectclass=person))", searchControls, CN_ATTRIBUTES_MAPPER, processor); assertThat(result).hasSize(1); @@ -118,4 +100,5 @@ public class PagedSearchITest extends AbstractJUnit4SpringContextTests { }); } + } diff --git a/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/core/LdapTemplateSearchResultITest.java b/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/core/LdapTemplateSearchResultITest.java index d38f0987..2df4449b 100644 --- a/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/core/LdapTemplateSearchResultITest.java +++ b/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/core/LdapTemplateSearchResultITest.java @@ -39,7 +39,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Verifies that LdapTemplate search methods work against OpenLDAP with TLS. - * + * * @author Mattias Hellborg Arthursson */ @ContextConfiguration(locations = { "/conf/ldapTemplateTestContext-tls.xml" }) @@ -74,9 +74,7 @@ public class LdapTemplateSearchResultITest extends AbstractJUnit4SpringContextTe @Before public void prepareTestedInstance() throws Exception { - LdapTestUtils.cleanAndSetup( - contextSource, - LdapUtils.newLdapName("ou=People"), + LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.newLdapName("ou=People"), new ClassPathResource("/setup_data.ldif")); attributesMapper = new AttributeCheckAttributesMapper(); @@ -137,8 +135,8 @@ public class LdapTemplateSearchResultITest extends AbstractJUnit4SpringContextTe attributesMapper.setExpectedAttributes(CN_SN_ATTRS); attributesMapper.setExpectedValues(CN_SN_VALUES); attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested - .search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, attributesMapper); + List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + attributesMapper); assertThat(list).hasSize(1); } @@ -154,7 +152,8 @@ public class LdapTemplateSearchResultITest extends AbstractJUnit4SpringContextTe public void testSearch_SearchScope_ContextMapper() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, contextMapper); + List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, + contextMapper); assertThat(list).hasSize(1); } @@ -163,7 +162,8 @@ public class LdapTemplateSearchResultITest extends AbstractJUnit4SpringContextTe contextMapper.setExpectedAttributes(CN_SN_ATTRS); contextMapper.setExpectedValues(CN_SN_VALUES); contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, contextMapper); + List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, + CN_SN_ATTRS, contextMapper); assertThat(list).hasSize(1); } @@ -179,7 +179,8 @@ public class LdapTemplateSearchResultITest extends AbstractJUnit4SpringContextTe public void testSearch_SearchScope_ContextMapper_Name() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, contextMapper); + List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, + contextMapper); assertThat(list).hasSize(1); } @@ -188,7 +189,9 @@ public class LdapTemplateSearchResultITest extends AbstractJUnit4SpringContextTe contextMapper.setExpectedAttributes(CN_SN_ATTRS); contextMapper.setExpectedValues(CN_SN_VALUES); contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, contextMapper); + List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, + CN_SN_ATTRS, contextMapper); assertThat(list).hasSize(1); } + } diff --git a/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/core/support/DigestMd5AuthenticationITest.java b/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/core/support/DigestMd5AuthenticationITest.java index 83035418..08d6290f 100644 --- a/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/core/support/DigestMd5AuthenticationITest.java +++ b/test/integration-tests-openldap/src/test/java/org/springframework/ldap/itest/core/support/DigestMd5AuthenticationITest.java @@ -34,11 +34,12 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Integration test to verify DIGEST-MD5 authentication support. - * + * * @author Marvin S. Addison */ @ContextConfiguration(locations = { "/conf/ldapTemplateDigestMd5TestContext.xml" }) public class DigestMd5AuthenticationITest extends AbstractJUnit4SpringContextTests { + @Autowired private LdapTemplate ldapTemplate; @@ -48,9 +49,7 @@ public class DigestMd5AuthenticationITest extends AbstractJUnit4SpringContextTes @Before public void prepareTestedInstance() throws Exception { - LdapTestUtils.cleanAndSetup( - contextSource, - LdapUtils.newLdapName("ou=People"), + LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.newLdapName("ou=People"), new ClassPathResource("/setup_data.ldif")); } @@ -64,4 +63,5 @@ public class DigestMd5AuthenticationITest extends AbstractJUnit4SpringContextTes DirContext ctxt = ldapTemplate.getContextSource().getContext("some.person1", "password"); assertThat(ctxt).isNotNull(); } + } diff --git a/test/integration-tests-sunone/src/test/java/org/springframework/ldap/itest/core/LdapTemplateVirtualListViewSearchITest.java b/test/integration-tests-sunone/src/test/java/org/springframework/ldap/itest/core/LdapTemplateVirtualListViewSearchITest.java index c4de4f48..566014b9 100644 --- a/test/integration-tests-sunone/src/test/java/org/springframework/ldap/itest/core/LdapTemplateVirtualListViewSearchITest.java +++ b/test/integration-tests-sunone/src/test/java/org/springframework/ldap/itest/core/LdapTemplateVirtualListViewSearchITest.java @@ -37,65 +37,60 @@ import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import static org.assertj.core.api.Assertions.assertThat; /** - * Integration tests for the virtual list view search result capability of - * LdapTemplate. The test should reflect the example in Chapter 7 of the Virtual + * Integration tests for the virtual list view search result capability of LdapTemplate. + * The test should reflect the example in Chapter 7 of the + * Virtual * List View RFC draft. * - *
    Here we walk through the client-server interaction for a - * specific virtual list view example: The task is to display a list of all - * 78564 persons in the US company "Ace Industry". This will be done by creating - * a graphical user interface object to display the list contents, and by - * repeatedly sending different versions of the same virtual list view search - * request to the server. The list view displays 20 entries on the screen at a - * time. + *
    Here we walk through the client-server interaction for a specific virtual + * list view example: The task is to display a list of all 78564 persons in the US company + * "Ace Industry". This will be done by creating a graphical user interface object to + * display the list contents, and by repeatedly sending different versions of the same + * virtual list view search request to the server. The list view displays 20 entries on + * the screen at a time. *

    - * We form a search with baseObject of "o=Ace Industry,c=us"; scope of - * wholeSubtree; and filter of "(objectClass=person)". We attach a server-side - * sort control [SSS] to the search request, specifying ascending sort on - * attribute "cn". To this search request, we attach a virtual list view request - * control with contents determined by the user activity and send the search - * request to the server. We display the results from each search result entry - * in the list window and update the slider position. + * We form a search with baseObject of "o=Ace Industry,c=us"; scope of wholeSubtree; and + * filter of "(objectClass=person)". We attach a server-side sort control [SSS] to the + * search request, specifying ascending sort on attribute "cn". To this search request, we + * attach a virtual list view request control with contents determined by the user + * activity and send the search request to the server. We display the results from each + * search result entry in the list window and update the slider position. *

    - * When the list view is first displayed, we want to initialize the contents - * showing the beginning of the list. Therefore, we set beforeCount to 0, - * afterCount to 19, contentCount to 0, offset to 1 and send the request to the - * server. The server duly returns the first 20 entries in the list, plus a - * content count of 78564 and targetPosition of 1. We therefore leave the scroll - * bar slider at its current location (the top of its range). + * When the list view is first displayed, we want to initialize the contents showing the + * beginning of the list. Therefore, we set beforeCount to 0, afterCount to 19, + * contentCount to 0, offset to 1 and send the request to the server. The server duly + * returns the first 20 entries in the list, plus a content count of 78564 and + * targetPosition of 1. We therefore leave the scroll bar slider at its current location + * (the top of its range). *

    - * Say that next the user drags the scroll bar slider down to the bottom of its - * range. We now wish to display the last 20 entries in the list, so we set - * beforeCount to 19, afterCount to 0, contentCount to 78564, offset to 78564 - * and send the request to the server. The server returns the last 20 entries in - * the list, plus a content count of 78564 and a targetPosition of 78564. + * Say that next the user drags the scroll bar slider down to the bottom of its range. We + * now wish to display the last 20 entries in the list, so we set beforeCount to 19, + * afterCount to 0, contentCount to 78564, offset to 78564 and send the request to the + * server. The server returns the last 20 entries in the list, plus a content count of + * 78564 and a targetPosition of 78564. *

    - * Next the user presses a page up key. Our page size is 20, so we set - * beforeCount to 0, afterCount to 19, contentCount to 78564, offset to - * 78564-19-20 and send the request to the server. The server returns the - * preceding 20 entries in the list, plus a content count of 78564 and a - * targetPosition of 78525. + * Next the user presses a page up key. Our page size is 20, so we set beforeCount to 0, + * afterCount to 19, contentCount to 78564, offset to 78564-19-20 and send the request to + * the server. The server returns the preceding 20 entries in the list, plus a content + * count of 78564 and a targetPosition of 78525. *

    - * Now the user grabs the scroll bar slider and drags it to 68% of the way down - * its travel. 68% of 78564 is 53424 so we set beforeCount to 9, afterCount to - * 10, contentCount to 78564, offset to 53424 and send the request to the - * server. The server returns the preceding 20 entries in the list, plus a - * content count of 78564 and a targetPosition of 53424. + * Now the user grabs the scroll bar slider and drags it to 68% of the way down its + * travel. 68% of 78564 is 53424 so we set beforeCount to 9, afterCount to 10, + * contentCount to 78564, offset to 53424 and send the request to the server. The server + * returns the preceding 20 entries in the list, plus a content count of 78564 and a + * targetPosition of 53424. *

    - * Lastly, the user types the letter "B". We set beforeCount to 9, afterCount to - * 10 and greaterThanOrEqual to "B". The server finds the first entry in the - * list not less than "B", let's say "Babs Jensen", and returns the nine - * preceding entries, the target entry, and the proceeding 10 entries. The - * server returns a content count of 78564 and a targetPosition of 5234 and so - * the client updates its scroll bar slider to 6.7% of full scale.

    + * Lastly, the user types the letter "B". We set beforeCount to 9, afterCount to 10 and + * greaterThanOrEqual to "B". The server finds the first entry in the list not less than + * "B", let's say "Babs Jensen", and returns the nine preceding entries, the target entry, + * and the proceeding 10 entries. The server returns a content count of 78564 and a + * targetPosition of 5234 and so the client updates its scroll bar slider to 6.7% of full + * scale.
    * * @author Ulrik Sandberg */ @ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) -public class LdapTemplateVirtualListViewSearchITest extends - AbstractJUnit4SpringContextTests { +public class LdapTemplateVirtualListViewSearchITest extends AbstractJUnit4SpringContextTests { @Autowired private LdapTemplate tested; @@ -136,8 +131,7 @@ public class LdapTemplateVirtualListViewSearchITest extends callbackHandler = new ContextMapperCallbackHandler(contextMapper); requestControl = new VirtualListViewControlDirContextProcessor(20); - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); + tested.search(BASE_STRING, FILTER_STRING, searchControls, callbackHandler, requestControl); cookie = requestControl.getCookie(); // assert that total count is still 78564 @@ -161,11 +155,9 @@ public class LdapTemplateVirtualListViewSearchITest extends callbackHandler = new ContextMapperCallbackHandler(contextMapper); // we need a constructor that takes a beforeCount and an afterCount - requestControl = new VirtualListViewControlDirContextProcessor(20, - 78564, listSize, cookie); + requestControl = new VirtualListViewControlDirContextProcessor(20, 78564, listSize, cookie); - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); + tested.search(BASE_STRING, FILTER_STRING, searchControls, callbackHandler, requestControl); cookie = requestControl.getCookie(); // assert that total count is still 78564 @@ -189,11 +181,9 @@ public class LdapTemplateVirtualListViewSearchITest extends callbackHandler = new ContextMapperCallbackHandler(contextMapper); // we need a constructor that takes a beforeCount and an afterCount - requestControl = new VirtualListViewControlDirContextProcessor(20, - 78564 - 19 - 20, listSize, cookie); + requestControl = new VirtualListViewControlDirContextProcessor(20, 78564 - 19 - 20, listSize, cookie); - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); + tested.search(BASE_STRING, FILTER_STRING, searchControls, callbackHandler, requestControl); cookie = requestControl.getCookie(); // assert that total count is still 78564 @@ -217,12 +207,10 @@ public class LdapTemplateVirtualListViewSearchITest extends callbackHandler = new ContextMapperCallbackHandler(contextMapper); // we need a constructor that takes a beforeCount and an afterCount - requestControl = new VirtualListViewControlDirContextProcessor(20, - 68, listSize, cookie); + requestControl = new VirtualListViewControlDirContextProcessor(20, 68, listSize, cookie); requestControl.setOffsetPercentage(true); - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); + tested.search(BASE_STRING, FILTER_STRING, searchControls, callbackHandler, requestControl); cookie = requestControl.getCookie(); // assert that total count is still 78564 @@ -247,12 +235,10 @@ public class LdapTemplateVirtualListViewSearchITest extends // we need a constructor that takes a String for 'greaterThanOrEqual' // also beforeCount and afterCount - requestControl = new VirtualListViewControlDirContextProcessor(20, - 5234, listSize, cookie); + requestControl = new VirtualListViewControlDirContextProcessor(20, 5234, listSize, cookie); requestControl.setOffsetPercentage(true); - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); + tested.search(BASE_STRING, FILTER_STRING, searchControls, callbackHandler, requestControl); cookie = requestControl.getCookie(); // assert that total count is still 78564 @@ -269,4 +255,5 @@ public class LdapTemplateVirtualListViewSearchITest extends person = (Person) list.get(9); assertThat(person.getFullname()).isEqualTo("Babs Jensen"); } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/LdapGroupDao.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/LdapGroupDao.java index dd9c616a..a5f4a6d3 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/LdapGroupDao.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/LdapGroupDao.java @@ -22,11 +22,10 @@ import org.springframework.ldap.core.support.BaseLdapPathAware; import javax.naming.Name; /** - * * @author Mattias Hellborg Arthursson */ -public class LdapGroupDao implements BaseLdapPathAware -{ +public class LdapGroupDao implements BaseLdapPathAware { + private Name basePath; public LdapGroupDao() { @@ -40,4 +39,5 @@ public class LdapGroupDao implements BaseLdapPathAware public Name getBasePath() { return basePath; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/NoAdTest.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/NoAdTest.java index a88ef6c6..6f49c2ae 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/NoAdTest.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/NoAdTest.java @@ -20,4 +20,5 @@ package org.springframework.ldap.itest; * @author Mattias Hellborg Arthursson */ public interface NoAdTest { + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/Person.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/Person.java index bff29e5f..be78b5d6 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/Person.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/Person.java @@ -21,10 +21,11 @@ import org.apache.commons.lang.builder.ToStringStyle; /** * Dummy bean to be used in the LdapTemplate integration tests. - * + * * @author Mattias Hellborg Arthursson */ public class Person { + private String fullname; private String lastname; @@ -64,9 +65,10 @@ public class Person { public void setPhone(String phone) { this.phone = phone; } - + @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/PersonAttributesMapper.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/PersonAttributesMapper.java index b0894f4e..0cad3eb9 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/PersonAttributesMapper.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/PersonAttributesMapper.java @@ -21,22 +21,20 @@ import javax.naming.directory.Attributes; import org.springframework.ldap.core.AttributesMapper; - /** * Dummy implementation of AttributesMapper for use in integration tests. - * + * * @author Mattias Hellborg Arthursson - * + * */ public class PersonAttributesMapper implements AttributesMapper { /** * Maps the given attributes into a {@link Person} object. - * + * * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes) */ - public Person mapFromAttributes(Attributes attributes) - throws NamingException { + public Person mapFromAttributes(Attributes attributes) throws NamingException { Person person = new Person(); person.setFullname((String) attributes.get("cn").get()); person.setLastname((String) attributes.get("sn").get()); @@ -44,4 +42,5 @@ public class PersonAttributesMapper implements AttributesMapper { person.setDescription((String) attributes.get("description").get()); return person; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/PersonContextMapper.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/PersonContextMapper.java index f2c07d5b..df3de700 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/PersonContextMapper.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/PersonContextMapper.java @@ -22,7 +22,7 @@ import org.springframework.ldap.core.support.AbstractContextMapper; /** * Dummy implemention of ContextMapper for use in the integration tests and for * illustration purposes. - * + * * @author Mattias Hellborg Arthursson */ public class PersonContextMapper extends AbstractContextMapper { @@ -36,4 +36,5 @@ public class PersonContextMapper extends AbstractContextMapper { return person; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/DummyDistinguishedNameConsumer.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/DummyDistinguishedNameConsumer.java index 8505a3c2..b0166daa 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/DummyDistinguishedNameConsumer.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/DummyDistinguishedNameConsumer.java @@ -18,12 +18,13 @@ package org.springframework.ldap.itest.core; import org.springframework.ldap.core.DistinguishedName; /** - * Dummy implementation of a class that has a {@link DistinguishedName} setter, - * used for testing purposes. - * + * Dummy implementation of a class that has a {@link DistinguishedName} setter, used for + * testing purposes. + * * @author Mattias Hellborg Arthursson */ public class DummyDistinguishedNameConsumer { + private DistinguishedName distinguishedName; public DistinguishedName getDistinguishedName() { @@ -33,4 +34,5 @@ public class DummyDistinguishedNameConsumer { public void setDistinguishedName(DistinguishedName distinguishedName) { this.distinguishedName = distinguishedName; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/support/DummyBaseLdapNameAware.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/support/DummyBaseLdapNameAware.java index d3a96d60..8c0346e4 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/support/DummyBaseLdapNameAware.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/support/DummyBaseLdapNameAware.java @@ -24,6 +24,7 @@ import javax.naming.ldap.LdapName; * @author Mattias Hellborg Arthursson */ public class DummyBaseLdapNameAware implements BaseLdapNameAware { + private LdapName baseLdapPath; @Override @@ -34,4 +35,5 @@ public class DummyBaseLdapNameAware implements BaseLdapNameAware { public LdapName getBaseLdapPath() { return baseLdapPath; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/support/DummyBaseLdapPathAware.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/support/DummyBaseLdapPathAware.java index 2ce073ea..f3af0fdc 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/support/DummyBaseLdapPathAware.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/core/support/DummyBaseLdapPathAware.java @@ -20,7 +20,7 @@ import org.springframework.ldap.core.support.BaseLdapPathAware; /** * Dummy implementation of {@link BaseLdapPathAware}. - * + * * @author Mattias Hellborg Arthursson */ public class DummyBaseLdapPathAware implements BaseLdapPathAware { diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/filter/DummyFilterConsumer.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/filter/DummyFilterConsumer.java index ec94b2b2..b0ebc2f2 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/filter/DummyFilterConsumer.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/filter/DummyFilterConsumer.java @@ -19,7 +19,7 @@ import org.springframework.ldap.filter.Filter; /** * Dummy class to test Filter property editor. - * + * * @author Mattias Hellborg Arthursson */ public class DummyFilterConsumer { @@ -33,4 +33,5 @@ public class DummyFilterConsumer { public void setFilter(Filter filter) { this.filter = filter; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/Group.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/Group.java index a9f21a6c..7116aeb5 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/Group.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/Group.java @@ -27,17 +27,17 @@ import java.util.Set; /** * @author Mattias Hellborg Arthursson */ -@Entry(objectClasses = {"top", "groupOfUniqueNames"}, base = "cn=groups") +@Entry(objectClasses = { "top", "groupOfUniqueNames" }, base = "cn=groups") public class Group { @Id private Name dn; - @Attribute(name="cn") + @Attribute(name = "cn") @DnAttribute("cn") private String name; - @Attribute(name="uniqueMember") + @Attribute(name = "uniqueMember") private Set members; public Name getDn() { @@ -71,4 +71,5 @@ public class Group { public void removeMember(Name member) { members.remove(member); } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/Person.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/Person.java index 6acf1fdf..fac09b10 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/Person.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/Person.java @@ -15,6 +15,7 @@ import org.springframework.ldap.odm.annotations.Transient; */ @Entry(objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }) public class Person implements Persistable { + @Id private Name dn; @@ -105,4 +106,5 @@ public class Person implements Persistable { public String getEntryUuid() { return entryUuid; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/PersonWithDnAnnotations.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/PersonWithDnAnnotations.java index b3ad2052..ce10ec1f 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/PersonWithDnAnnotations.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/odm/PersonWithDnAnnotations.java @@ -15,11 +15,12 @@ import org.springframework.ldap.odm.annotations.Transient; */ @Entry(objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }) public class PersonWithDnAnnotations { + @Id private Name dn; @Attribute(name = "cn") - @DnAttribute(value="cn", index=2) + @DnAttribute(value = "cn", index = 2) private String commonName; @Attribute(name = "sn") @@ -34,11 +35,11 @@ public class PersonWithDnAnnotations { @Attribute(name = "telephoneNumber") private String telephoneNumber; - @DnAttribute(value="ou", index=1) + @DnAttribute(value = "ou", index = 1) @Transient private String company; - @DnAttribute(value="ou", index=0) + @DnAttribute(value = "ou", index = 0) @Transient private String country; @@ -113,4 +114,5 @@ public class PersonWithDnAnnotations { public String getEntryUuid() { return entryUuid; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/support/springsecurity/MethodSecurityExpressionHandler.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/support/springsecurity/MethodSecurityExpressionHandler.java index 8cf66e8b..2544e68c 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/support/springsecurity/MethodSecurityExpressionHandler.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/support/springsecurity/MethodSecurityExpressionHandler.java @@ -23,6 +23,7 @@ import org.springframework.security.access.expression.method.DefaultMethodSecuri * @author Mattias Hellborg Arthursson */ public class MethodSecurityExpressionHandler extends DefaultMethodSecurityExpressionHandler { + private LdapGroupDao groupDao; public LdapGroupDao getGroupDao() { diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyDao.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyDao.java index 0356669e..3225d94c 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyDao.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyDao.java @@ -17,26 +17,22 @@ package org.springframework.ldap.itest.transaction.compensating.manager; public interface DummyDao { - void createWithException(String country, String company, String fullname, - String lastname, String description); - void create(String country, String company, String fullname, - String lastname, String description); + void createWithException(String country, String company, String fullname, String lastname, String description); + + void create(String country, String company, String fullname, String lastname, String description); void update(String dn, String fullname, String lastname, String description); - void updateWithException(String dn, String fullname, String lastname, - String description); + void updateWithException(String dn, String fullname, String lastname, String description); void updateAndRename(String dn, String newDn, String description); - void updateAndRenameWithException(String dn, String newDn, - String description); + void updateAndRenameWithException(String dn, String newDn, String description); void modifyAttributes(String dn, String lastName, String description); - void modifyAttributesWithException(String dn, String lastName, - String description); + void modifyAttributesWithException(String dn, String lastName, String description); void unbind(String dn, String fullname); @@ -49,4 +45,5 @@ public interface DummyDao { void createRecursivelyAndUnbindSubnode(); void createRecursivelyAndUnbindSubnodeWithException(); + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyException.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyException.java index fba9e37c..c98f15a9 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyException.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyException.java @@ -16,7 +16,9 @@ package org.springframework.ldap.itest.transaction.compensating.manager; public class DummyException extends RuntimeException { + public DummyException(String message) { super(message); } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyServiceImpl.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyServiceImpl.java index bd5094a5..f654ccc3 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyServiceImpl.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/DummyServiceImpl.java @@ -16,9 +16,11 @@ package org.springframework.ldap.itest.transaction.compensating.manager; public class DummyServiceImpl { + private DummyDao dummyDaoImpl; public void setDummyDaoImpl(DummyDao dummyDaoImpl) { this.dummyDaoImpl = dummyDaoImpl; } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/LdapAndJdbcDummyDaoImpl.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/LdapAndJdbcDummyDaoImpl.java index 4b9c984d..44209a19 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/LdapAndJdbcDummyDaoImpl.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/LdapAndJdbcDummyDaoImpl.java @@ -24,6 +24,7 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public class LdapAndJdbcDummyDaoImpl implements DummyDao { + private LdapTemplate ldapTemplate; private JdbcTemplate jdbcTemplate; @@ -38,18 +39,20 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#createWithException(java.lang.String, - * java.lang.String, java.lang.String, java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#createWithException(java.lang + * .String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void createWithException(String country, String company, String fullname, String lastname, String description) { + public void createWithException(String country, String company, String fullname, String lastname, + String description) { create(country, company, fullname, lastname, description); throw new DummyException("This method failed"); } /* * (non-Javadoc) - * + * * @see org.springframework.ldap.transaction.support.DummyDao#create(java.lang.String, * java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ @@ -70,7 +73,7 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * + * * @see org.springframework.ldap.transaction.support.DummyDao#update(java.lang.String, * java.lang.String, java.lang.String) */ @@ -80,15 +83,16 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { ctx.setAttributeValue("description", description); ldapTemplate.modifyAttributes(ctx); - jdbcTemplate.update("update PERSON set lastname=?, description = ? where fullname = ?", new Object[] { - lastname, description, fullname }); + jdbcTemplate.update("update PERSON set lastname=?, description = ? where fullname = ?", + new Object[] { lastname, description, fullname }); } /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#updateWithException(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#updateWithException(java.lang + * .String, java.lang.String, java.lang.String) */ public void updateWithException(String dn, String fullname, String lastname, String description) { update(dn, fullname, lastname, description); @@ -97,9 +101,10 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#updateAndRename(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#updateAndRename(java.lang. + * String, java.lang.String, java.lang.String) */ public void updateAndRename(String dn, String newDn, String description) { DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); @@ -111,9 +116,10 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#updateAndRenameWithException(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#updateAndRenameWithException( + * java.lang.String, java.lang.String, java.lang.String) */ public void updateAndRenameWithException(String dn, String newDn, String description) { updateAndRename(dn, newDn, description); @@ -122,9 +128,10 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#modifyAttributes(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#modifyAttributes(java.lang. + * String, java.lang.String, java.lang.String) */ public void modifyAttributes(String dn, String lastName, String description) { DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); @@ -136,9 +143,10 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#modifyAttributesWithException(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#modifyAttributesWithException + * (java.lang.String, java.lang.String, java.lang.String) */ public void modifyAttributesWithException(String dn, String lastName, String description) { modifyAttributes(dn, lastName, description); @@ -147,7 +155,7 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * + * * @see org.springframework.ldap.transaction.support.DummyDao#unbind(java.lang.String) */ public void unbind(String dn, String fullname) { @@ -157,8 +165,10 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#unbindWithException(java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#unbindWithException(java.lang + * .String) */ public void unbindWithException(String dn, String fullname) { unbind(dn, fullname); @@ -184,4 +194,5 @@ public class LdapAndJdbcDummyDaoImpl implements DummyDao { public void createRecursivelyAndUnbindSubnodeWithException() { throw new UnsupportedOperationException(); } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/LdapDummyDaoImpl.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/LdapDummyDaoImpl.java index dbe116ce..b801e619 100644 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/LdapDummyDaoImpl.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/LdapDummyDaoImpl.java @@ -23,7 +23,9 @@ import org.springframework.transaction.annotation.Transactional; @Transactional public class LdapDummyDaoImpl implements DummyDao { + private static final boolean RECURSIVE = true; + private LdapTemplate ldapTemplate; public void setLdapTemplate(LdapTemplate ldapTemplate) { @@ -32,26 +34,24 @@ public class LdapDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#createWithException(java.lang.String, - * java.lang.String, java.lang.String, java.lang.String, - * java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#createWithException(java.lang + * .String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void createWithException(String country, String company, - String fullname, String lastname, String description) { + public void createWithException(String country, String company, String fullname, String lastname, + String description) { create(country, company, fullname, lastname, description); throw new DummyException("This method failed"); } /* * (non-Javadoc) - * + * * @see org.springframework.ldap.transaction.support.DummyDao#create(java.lang.String, - * java.lang.String, java.lang.String, java.lang.String, - * java.lang.String) + * java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void create(String country, String company, String fullname, - String lastname, String description) { + public void create(String country, String company, String fullname, String lastname, String description) { DistinguishedName dn = new DistinguishedName(); dn.add("ou", country); dn.add("ou", company); @@ -67,12 +67,11 @@ public class LdapDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * + * * @see org.springframework.ldap.transaction.support.DummyDao#update(java.lang.String, - * java.lang.String, java.lang.String) + * java.lang.String, java.lang.String) */ - public void update(String dn, String fullname, String lastname, - String description) { + public void update(String dn, String fullname, String lastname, String description) { DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); ctx.setAttributeValue("sn", lastname); ctx.setAttributeValue("description", description); @@ -82,21 +81,22 @@ public class LdapDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#updateWithException(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#updateWithException(java.lang + * .String, java.lang.String, java.lang.String) */ - public void updateWithException(String dn, String fullname, - String lastname, String description) { + public void updateWithException(String dn, String fullname, String lastname, String description) { update(dn, fullname, lastname, description); throw new DummyException("This method failed."); } /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#updateAndRename(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#updateAndRename(java.lang. + * String, java.lang.String, java.lang.String) */ public void updateAndRename(String dn, String newDn, String description) { DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); @@ -108,21 +108,22 @@ public class LdapDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#updateAndRenameWithException(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#updateAndRenameWithException( + * java.lang.String, java.lang.String, java.lang.String) */ - public void updateAndRenameWithException(String dn, String newDn, - String description) { + public void updateAndRenameWithException(String dn, String newDn, String description) { updateAndRename(dn, newDn, description); throw new DummyException("This method failed."); } /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#modifyAttributes(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#modifyAttributes(java.lang. + * String, java.lang.String, java.lang.String) */ public void modifyAttributes(String dn, String lastName, String description) { DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); @@ -134,19 +135,19 @@ public class LdapDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#modifyAttributesWithException(java.lang.String, - * java.lang.String, java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#modifyAttributesWithException + * (java.lang.String, java.lang.String, java.lang.String) */ - public void modifyAttributesWithException(String dn, String lastName, - String description) { + public void modifyAttributesWithException(String dn, String lastName, String description) { modifyAttributes(dn, lastName, description); throw new DummyException("This method failed."); } /* * (non-Javadoc) - * + * * @see org.springframework.ldap.transaction.support.DummyDao#unbind(java.lang.String) */ public void unbind(String dn, String fullname) { @@ -155,8 +156,10 @@ public class LdapDummyDaoImpl implements DummyDao { /* * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#unbindWithException(java.lang.String) + * + * @see + * org.springframework.ldap.transaction.support.DummyDao#unbindWithException(java.lang + * .String) */ public void unbindWithException(String dn, String fullname) { unbind(dn, fullname); @@ -177,7 +180,7 @@ public class LdapDummyDaoImpl implements DummyDao { @Override public void createRecursivelyAndUnbindSubnode() { DirContextAdapter ctx = new DirContextAdapter(); - ctx.setAttributeValues("objectclass", new String[]{"top", "organizationalUnit"}); + ctx.setAttributeValues("objectclass", new String[] { "top", "organizationalUnit" }); ctx.setAttributeValue("ou", "dummy"); ctx.setAttributeValue("description", "dummy description"); @@ -192,4 +195,5 @@ public class LdapDummyDaoImpl implements DummyDao { createRecursivelyAndUnbindSubnode(); throw new DummyException("This method failed"); } + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/DummyDaoLdapAndHibernateImpl.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/DummyDaoLdapAndHibernateImpl.java index e3516406..dbf3e830 100755 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/DummyDaoLdapAndHibernateImpl.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/DummyDaoLdapAndHibernateImpl.java @@ -29,7 +29,6 @@ public class DummyDaoLdapAndHibernateImpl extends HibernateDaoSupport implements ldapTemplate.bind(dn, ctx, null); this.getHibernateTemplate().saveOrUpdate(person); - } public void createWithException(OrgPerson person) { @@ -46,8 +45,7 @@ public class DummyDaoLdapAndHibernateImpl extends HibernateDaoSupport implements ldapTemplate.modifyAttributes(dn, ctx.getModificationItems()); } - public void modifyAttributesWithException(String dn, String lastName, - String description) { + public void modifyAttributesWithException(String dn, String lastName, String description) { modifyAttributes(dn, lastName, description); throw new DummyException("This method failed."); } @@ -95,13 +93,11 @@ public class DummyDaoLdapAndHibernateImpl extends HibernateDaoSupport implements throw new DummyException("This method failed"); } - - public void setLdapTemplate(LdapTemplate ldapTemplate) { this.ldapTemplate = ldapTemplate; } - private String prepareDn(OrgPerson person){ + private String prepareDn(OrgPerson person) { return "cn=" + person.getFullname() + ",ou=" + person.getCompany() + ",ou=" + person.getCountry(); } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/OrgPerson.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/OrgPerson.java index 94c4dcad..d9471ae0 100755 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/OrgPerson.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/OrgPerson.java @@ -2,23 +2,24 @@ package org.springframework.ldap.itest.transaction.compensating.manager.hibernat /** * Pojo for use with the ContextSourceAndHibernateTransactionManager integration tests + * * @author Hans Westerbeek * */ -public class OrgPerson{ - +public class OrgPerson { + private Integer id; - + private String fullname; private String lastname; private String company; - + private String country; - + private String description; - + public Integer getId() { return id; } @@ -43,7 +44,6 @@ public class OrgPerson{ this.lastname = lastname; } - public String getCountry() { return country; } @@ -119,5 +119,5 @@ public class OrgPerson{ return false; return true; } - + } diff --git a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/OrgPersonDao.java b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/OrgPersonDao.java index 22d0c86f..7916999c 100755 --- a/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/OrgPersonDao.java +++ b/test/integration-tests/src/main/java/org/springframework/ldap/itest/transaction/compensating/manager/hibernate/OrgPersonDao.java @@ -1,6 +1,7 @@ package org.springframework.ldap.itest.transaction.compensating.manager.hibernate; public interface OrgPersonDao { + void createWithException(OrgPerson person); void create(OrgPerson person); @@ -20,4 +21,5 @@ public interface OrgPersonDao { void unbind(OrgPerson person); void unbindWithException(OrgPerson person); + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/LdapConditionallyFilteredTestRunner.java b/test/integration-tests/src/test/java/org/springframework/ldap/LdapConditionallyFilteredTestRunner.java index 4182bae6..2d2718c2 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/LdapConditionallyFilteredTestRunner.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/LdapConditionallyFilteredTestRunner.java @@ -26,11 +26,11 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Mattias Hellborg Arthursson */ public class LdapConditionallyFilteredTestRunner extends SpringJUnit4ClassRunner { + /** * Constructs a new {@code SpringJUnit4ClassRunner} and initializes a - * {@link org.springframework.test.context.TestContextManager} to provide Spring testing functionality to - * standard JUnit tests. - * + * {@link org.springframework.test.context.TestContextManager} to provide Spring + * testing functionality to standard JUnit tests. * @param clazz the test class to be run * @see #createTestContextManager(Class) */ @@ -41,9 +41,11 @@ public class LdapConditionallyFilteredTestRunner extends SpringJUnit4ClassRunner if (noadtest != null) { try { filter(Categories.CategoryFilter.exclude(NoAdTest.class)); - } catch (NoTestsRemainException e) { + } + catch (NoTestsRemainException e) { // Nothing to do here. } } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/AbstractLdapTemplateIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/AbstractLdapTemplateIntegrationTest.java index bb0598e6..658deb49 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/AbstractLdapTemplateIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/AbstractLdapTemplateIntegrationTest.java @@ -59,7 +59,7 @@ public abstract class AbstractLdapTemplateIntegrationTest { @Before public void cleanAndSetup() throws NamingException, IOException { Resource ldifResource = getLdifFileResource(); - if(!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(DEFAULT_BASE))) { + if (!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(DEFAULT_BASE))) { List lines = IOUtils.readLines(ldifResource.getInputStream()); StringWriter sw = new StringWriter(); @@ -82,4 +82,5 @@ public abstract class AbstractLdapTemplateIntegrationTest { protected Name getRoot() { return LdapUtils.emptyLdapName(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientAuthenticationITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientAuthenticationITest.java index 57ede34b..903eb024 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientAuthenticationITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientAuthenticationITest.java @@ -45,7 +45,7 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; * * @author Josh Cummings */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -65,9 +65,7 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn public void testAuthenticateWithLdapQuery() { AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - LdapQuery query = LdapQueryBuilder.query() - .where("objectclass").is("person") - .and("uid").is("some.person3"); + LdapQuery query = LdapQueryBuilder.query().where("objectclass").is("person").and("uid").is("some.person3"); tested.authenticate().query(query).password("password").execute(); } @@ -77,8 +75,8 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); LdapQuery query = LdapQueryBuilder.query().filter(filter); - assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> - tested.authenticate().query(query).password("invalidpassword").execute()); + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> tested.authenticate().query(query).password("invalidpassword").execute()); } @Test @@ -86,11 +84,9 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn public void testAuthenticateWithLdapQueryAndInvalidPassword() { AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - LdapQuery query = LdapQueryBuilder.query() - .where("objectclass").is("person") - .and("uid").is("some.person3"); - assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> - tested.authenticate().query(query).password("invalidpassword").execute()); + LdapQuery query = LdapQueryBuilder.query().where("objectclass").is("person").and("uid").is("some.person3"); + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> tested.authenticate().query(query).password("invalidpassword").execute()); } @Test @@ -103,7 +99,8 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn try { DirContextAdapter adapter = (DirContextAdapter) ctx.lookup(entry.getRelativeDn()); assertThat(adapter.getStringAttribute("cn")).isEqualTo("Some Person3"); - } catch (NamingException e) { + } + catch (NamingException e) { throw new RuntimeException("Failed to lookup " + entry.getRelativeDn(), e); } }; @@ -116,9 +113,7 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn @Test @Category(NoAdTest.class) public void testAuthenticateWithLdapQueryAndMapper() { - LdapQuery query = LdapQueryBuilder.query() - .where("objectclass").is("person") - .and("uid").is("some.person3"); + LdapQuery query = LdapQueryBuilder.query().where("objectclass").is("person").and("uid").is("some.person3"); DirContextOperations ctx = tested.authenticate().query(query).password("password") .execute(new LookupAttemptingCallback()); @@ -129,11 +124,9 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn @Test @Category(NoAdTest.class) public void testAuthenticateWithLdapQueryAndMapperAndInvalidPassword() { - LdapQuery query = LdapQueryBuilder.query() - .where("objectclass").is("person") - .and("uid").is("some.person3"); - assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> - tested.authenticate().query(query).password("invalidpassword").execute(new LookupAttemptingCallback())); + LdapQuery query = LdapQueryBuilder.query().where("objectclass").is("person").and("uid").is("some.person3"); + assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> tested.authenticate().query(query) + .password("invalidpassword").execute(new LookupAttemptingCallback())); } @Test @@ -142,19 +135,19 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); LdapQuery query = LdapQueryBuilder.query().filter(filter); - assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> - tested.authenticate().query(query).password("invalidpassword").execute()); + assertThatExceptionOfType(AuthenticationException.class) + .isThrownBy(() -> tested.authenticate().query(query).password("invalidpassword").execute()); } @Test @Category(NoAdTest.class) public void testAuthenticateWithFilterThatDoesNotMatchAnything() { AndFilter filter = new AndFilter(); - filter.and(new EqualsFilter("objectclass", "person")).and( - new EqualsFilter("uid", "some.person.that.isnt.there")); + filter.and(new EqualsFilter("objectclass", "person")) + .and(new EqualsFilter("uid", "some.person.that.isnt.there")); LdapQuery query = LdapQueryBuilder.query().filter(filter); - assertThatExceptionOfType(EmptyResultDataAccessException.class).isThrownBy(() -> - tested.authenticate().query(query).password("password").execute()); + assertThatExceptionOfType(EmptyResultDataAccessException.class) + .isThrownBy(() -> tested.authenticate().query(query).password("password").execute()); } @Test @@ -163,8 +156,8 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", "Some Person")); LdapQuery query = LdapQueryBuilder.query().filter(filter); - assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class).isThrownBy(() -> - tested.authenticate().query(query).password("password").execute()); + assertThatExceptionOfType(IncorrectResultSizeDataAccessException.class) + .isThrownBy(() -> tested.authenticate().query(query).password("password").execute()); } @Test @@ -176,4 +169,5 @@ public class DefaultLdapClientAuthenticationITest extends AbstractLdapTemplateIn LookupAttemptingCallback callback = new LookupAttemptingCallback(); tested.authenticate().query(query).password("password").execute(callback); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientBindUnbindITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientBindUnbindITest.java index 8f3aa275..75dca6a4 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientBindUnbindITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientBindUnbindITest.java @@ -34,16 +34,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** - * Tests the bind and unbind methods of LdapTemplate. The test methods in this - * class tests a little too much, but we need to clean up after binding, so the - * most efficient way to test is to do it all in one test method. Also, the - * methods in this class relies on that the lookup method works as it should - - * that should be ok, since that is verified in a separate test class. - * + * Tests the bind and unbind methods of LdapTemplate. The test methods in this class tests + * a little too much, but we need to clean up after binding, so the most efficient way to + * test is to do it all in one test method. Also, the methods in this class relies on that + * the lookup method works as it should - that should be ok, since that is verified in a + * separate test class. + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) public class DefaultLdapClientBindUnbindITest extends AbstractLdapTemplateIntegrationTest { + @Autowired private LdapClient tested; @@ -80,8 +81,7 @@ public class DefaultLdapClientBindUnbindITest extends AbstractLdapTemplateIntegr @Test public void testBindAndUnbindWithDirContextAdapter() { DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); adapter.setAttributeValue("cn", "Some Person4"); adapter.setAttributeValue("sn", "Person4"); @@ -94,8 +94,7 @@ public class DefaultLdapClientBindUnbindITest extends AbstractLdapTemplateIntegr @Test public void testBindAndUnbindWithDirContextAdapterUsingLdapName() { DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); adapter.setAttributeValue("cn", "Some Person4"); adapter.setAttributeValue("sn", "Person4"); @@ -108,8 +107,7 @@ public class DefaultLdapClientBindUnbindITest extends AbstractLdapTemplateIntegr @Test public void testBindAndUnbindWithDirContextAdapterOnly() { DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN)); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); adapter.setAttributeValue("cn", "Some Person4"); adapter.setAttributeValue("sn", "Person4"); @@ -122,8 +120,7 @@ public class DefaultLdapClientBindUnbindITest extends AbstractLdapTemplateIntegr @Test public void testBindAndRebindWithDirContextAdapterOnly() { DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN)); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); adapter.setAttributeValue("cn", "Some Person4"); adapter.setAttributeValue("sn", "Person4"); @@ -160,8 +157,8 @@ public class DefaultLdapClientBindUnbindITest extends AbstractLdapTemplateIntegr } private void verifyCleanup() { - assertThatExceptionOfType(NameNotFoundException.class) - .describedAs("NameNotFoundException expected") + assertThatExceptionOfType(NameNotFoundException.class).describedAs("NameNotFoundException expected") .isThrownBy(() -> tested.search().name(DN).toEntry()); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientListITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientListITest.java index 46213bbd..19005b41 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientListITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientListITest.java @@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link LdapClient}'s list methods. - * + * * @author Josh Cummings */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) public class DefaultLdapClientListITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -173,4 +173,5 @@ public class DefaultLdapClientListITest extends AbstractLdapTemplateIntegrationT }); assertThat(handler.getNoOfRows()).isEqualTo(3); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientLookupITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientLookupITest.java index 9b4597f9..c73ef475 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientLookupITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientLookupITest.java @@ -37,7 +37,7 @@ import static org.assertj.core.api.Assertions.assertThat; * * @author Josh Cummings */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -45,8 +45,8 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio /** * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set in + * the ContextSource. */ @Test public void testLookup_Plain() { @@ -59,8 +59,8 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio /** * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set in + * the ContextSource. */ @Test public void testLookupContextRoot() { @@ -82,7 +82,8 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio @Test public void testLookup_AttributesMapper_LdapName() { AttributesMapper mapper = new PersonAttributesMapper(); - Person person = tested.search().name(LdapUtils.newLdapName("cn=Some Person2, ou=company1,ou=Sweden")).toObject(mapper); + Person person = tested.search().name(LdapUtils.newLdapName("cn=Some Person2, ou=company1,ou=Sweden")) + .toObject(mapper); assertThat(person.getFullname()).isEqualTo("Some Person2"); assertThat(person.getLastname()).isEqualTo("Person2"); @@ -90,17 +91,17 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio } /** - * An {@link AttributesMapper} that only maps a subset of the full - * attributes list. Used in tests where the return attributes list has been - * limited. - * + * An {@link AttributesMapper} that only maps a subset of the full attributes list. + * Used in tests where the return attributes list has been limited. + * * @author Ulrik Sandberg */ private static final class SubsetPersonAttributesMapper implements AttributesMapper { + /** - * Maps the cn attribute into a {@link Person} object. Also - * verifies that the other attributes haven't been set. - * + * Maps the cn attribute into a {@link Person} object. Also verifies + * that the other attributes haven't been set. + * * @see AttributesMapper#mapFromAttributes(Attributes) */ public Person mapFromAttributes(Attributes attributes) throws NamingException { @@ -110,19 +111,20 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio assertThat(attributes.get("description")).as("description should be null").isNull(); return person; } + } /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. + * Verifies that only the subset is used when specifying a subset of the available + * attributes as return attributes. */ @Test public void testLookup_ReturnAttributes_AttributesMapper() { AttributesMapper mapper = new SubsetPersonAttributesMapper(); - Person person = tested.search().query((builder) -> builder - .base("cn=Some Person2, ou=company1,ou=Sweden") - .attributes("cn")).toObject(mapper); + Person person = tested.search() + .query((builder) -> builder.base("cn=Some Person2, ou=company1,ou=Sweden").attributes("cn")) + .toObject(mapper); assertThat(person.getFullname()).isEqualTo("Some Person2"); assertThat(person.getLastname()).as("lastName should not be set").isNull(); @@ -130,16 +132,16 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio } /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. Uses LdapName instead - * of plain string as name. + * Verifies that only the subset is used when specifying a subset of the available + * attributes as return attributes. Uses LdapName instead of plain string as name. */ @Test public void testLookup_ReturnAttributes_AttributesMapper_LdapName() { AttributesMapper mapper = new SubsetPersonAttributesMapper(); - Person person = tested.search().query((builder) -> builder - .base(LdapUtils.newLdapName("cn=Some Person2, ou=company1,ou=Sweden")) - .attributes("cn")).toObject(mapper); + Person person = tested + .search().query((builder) -> builder + .base(LdapUtils.newLdapName("cn=Some Person2, ou=company1,ou=Sweden")).attributes("cn")) + .toObject(mapper); assertThat(person.getFullname()).isEqualTo("Some Person2"); assertThat(person.getLastname()).as("lastName should not be set").isNull(); @@ -148,8 +150,8 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio /** * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set in + * the ContextSource. */ @Test public void testLookup_ContextMapper() { @@ -162,15 +164,16 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio } /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. + * Verifies that only the subset is used when specifying a subset of the available + * attributes as return attributes. */ @Test public void testLookup_ReturnAttributes_ContextMapper() { ContextMapper mapper = new PersonContextMapper(); - Person person = tested.search().query((builder) -> builder - .base("cn=Some Person2, ou=company1,ou=Sweden").attributes("cn")).toObject(mapper); + Person person = tested.search() + .query((builder) -> builder.base("cn=Some Person2, ou=company1,ou=Sweden").attributes("cn")) + .toObject(mapper); assertThat(person.getFullname()).isEqualTo("Some Person2"); assertThat(person.getLastname()).as("lastName should not be set").isNull(); @@ -186,4 +189,5 @@ public class DefaultLdapClientLookupITest extends AbstractLdapTemplateIntegratio assertThat(result.getDn()).isEqualTo(expectedName); assertThat(result.getNameInNamespace()).isEqualTo("cn=Some Person2,ou=company1,ou=Sweden," + base); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientLookupMultiRdnITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientLookupMultiRdnITest.java index 17afd411..40079e6b 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientLookupMultiRdnITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientLookupMultiRdnITest.java @@ -32,10 +32,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests {@link LdapClient}'s lookup methods. - * + * * @author Josh Cummings */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) public class DefaultLdapClientLookupMultiRdnITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -45,10 +45,9 @@ public class DefaultLdapClientLookupMultiRdnITest extends AbstractLdapTemplateIn return new ClassPathResource("/setup_data_multi_rdn.ldif"); } - /** - * Verifies that we can lookup an entry that has a multi-valued rdn, which - * means more than one attribute is part of the relative DN for the entry. + * Verifies that we can lookup an entry that has a multi-valued rdn, which means more + * than one attribute is part of the relative DN for the entry. */ @Test @Category(NoAdTest.class) @@ -61,9 +60,9 @@ public class DefaultLdapClientLookupMultiRdnITest extends AbstractLdapTemplateIn } /** - * Verifies that we can lookup an entry that has a multi-valued rdn, which - * means more than one attribute is part of the relative DN for the entry. - * + * Verifies that we can lookup an entry that has a multi-valued rdn, which means more + * than one attribute is part of the relative DN for the entry. + * */ @Test @Category(NoAdTest.class) @@ -81,4 +80,5 @@ public class DefaultLdapClientLookupMultiRdnITest extends AbstractLdapTemplateIn assertThat(result.getDn().toString()).isEqualTo("cn=Some Person+sn=Person,ou=company1,ou=Norway"); assertThat(result.getNameInNamespace()).isEqualTo("cn=Some Person+sn=Person,ou=company1,ou=Norway," + base); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientModifyITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientModifyITest.java index 5676cf2a..e6786a10 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientModifyITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientModifyITest.java @@ -44,13 +44,14 @@ import static org.assertj.core.api.Assertions.fail; /** * Tests {@link LdapClient}'s modification methods (rebind and modifyAttributes) * - *

    It also illustrates the use of DirContextAdapter as a means of getting + *

    + * It also illustrates the use of DirContextAdapter as a means of getting * {@code ModificationItems}, in order to avoid doing a full rebind and use * {@code modify()} instead. - * + * * @author Josh Cummings */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) public class DefaultLdapClientModifyITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -158,8 +159,8 @@ public class DefaultLdapClientModifyITest extends AbstractLdapTemplateIntegratio /** * Test written originally to verify that duplicates are allowed on ordered - * attributes, but had to be changed since Apache DS seems to disallow - * duplicates even for ordered attributes. + * attributes, but had to be changed since Apache DS seems to disallow duplicates even + * for ordered attributes. */ @Test public void testModifyAttributes_MultiValueAddDuplicateToOrdered() { @@ -180,16 +181,16 @@ public class DefaultLdapClientModifyITest extends AbstractLdapTemplateIntegratio @Test public void testModifyAttributes_Plain() { - ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description", - "Some other description")); + ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, + new BasicAttribute("description", "Some other description")); tested.modify(PERSON4_DN).attributes(item).execute(); verifyBoundCorrectData(); } @Test public void testModifyAttributes_LdapName() { - ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description", - "Some other description")); + ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, + new BasicAttribute("description", "Some other description")); tested.modify(LdapUtils.newLdapName(PERSON4_DN)).attributes(item).execute(); verifyBoundCorrectData(); } @@ -211,9 +212,9 @@ public class DefaultLdapClientModifyITest extends AbstractLdapTemplateIntegratio } /** - * Demonstrates how the DirContextAdapter can be used to automatically keep - * track of changes of the attributes and deliver ModificationItems to use - * in moifyAttributes(). + * Demonstrates how the DirContextAdapter can be used to automatically keep track of + * changes of the attributes and deliver ModificationItems to use in + * moifyAttributes(). */ @Test public void testModifyAttributes_DirContextAdapter() { @@ -248,4 +249,5 @@ public class DefaultLdapClientModifyITest extends AbstractLdapTemplateIntegratio assertThat(result.getStringAttribute("sn")).isEqualTo("Person4"); assertThat(result.getStringAttribute("description")).isEqualTo("Some other description"); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientRecursiveDeleteITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientRecursiveDeleteITest.java index a39736a1..714b8fa8 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientRecursiveDeleteITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientRecursiveDeleteITest.java @@ -35,12 +35,12 @@ import org.springframework.test.context.ContextConfiguration; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** - * Tests {@code LdapClient}'s recursive modification methods (unbind and the protected delete - * methods). - * + * Tests {@code LdapClient}'s recursive modification methods (unbind and the protected + * delete methods). + * * @author Josh Cummings */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) public class DefaultLdapClientRecursiveDeleteITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -126,4 +126,5 @@ public class DefaultLdapClientRecursiveDeleteITest extends AbstractLdapTemplateI .describedAs("Expected entry '" + dn + "' to be non-existent") .isThrownBy(() -> tested.list(dn).toList(NameClassPair::getName)); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientRenameITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientRenameITest.java index 35e52e80..44bf1621 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientRenameITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientRenameITest.java @@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.fail; /** * Tests {@link LdapClient}'s rename methods. - * + * * @author Josh Cummings */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) public class DefaultLdapClientRenameITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -99,4 +99,5 @@ public class DefaultLdapClientRenameITest extends AbstractLdapTemplateIntegratio assertThat(result.getStringAttribute("sn")).isEqualTo("Person6"); assertThat(result.getStringAttribute("description")).isEqualTo("Some description"); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientSearchResultITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientSearchResultITest.java index 73590762..8c83923c 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientSearchResultITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/DefaultLdapClientSearchResultITest.java @@ -49,10 +49,10 @@ import static org.springframework.ldap.query.LdapQueryBuilder.query; /** * Tests for {@link LdapClient}'s search methods. - * + * * @author Josh Cummings */ -@ContextConfiguration(locations = {"/conf/ldapClientTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapClientTestContext.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateIntegrationTest { @@ -106,9 +106,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base(BASE_STRING) - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search() + .query(query().base(BASE_STRING).where("objectclass").is("person").and("sn").is("Person2")) .toList(attributesMapper); assertThat(list).hasSize(1); } @@ -118,35 +117,30 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base(BASE_STRING) - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search() + .query(query().base(BASE_STRING).where("objectclass").is("person").and("sn").is("Person2")) .toStream(attributesMapper).collect(Collectors.toList()); assertThat(list).hasSize(1); } @Test public void testSearch_LdapQuery_AttributesMapper_FewerAttributes() { - attributesMapper.setExpectedAttributes(new String[] {"cn"}); - attributesMapper.setExpectedValues(new String[]{"Some Person2"}); + attributesMapper.setExpectedAttributes(new String[] { "cn" }); + attributesMapper.setExpectedValues(new String[] { "Some Person2" }); - List list = tested.search().query(query() - .base(BASE_STRING) - .attributes("cn") - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search().query( + query().base(BASE_STRING).attributes("cn").where("objectclass").is("person").and("sn").is("Person2")) .toList(attributesMapper); assertThat(list).hasSize(1); } @Test public void testSearchForStream_LdapQuery_AttributesMapper_FewerAttributes() { - attributesMapper.setExpectedAttributes(new String[] {"cn"}); - attributesMapper.setExpectedValues(new String[]{"Some Person2"}); + attributesMapper.setExpectedAttributes(new String[] { "cn" }); + attributesMapper.setExpectedValues(new String[] { "Some Person2" }); - List list = tested.search().query(query() - .base(BASE_STRING) - .attributes("cn") - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search().query( + query().base(BASE_STRING).attributes("cn").where("objectclass").is("person").and("sn").is("Person2")) .toStream(attributesMapper).collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -156,11 +150,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base(BASE_STRING) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")) - .toList(attributesMapper); + List list = tested.search().query(query().base(BASE_STRING).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2")).toList(attributesMapper); assertThat(list).isEmpty(); } @@ -169,11 +160,9 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base(BASE_STRING) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")) - .toStream(attributesMapper).collect(Collectors.toList()); + List list = tested.search().query(query().base(BASE_STRING).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2")).toStream(attributesMapper) + .collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -182,10 +171,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search().query(query().base("ou=company1,ou=Sweden") + .searchScope(SearchScope.ONELEVEL).where("objectclass").is("person").and("sn").is("Person2")) .toList(attributesMapper); assertThat(list).hasSize(1); } @@ -195,9 +182,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) + List list = tested + .search().query(query().base("ou=company1,ou=Sweden").searchScope(SearchScope.ONELEVEL) .where("objectclass").is("person").and("sn").is("Person2")) .toStream(attributesMapper).collect(Collectors.toList()); assertThat(list).hasSize(1); @@ -208,8 +194,7 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search().query(query().where("objectclass").is("person").and("sn").is("Person2")) .toList(attributesMapper); assertThat(list).hasSize(1); } @@ -219,8 +204,7 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search().query(query().where("objectclass").is("person").and("sn").is("Person2")) .toStream(attributesMapper).collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -230,9 +214,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base("ou=Norway") - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search() + .query(query().base("ou=Norway").where("objectclass").is("person").and("sn").is("Person2")) .toList(attributesMapper); assertThat(list).isEmpty(); } @@ -242,9 +225,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base("ou=Norway") - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search() + .query(query().base("ou=Norway").where("objectclass").is("person").and("sn").is("Person2")) .toStream(attributesMapper).collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -253,8 +235,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearch_SearchScope_AttributesMapper() { attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query().base(BASE_STRING) - .searchScope(SearchScope.SUBTREE).filter(FILTER_STRING)) + List list = tested.search() + .query(query().base(BASE_STRING).searchScope(SearchScope.SUBTREE).filter(FILTER_STRING)) .toList(attributesMapper); assertThat(list).hasSize(1); } @@ -264,11 +246,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(CN_SN_ATTRS); attributesMapper.setExpectedValues(CN_SN_VALUES); attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search().query(query().base(BASE_STRING) - .searchScope(SearchScope.SUBTREE) - .attributes(CN_SN_ATTRS) - .filter(FILTER_STRING)) - .toList(attributesMapper); + List list = tested.search().query(query().base(BASE_STRING).searchScope(SearchScope.SUBTREE) + .attributes(CN_SN_ATTRS).filter(FILTER_STRING)).toList(attributesMapper); assertThat(list).hasSize(1); } @@ -285,8 +264,9 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearch_SearchScope_AttributesMapper_Name() { attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query().base(BASE_NAME).searchScope(SearchScope.SUBTREE) - .filter(FILTER_STRING)).toList(attributesMapper); + List list = tested.search() + .query(query().base(BASE_NAME).searchScope(SearchScope.SUBTREE).filter(FILTER_STRING)) + .toList(attributesMapper); assertThat(list).hasSize(1); } @@ -295,8 +275,9 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte attributesMapper.setExpectedAttributes(CN_SN_ATTRS); attributesMapper.setExpectedValues(CN_SN_VALUES); attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search().query(query().base(BASE_NAME).searchScope(SearchScope.SUBTREE) - .attributes(CN_SN_ATTRS).filter(FILTER_STRING)).toList(attributesMapper); + List list = tested.search().query( + query().base(BASE_NAME).searchScope(SearchScope.SUBTREE).attributes(CN_SN_ATTRS).filter(FILTER_STRING)) + .toList(attributesMapper); assertThat(list).hasSize(1); } @@ -324,10 +305,10 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte .toObject((Object ctx) -> ctx); } - @Test//(expected = EmptyResultDataAccessException.class) + @Test // (expected = EmptyResultDataAccessException.class) public void testSearchForObjectNoHits() { - Object result = tested.search().query(query().base(BASE_STRING) - .filter("(&(objectclass=person)(sn=Person does not exist))")) + Object result = tested.search() + .query(query().base(BASE_STRING).filter("(&(objectclass=person)(sn=Person does not exist))")) .toObject((Object ctx) -> ctx); assertThat(result).isNull(); } @@ -336,8 +317,9 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearch_SearchScope_ContextMapper() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query().base(BASE_STRING).searchScope(SearchScope.SUBTREE) - .filter(FILTER_STRING)).toList(contextMapper); + List list = tested.search() + .query(query().base(BASE_STRING).searchScope(SearchScope.SUBTREE).filter(FILTER_STRING)) + .toList(contextMapper); assertThat(list).hasSize(1); } @@ -364,9 +346,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearch_ContextMapper_LdapQuery() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base(BASE_NAME) - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search() + .query(query().base(BASE_NAME).where("objectclass").is("person").and("sn").is("Person2")) .toList(contextMapper); assertThat(list).hasSize(1); } @@ -375,9 +356,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearchForStream_ContextMapper_LdapQuery() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base(BASE_NAME) - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search() + .query(query().base(BASE_NAME).where("objectclass").is("person").and("sn").is("Person2")) .toStream(contextMapper).collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -386,9 +366,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearch_ContextMapper_LdapQuery_NoBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .where("objectclass").is("person").and("sn").is("Person2")) - .toList(contextMapper); + List list = tested.search() + .query(query().where("objectclass").is("person").and("sn").is("Person2")).toList(contextMapper); assertThat(list).hasSize(1); } @@ -396,9 +375,9 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearchForStream_ContextMapper_LdapQuery_NoBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .where("objectclass").is("person").and("sn").is("Person2")) - .toStream(contextMapper).collect(Collectors.toList()); + List list = tested.search() + .query(query().where("objectclass").is("person").and("sn").is("Person2")).toStream(contextMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -406,11 +385,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearch_ContextMapper_LdapQuery_SearchScope() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base(BASE_NAME) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")) - .toList(contextMapper); + List list = tested.search().query(query().base(BASE_NAME).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2")).toList(contextMapper); assertThat(list).isEmpty(); } @@ -418,11 +394,9 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearchForStream_ContextMapper_LdapQuery_SearchScope() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base(BASE_NAME) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")) - .toStream(contextMapper).collect(Collectors.toList()); + List list = tested.search().query(query().base(BASE_NAME).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2")).toStream(contextMapper) + .collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -430,10 +404,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearch_ContextMapper_LdapQuery_SearchScope_CorrectBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")) + List list = tested.search().query(query().base("ou=company1,ou=Sweden") + .searchScope(SearchScope.ONELEVEL).where("objectclass").is("person").and("sn").is("Person2")) .toList(contextMapper); assertThat(list).hasSize(1); } @@ -442,9 +414,8 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearchForStream_ContextMapper_LdapQuery_SearchScope_CorrectBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) + List list = tested + .search().query(query().base("ou=company1,ou=Sweden").searchScope(SearchScope.ONELEVEL) .where("objectclass").is("person").and("sn").is("Person2")) .toStream(contextMapper).collect(Collectors.toList()); assertThat(list).hasSize(1); @@ -453,28 +424,26 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte @Test public void testSearchForContext_LdapQuery() { ContextMapper mapper = (result) -> (DirContextOperations) result; - DirContextOperations result = tested.search().query(query() - .where("objectclass").is("person").and("sn").is("Person2")).toObject(mapper); + DirContextOperations result = tested.search() + .query(query().where("objectclass").is("person").and("sn").is("Person2")).toObject(mapper); assertThat(result).isNotNull(); assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); } - @Test//(expected = EmptyResultDataAccessException.class) + @Test // (expected = EmptyResultDataAccessException.class) public void testSearchForContext_LdapQuery_SearchScopeNotFound() { - Object result = tested.search().query(query() - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")).toObject(attributesMapper); + Object result = tested.search().query( + query().searchScope(SearchScope.ONELEVEL).where("objectclass").is("person").and("sn").is("Person2")) + .toObject(attributesMapper); assertThat(result).isNull(); } @Test public void testSearchForContext_LdapQuery_SearchScope_CorrectBase() { ContextMapper mapper = (result) -> (DirContextOperations) result; - DirContextOperations result = - tested.search().query(query() - .searchScope(SearchScope.ONELEVEL) - .base("ou=company1,ou=Sweden") - .where("objectclass").is("person").and("sn").is("Person2")).toObject(mapper); + DirContextOperations result = tested.search().query(query().searchScope(SearchScope.ONELEVEL) + .base("ou=company1,ou=Sweden").where("objectclass").is("person").and("sn").is("Person2")) + .toObject(mapper); assertThat(result).isNotNull(); assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); @@ -484,8 +453,9 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearch_SearchScope_ContextMapper_Name() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search().query(query().base(BASE_NAME).searchScope(SearchScope.SUBTREE) - .filter(FILTER_STRING)).toList(contextMapper); + List list = tested.search() + .query(query().base(BASE_NAME).searchScope(SearchScope.SUBTREE).filter(FILTER_STRING)) + .toList(contextMapper); assertThat(list).hasSize(1); } @@ -494,8 +464,9 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte contextMapper.setExpectedAttributes(CN_SN_ATTRS); contextMapper.setExpectedValues(CN_SN_VALUES); contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search().query(query().base(BASE_NAME).searchScope(SearchScope.SUBTREE) - .attributes(CN_SN_ATTRS).filter(FILTER_STRING)).toList(contextMapper); + List list = tested.search().query( + query().base(BASE_NAME).searchScope(SearchScope.SUBTREE).attributes(CN_SN_ATTRS).filter(FILTER_STRING)) + .toList(contextMapper); assertThat(list).hasSize(1); } @@ -503,8 +474,7 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte public void testSearchWithInvalidSearchBaseShouldByDefaultThrowException() { try { tested.search().query(query().base(BASE_NAME + "ou=unknown").searchScope(SearchScope.SUBTREE) - .attributes(CN_SN_ATTRS).filter(FILTER_STRING)) - .toObject(contextMapper); + .attributes(CN_SN_ATTRS).filter(FILTER_STRING)).toObject(contextMapper); fail("NameNotFoundException expected"); } catch (NameNotFoundException expected) { @@ -519,16 +489,14 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte contextMapper.setExpectedValues(CN_SN_VALUES); contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); List list = tested.search().query(query().base(BASE_NAME + "ou=unknown") - .searchScope(SearchScope.SUBTREE).attributes(CN_SN_ATTRS).filter(FILTER_STRING)) - .toList(contextMapper); + .searchScope(SearchScope.SUBTREE).attributes(CN_SN_ATTRS).filter(FILTER_STRING)).toList(contextMapper); assertThat(list).isEmpty(); } @Test public void verifyThatSearchWithCountLimitReturnsTheEntriesFoundSoFar() { - List result = tested.search().query(query() - .countLimit(3) - .where("objectclass").is("person")).toList((Object ctx) -> new Object()); + List result = tested.search().query(query().countLimit(3).where("objectclass").is("person")) + .toList((Object ctx) -> new Object()); assertThat(result).hasSize(3); } @@ -536,8 +504,7 @@ public class DefaultLdapClientSearchResultITest extends AbstractLdapTemplateInte @Test(expected = SizeLimitExceededException.class) public void verifyThatSearchWithCountLimitWithFlagToFalseThrowsException() { ReflectionTestUtils.setField(tested, "ignoreSizeLimitExceededException", false); - tested.search().query(query() - .countLimit(3) - .where("objectclass").is("person")).toList((Object ctx) -> ctx); + tested.search().query(query().countLimit(3).where("objectclass").is("person")).toList((Object ctx) -> ctx); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/InvalidBackslashITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/InvalidBackslashITest.java index 3369b95d..4af14b51 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/InvalidBackslashITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/InvalidBackslashITest.java @@ -37,10 +37,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for verifying that issues LDAP-50 and LDAP-109 are solved. - * + * * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class InvalidBackslashITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -66,28 +66,25 @@ public class InvalidBackslashITest extends AbstractLdapTemplateIntegrationTest { } /** - * Test for LDAP-109, LDAP-50. When an entry has a distinguished name - * including a backslach ('\') the Name supplied to DefaultDirObjectFactory - * will be invalid. + * Test for LDAP-109, LDAP-50. When an entry has a distinguished name including a + * backslach ('\') the Name supplied to DefaultDirObjectFactory will be invalid. *

    - * E.g. the distinguished name "cn=Some\\Person6,ou=company1,ou=Sweden" - * (indicating that the cn value is 'Some\Person'), will be represented by a + * E.g. the distinguished name "cn=Some\\Person6,ou=company1,ou=Sweden" (indicating + * that the cn value is 'Some\Person'), will be represented by a * CompositeName with the string representation - * "cn=Some\\\Person6,ou=company1,ou=Sweden", which is in fact an invalid DN. - * This will be supplied to DistinguishedName for parsing, - * causing it to fail. This test makes sure that Spring LDAP properly works - * around this bug. + * "cn=Some\\\Person6,ou=company1,ou=Sweden", which is in fact an invalid DN. This + * will be supplied to DistinguishedName for parsing, causing it to fail. + * This test makes sure that Spring LDAP properly works around this bug. *

    *

    * What happens under the covers is (in the Java LDAP Provider code): - * + * *

     	 * LdapName ldapname = new LdapName("cn=Some\\\\Person6,ou=company1,ou=Sweden");
     	 * CompositeName compositeName = new CompositeName();
     	 * compositeName.add(ldapname.get(ldapname.size() - 1)); // for some odd reason
    -	 * 
    - * CompositeName#add() cannot handle this and the result is - * the spoiled DN. + * CompositeName#add() cannot handle this and the result is the + * spoiled DN. *

    * @throws InvalidNameException */ @@ -107,4 +104,5 @@ public class InvalidBackslashITest extends AbstractLdapTemplateIntegrationTest { assertThat(result).hasSize(1); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAttributesMapperITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAttributesMapperITest.java index 79404e6b..4dde9f51 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAttributesMapperITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAttributesMapperITest.java @@ -32,11 +32,12 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests the attributes mapper search method. - * + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateAttributesMapperITest extends AbstractLdapTemplateIntegrationTest { + @Autowired private LdapTemplate tested; @@ -54,7 +55,7 @@ public class LdapTemplateAttributesMapperITest extends AbstractLdapTemplateInteg /** * Demonstrates how to retrieve all values of a multi-value attribute. - * + * * @see LdapTemplateContextMapperITest#testSearch_ContextMapper_MultiValue() */ @Test @@ -77,4 +78,5 @@ public class LdapTemplateAttributesMapperITest extends AbstractLdapTemplateInteg assertThat(((String[]) result.get(0)).length).isEqualTo(4); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAuthenticationITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAuthenticationITest.java index 7ae67540..22d0caba 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAuthenticationITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAuthenticationITest.java @@ -40,11 +40,11 @@ import static org.springframework.ldap.query.LdapQueryBuilder.query; /** * Tests the authenticate methods of LdapTemplate. - * + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -63,10 +63,7 @@ public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegra public void testAuthenticateWithLdapQuery() { AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - tested.authenticate(query() - .where("objectclass").is("person") - .and("uid").is("some.person3"), - "password"); + tested.authenticate(query().where("objectclass").is("person").and("uid").is("some.person3"), "password"); } @Test @@ -82,10 +79,7 @@ public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegra public void testAuthenticateWithLdapQueryAndInvalidPassword() { AndFilter filter = new AndFilter(); filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - tested.authenticate(query() - .where("objectclass").is("person") - .and("uid").is("some.person3"), - "invalidpassword"); + tested.authenticate(query().where("objectclass").is("person").and("uid").is("some.person3"), "invalidpassword"); } @Test @@ -110,10 +104,8 @@ public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegra @Test @Category(NoAdTest.class) public void testAuthenticateWithLdapQueryAndMapper() { - DirContextOperations ctx = tested.authenticate(query() - .where("objectclass").is("person") - .and("uid").is("some.person3"), - "password", + DirContextOperations ctx = tested.authenticate( + query().where("objectclass").is("person").and("uid").is("some.person3"), "password", new LookupAttemptingCallback()); assertThat(ctx).isNotNull(); @@ -123,10 +115,8 @@ public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegra @Test(expected = AuthenticationException.class) @Category(NoAdTest.class) public void testAuthenticateWithLdapQueryAndMapperAndInvalidPassword() { - DirContextOperations ctx = tested.authenticate(query() - .where("objectclass").is("person") - .and("uid").is("some.person3"), - "invalidpassword", + DirContextOperations ctx = tested.authenticate( + query().where("objectclass").is("person").and("uid").is("some.person3"), "invalidpassword", new LookupAttemptingCallback()); } @@ -139,20 +129,22 @@ public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegra assertThat(tested.authenticate("", filter.toString(), "invalidpassword", errorCallback)).isFalse(); final Exception error = errorCallback.getError(); assertThat(error).as("collected error should not be null").isNotNull(); - assertThat(error instanceof AuthenticationException).as("expected org.springframework.ldap.AuthenticationException").isTrue(); - assertThat(error.getCause() instanceof javax.naming.AuthenticationException).as("expected javax.naming.AuthenticationException").isTrue(); + assertThat(error instanceof AuthenticationException) + .as("expected org.springframework.ldap.AuthenticationException").isTrue(); + assertThat(error.getCause() instanceof javax.naming.AuthenticationException) + .as("expected javax.naming.AuthenticationException").isTrue(); } @Test @Category(NoAdTest.class) public void testAuthenticateWithFilterThatDoesNotMatchAnything() { AndFilter filter = new AndFilter(); - filter.and(new EqualsFilter("objectclass", "person")).and( - new EqualsFilter("uid", "some.person.that.isnt.there")); + filter.and(new EqualsFilter("objectclass", "person")) + .and(new EqualsFilter("uid", "some.person.that.isnt.there")); assertThat(tested.authenticate("", filter.toString(), "password")).isFalse(); } - @Test(expected=IncorrectResultSizeDataAccessException.class) + @Test(expected = IncorrectResultSizeDataAccessException.class) @Category(NoAdTest.class) public void testAuthenticateWithFilterThatMatchesSeveralEntries() { AndFilter filter = new AndFilter(); @@ -168,4 +160,5 @@ public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegra LookupAttemptingCallback callback = new LookupAttemptingCallback(); assertThat(tested.authenticate("", filter.encode(), "password", callback)).isTrue(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateBindUnbindITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateBindUnbindITest.java index 2644518a..a3d2bb7b 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateBindUnbindITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateBindUnbindITest.java @@ -32,17 +32,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Tests the bind and unbind methods of LdapTemplate. The test methods in this - * class tests a little too much, but we need to clean up after binding, so the - * most efficient way to test is to do it all in one test method. Also, the - * methods in this class relies on that the lookup method works as it should - - * that should be ok, since that is verified in a separate test class. - * + * Tests the bind and unbind methods of LdapTemplate. The test methods in this class tests + * a little too much, but we need to clean up after binding, so the most efficient way to + * test is to do it all in one test method. Also, the methods in this class relies on that + * the lookup method works as it should - that should be ok, since that is verified in a + * separate test class. + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -public class LdapTemplateBindUnbindITest extends - AbstractLdapTemplateIntegrationTest { +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) +public class LdapTemplateBindUnbindITest extends AbstractLdapTemplateIntegrationTest { + @Autowired private LdapTemplate tested; @@ -79,8 +79,7 @@ public class LdapTemplateBindUnbindITest extends @Test public void testBindAndUnbindWithDirContextAdapter() { DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); adapter.setAttributeValue("cn", "Some Person4"); adapter.setAttributeValue("sn", "Person4"); @@ -93,8 +92,7 @@ public class LdapTemplateBindUnbindITest extends @Test public void testBindAndUnbindWithDirContextAdapterUsingLdapName() { DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); adapter.setAttributeValue("cn", "Some Person4"); adapter.setAttributeValue("sn", "Person4"); @@ -107,8 +105,7 @@ public class LdapTemplateBindUnbindITest extends @Test public void testBindAndUnbindWithDirContextAdapterOnly() { DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN)); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); adapter.setAttributeValue("cn", "Some Person4"); adapter.setAttributeValue("sn", "Person4"); @@ -121,8 +118,7 @@ public class LdapTemplateBindUnbindITest extends @Test public void testBindAndRebindWithDirContextAdapterOnly() { DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN)); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); adapter.setAttributeValue("cn", "Some Person4"); adapter.setAttributeValue("sn", "Person4"); @@ -167,4 +163,5 @@ public class LdapTemplateBindUnbindITest extends assertThat(true).isTrue(); } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateContextExecutorTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateContextExecutorTest.java index b719c830..32575213 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateContextExecutorTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateContextExecutorTest.java @@ -29,10 +29,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for LdapTemplate's context executor methods. - * + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateContextExecutorTest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -49,4 +49,5 @@ public class LdapTemplateContextExecutorTest extends AbstractLdapTemplateIntegra Object object = tested.executeReadOnly(executor); assertThat(object instanceof DirContextAdapter).as("Should be a DirContextAdapter").isTrue(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateContextMapperITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateContextMapperITest.java index 312e002a..64de4fb1 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateContextMapperITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateContextMapperITest.java @@ -28,20 +28,21 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; /** - * Tests the ContextMapper search method. In its way this method also - * demonstrates the use of DirContextAdapter and the DirObjectFactory. - * + * Tests the ContextMapper search method. In its way this method also demonstrates the use + * of DirContextAdapter and the DirObjectFactory. + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateContextMapperITest extends AbstractLdapTemplateIntegrationTest { - + @Autowired private LdapTemplate tested; /** - * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * This method depends on a DirObjectFactory + * ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set + * in the ContextSource. */ @Test public void testSearch_ContextMapper() { @@ -57,7 +58,7 @@ public class LdapTemplateContextMapperITest extends AbstractLdapTemplateIntegrat /** * Demonstrates how to retrieve all values of a multi-value attribute. - * + * * @see LdapTemplateAttributesMapperITest#testSearch_AttributesMapper_MultiValue() */ @Test @@ -74,4 +75,5 @@ public class LdapTemplateContextMapperITest extends AbstractLdapTemplateIntegrat assertThat(result).hasSize(1); assertThat(((String[]) result.get(0)).length).isEqualTo(4); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateListITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateListITest.java index 4087b700..c004eb34 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateListITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateListITest.java @@ -33,10 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests for LdapTemplate's list methods. - * + * * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateListITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -157,4 +157,5 @@ public class LdapTemplateListITest extends AbstractLdapTemplateIntegrationTest { tested.listBindings(BASE_NAME, handler); assertThat(handler.getNoOfRows()).isEqualTo(3); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateLookupITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateLookupITest.java index 533da621..e3d8fa8e 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateLookupITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateLookupITest.java @@ -33,11 +33,11 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests the lookup methods of LdapTemplate. - * + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -45,8 +45,8 @@ public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest /** * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set in + * the ContextSource. */ @Test public void testLookup_Plain() { @@ -59,8 +59,8 @@ public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest /** * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set in + * the ContextSource. */ @Test public void testLookupContextRoot() { @@ -91,17 +91,17 @@ public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest } /** - * An {@link AttributesMapper} that only maps a subset of the full - * attributes list. Used in tests where the return attributes list has been - * limited. - * + * An {@link AttributesMapper} that only maps a subset of the full attributes list. + * Used in tests where the return attributes list has been limited. + * * @author Ulrik Sandberg */ private final class SubsetPersonAttributesMapper implements AttributesMapper { + /** - * Maps the cn attribute into a {@link Person} object. Also - * verifies that the other attributes haven't been set. - * + * Maps the cn attribute into a {@link Person} object. Also verifies + * that the other attributes haven't been set. + * * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes) */ public Object mapFromAttributes(Attributes attributes) throws NamingException { @@ -111,11 +111,12 @@ public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest assertThat(attributes.get("description")).as("description should be null").isNull(); return person; } + } /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. + * Verifies that only the subset is used when specifying a subset of the available + * attributes as return attributes. */ @Test public void testLookup_ReturnAttributes_AttributesMapper() { @@ -129,9 +130,8 @@ public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest } /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. Uses LdapName instead - * of plain string as name. + * Verifies that only the subset is used when specifying a subset of the available + * attributes as return attributes. Uses LdapName instead of plain string as name. */ @Test public void testLookup_ReturnAttributes_AttributesMapper_LdapName() { @@ -146,8 +146,8 @@ public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest /** * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set in + * the ContextSource. */ @Test public void testLookup_ContextMapper() { @@ -160,8 +160,8 @@ public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest } /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. + * Verifies that only the subset is used when specifying a subset of the available + * attributes as return attributes. */ @Test public void testLookup_ReturnAttributes_ContextMapper() { @@ -183,4 +183,5 @@ public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest assertThat(result.getDn()).isEqualTo(expectedName); assertThat(result.getNameInNamespace()).isEqualTo("cn=Some Person2,ou=company1,ou=Sweden," + base); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateLookupMultiRdnITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateLookupMultiRdnITest.java index 4f601e82..4fcf124e 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateLookupMultiRdnITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateLookupMultiRdnITest.java @@ -30,11 +30,11 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Tests the lookup methods of LdapTemplate. - * + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateLookupMultiRdnITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -44,10 +44,9 @@ public class LdapTemplateLookupMultiRdnITest extends AbstractLdapTemplateIntegra return new ClassPathResource("/setup_data_multi_rdn.ldif"); } - /** - * Verifies that we can lookup an entry that has a multi-valued rdn, which - * means more than one attribute is part of the relative DN for the entry. + * Verifies that we can lookup an entry that has a multi-valued rdn, which means more + * than one attribute is part of the relative DN for the entry. */ @Test @Category(NoAdTest.class) @@ -61,9 +60,9 @@ public class LdapTemplateLookupMultiRdnITest extends AbstractLdapTemplateIntegra } /** - * Verifies that we can lookup an entry that has a multi-valued rdn, which - * means more than one attribute is part of the relative DN for the entry. - * + * Verifies that we can lookup an entry that has a multi-valued rdn, which means more + * than one attribute is part of the relative DN for the entry. + * */ @Test @Category(NoAdTest.class) @@ -83,4 +82,5 @@ public class LdapTemplateLookupMultiRdnITest extends AbstractLdapTemplateIntegra assertThat(result.getDn().toString()).isEqualTo("cn=Some Person+sn=Person,ou=company1,ou=Norway"); assertThat(result.getNameInNamespace()).isEqualTo("cn=Some Person+sn=Person,ou=company1,ou=Norway," + base); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateModifyITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateModifyITest.java index cf2ddc0d..c60f694d 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateModifyITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateModifyITest.java @@ -39,19 +39,18 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Tests the modification methods (rebind and modifyAttributes) of LdapTemplate. - * It also illustrates the use of DirContextAdapter as a means of getting - * ModificationItems, in order to avoid doing a full rebind and use - * modifyAttributes() instead. We rely on that the bind, unbind and lookup - * methods work as they should - that should be ok, since that is verified in a - * separate test class. NOTE: if any of the tests in this class fails, it may be - * necessary to run the cleanup script as described in README.txt under + * Tests the modification methods (rebind and modifyAttributes) of LdapTemplate. It also + * illustrates the use of DirContextAdapter as a means of getting ModificationItems, in + * order to avoid doing a full rebind and use modifyAttributes() instead. We rely on that + * the bind, unbind and lookup methods work as they should - that should be ok, since that + * is verified in a separate test class. NOTE: if any of the tests in this class fails, it + * may be necessary to run the cleanup script as described in README.txt under * /src/iutest/. - * + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -163,8 +162,8 @@ public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest /** * Test written originally to verify that duplicates are allowed on ordered - * attributes, but had to be changed since Apache DS seems to disallow - * duplicates even for ordered attributes. + * attributes, but had to be changed since Apache DS seems to disallow duplicates even + * for ordered attributes. */ @Test public void testModifyAttributes_MultiValueAddDuplicateToOrdered() { @@ -187,8 +186,8 @@ public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest @Test public void testModifyAttributes_Plain() { - ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description", - "Some other description")); + ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, + new BasicAttribute("description", "Some other description")); tested.modifyAttributes(PERSON4_DN, new ModificationItem[] { item }); @@ -197,8 +196,8 @@ public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest @Test public void testModifyAttributes_LdapName() { - ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description", - "Some other description")); + ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, + new BasicAttribute("description", "Some other description")); tested.modifyAttributes(LdapUtils.newLdapName(PERSON4_DN), new ModificationItem[] { item }); @@ -223,9 +222,9 @@ public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest } /** - * Demonstrates how the DirContextAdapter can be used to automatically keep - * track of changes of the attributes and deliver ModificationItems to use - * in moifyAttributes(). + * Demonstrates how the DirContextAdapter can be used to automatically keep track of + * changes of the attributes and deliver ModificationItems to use in + * moifyAttributes(). */ @Test public void testModifyAttributes_DirContextAdapter() throws Exception { @@ -242,9 +241,7 @@ public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest @Test public void verifyCompleteReplacementOfUniqueMemberAttribute_Ldap119Workaround() { DirContextOperations ctx = tested.lookupContext("cn=ROLE_USER,ou=groups"); - ctx.setAttributeValues("uniqueMember", - new String[]{"cn=Some Person,ou=company1,ou=Norway," + base}, - true); + ctx.setAttributeValues("uniqueMember", new String[] { "cn=Some Person,ou=company1,ou=Norway," + base }, true); ctx.getModificationItems(); tested.modifyAttributes(ctx); @@ -257,12 +254,12 @@ public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest @Test public void verifyCompleteReplacementOfUniqueMemberAttribute_Ldap119() { DirContextOperations ctx = tested.lookupContext("cn=ROLE_USER,ou=groups"); - ctx.setAttributeValues("uniqueMember", - new String[]{"cn=Some Person,ou=company1,ou=Norway," + base}); + ctx.setAttributeValues("uniqueMember", new String[] { "cn=Some Person,ou=company1,ou=Norway," + base }); ctx.getModificationItems(); tested.modifyAttributes(ctx); } + private Attributes setupAttributes() { Attributes attributes = new BasicAttributes(); BasicAttribute ocattr = new BasicAttribute("objectclass"); @@ -281,4 +278,5 @@ public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest assertThat(result.getStringAttribute("sn")).isEqualTo("Person4"); assertThat(result.getStringAttribute("description")).isEqualTo("Some other description"); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateNoBaseSuffixITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateNoBaseSuffixITest.java index 0c4fc250..231ce016 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateNoBaseSuffixITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateNoBaseSuffixITest.java @@ -32,14 +32,14 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Tests to verify that not setting a base suffix on the ContextSource (as - * defined in ldapTemplateNoBaseSuffixTestContext.xml) works as expected. - * + * Tests to verify that not setting a base suffix on the ContextSource (as defined in + * ldapTemplateNoBaseSuffixTestContext.xml) works as expected. + * * NOTE: This test will not work under Java 1.4.1 or earlier. - * + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateNoBaseSuffixTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateNoBaseSuffixTestContext.xml" }) public class LdapTemplateNoBaseSuffixITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -51,8 +51,9 @@ public class LdapTemplateNoBaseSuffixITest extends AbstractLdapTemplateIntegrati } /** - * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * This method depends on a DirObjectFactory + * ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set + * in the ContextSource. */ @Test public void testLookup_Plain() { @@ -84,8 +85,7 @@ public class LdapTemplateNoBaseSuffixITest extends AbstractLdapTemplateIntegrati adapter.setAttributeValue("sn", "Person4"); tested.bind("cn=Some Person4, ou=company1, ou=Sweden," + base, adapter, null); - DirContextAdapter result = (DirContextAdapter) tested - .lookup("cn=Some Person4, ou=company1, ou=Sweden," + base); + DirContextAdapter result = (DirContextAdapter) tested.lookup("cn=Some Person4, ou=company1, ou=Sweden," + base); assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); assertThat(result.getStringAttribute("sn")).isEqualTo("Person4"); @@ -100,4 +100,5 @@ public class LdapTemplateNoBaseSuffixITest extends AbstractLdapTemplateIntegrati assertThat(true).isTrue(); } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplatePooledITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplatePooledITest.java index 24d71fc5..9a523bd0 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplatePooledITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplatePooledITest.java @@ -33,9 +33,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * This test only works against in-process Apache DS server, regardless of configured profile. + * This test only works against in-process Apache DS server, regardless of configured + * profile. */ -@ContextConfiguration(locations = {"/conf/ldapTemplatePooledTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplatePooledTestContext.xml" }) public class LdapTemplatePooledITest extends AbstractJUnit4SpringContextTests { @Autowired @@ -54,13 +55,14 @@ public class LdapTemplatePooledITest extends AbstractJUnit4SpringContextTests { /** * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) being set in + * the ContextSource. */ @Test public void verifyThatInvalidConnectionIsAutomaticallyPurged() throws Exception { LdapTestUtils.startEmbeddedServer(1888, "dc=261consulting,dc=com", "jayway"); - LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.emptyLdapName(), new ClassPathResource("/setup_data.ldif")); + LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.emptyLdapName(), + new ClassPathResource("/setup_data.ldif")); DirContextOperations result = tested.lookupContext("cn=Some Person2, ou=company1,ou=Sweden"); assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); @@ -74,13 +76,17 @@ public class LdapTemplatePooledITest extends AbstractJUnit4SpringContextTests { try { tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); fail("Exception expected"); - } catch (Exception expected) { + } + catch (Exception expected) { // This should fail because the target connection was closed assertThat(true).isTrue(); } - LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.emptyLdapName(), new ClassPathResource("/setup_data.ldif")); - // But this should be OK, because the dirty connection should have been automatically purged. + LdapTestUtils.cleanAndSetup(contextSource, LdapUtils.emptyLdapName(), + new ClassPathResource("/setup_data.ldif")); + // But this should be OK, because the dirty connection should have been + // automatically purged. tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateRecursiveDeleteITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateRecursiveDeleteITest.java index 767a7979..ee1fd28e 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateRecursiveDeleteITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateRecursiveDeleteITest.java @@ -33,13 +33,13 @@ import javax.naming.ldap.LdapName; import static junit.framework.Assert.fail; /** - * Tests the recursive modification methods (unbind and the protected delete - * methods) of LdapTemplate. - * + * Tests the recursive modification methods (unbind and the protected delete methods) of + * LdapTemplate. + * * @author Mattias Hellborg Arthursson * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateRecursiveDeleteITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -129,4 +129,5 @@ public class LdapTemplateRecursiveDeleteITest extends AbstractLdapTemplateIntegr // expected } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateRenameITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateRenameITest.java index a0cb22cc..ad76a6b3 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateRenameITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateRenameITest.java @@ -33,13 +33,13 @@ import static org.assertj.core.api.Assertions.fail; /** * Tests the rename methods of LdapTemplate. - * - * We rely on that the bind, unbind and lookup methods work as they should - - * that should be ok, since that is verified in a separate test class. * - * + * + * We rely on that the bind, unbind and lookup methods work as they should - that should + * be ok, since that is verified in a separate test class. * + * * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateRenameITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -100,4 +100,5 @@ public class LdapTemplateRenameITest extends AbstractLdapTemplateIntegrationTest assertThat(result.getStringAttribute("sn")).isEqualTo("Person6"); assertThat(result.getStringAttribute("description")).isEqualTo("Some description"); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateSearchResultITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateSearchResultITest.java index 19747d29..46557cd1 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateSearchResultITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateSearchResultITest.java @@ -47,13 +47,12 @@ import static org.assertj.core.api.Assertions.fail; import static org.springframework.ldap.query.LdapQueryBuilder.query; /** - * Tests for LdapTemplate's search methods. This test class tests all the - * different versions of the search methods except the generic ones covered in - * other tests. - * + * Tests for LdapTemplate's search methods. This test class tests all the different + * versions of the search methods except the generic ones covered in other tests. + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrationTest { @@ -106,10 +105,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base(BASE_STRING) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); + List list = tested.search( + query().base(BASE_STRING).where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).hasSize(1); } @@ -118,35 +115,31 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base(BASE_STRING) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base(BASE_STRING).where("objectclass").is("person").and("sn").is("Person2"), + attributesMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @Test public void testSearch_LdapQuery_AttributesMapper_FewerAttributes() { - attributesMapper.setExpectedAttributes(new String[] {"cn"}); - attributesMapper.setExpectedValues(new String[]{"Some Person2"}); + attributesMapper.setExpectedAttributes(new String[] { "cn" }); + attributesMapper.setExpectedValues(new String[] { "Some Person2" }); - List list = tested.search(query() - .base(BASE_STRING) - .attributes("cn") - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.search( + query().base(BASE_STRING).attributes("cn").where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).hasSize(1); } @Test public void testSearchForStream_LdapQuery_AttributesMapper_FewerAttributes() { - attributesMapper.setExpectedAttributes(new String[] {"cn"}); - attributesMapper.setExpectedValues(new String[]{"Some Person2"}); + attributesMapper.setExpectedAttributes(new String[] { "cn" }); + attributesMapper.setExpectedValues(new String[] { "Some Person2" }); - List list = tested.searchForStream(query() - .base(BASE_STRING) - .attributes("cn") - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.searchForStream( + query().base(BASE_STRING).attributes("cn").where("objectclass").is("person").and("sn").is("Person2"), attributesMapper).collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -156,11 +149,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base(BASE_STRING) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); + List list = tested.search(query().base(BASE_STRING).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).isEmpty(); } @@ -169,11 +159,9 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base(BASE_STRING) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested.searchForStream(query().base(BASE_STRING).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), attributesMapper) + .collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -182,11 +170,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); + List list = tested.search(query().base("ou=company1,ou=Sweden").searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).hasSize(1); } @@ -195,11 +180,10 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base("ou=company1,ou=Sweden").searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), attributesMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -208,8 +192,7 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.search(query().where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).hasSize(1); } @@ -219,9 +202,9 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().where("objectclass").is("person").and("sn").is("Person2"), attributesMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -230,10 +213,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base("ou=Norway") - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); + List list = tested.search( + query().base("ou=Norway").where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).isEmpty(); } @@ -242,10 +223,10 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base("ou=Norway") - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base("ou=Norway").where("objectclass").is("person").and("sn").is("Person2"), + attributesMapper) + .collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -288,8 +269,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati attributesMapper.setExpectedAttributes(CN_SN_ATTRS); attributesMapper.setExpectedValues(CN_SN_VALUES); attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested - .search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, attributesMapper); + List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + attributesMapper); assertThat(list).hasSize(1); } @@ -305,8 +286,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearchForObject() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - DirContextAdapter result = (DirContextAdapter) tested - .searchForObject(BASE_STRING, FILTER_STRING, contextMapper); + DirContextAdapter result = (DirContextAdapter) tested.searchForObject(BASE_STRING, FILTER_STRING, + contextMapper); assertThat(result).isNotNull(); } @@ -322,12 +303,13 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati @Test(expected = EmptyResultDataAccessException.class) public void testSearchForObjectNoHits() { - tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=Person does not exist))", new AbstractContextMapper() { - @Override - protected Object doMapFromContext(DirContextOperations ctx) { - return ctx; - } - }); + tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=Person does not exist))", + new AbstractContextMapper() { + @Override + protected Object doMapFromContext(DirContextOperations ctx) { + return ctx; + } + }); } @Test @@ -359,10 +341,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearch_ContextMapper_LdapQuery() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base(BASE_NAME) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper); + List list = tested.search( + query().base(BASE_NAME).where("objectclass").is("person").and("sn").is("Person2"), contextMapper); assertThat(list).hasSize(1); } @@ -370,10 +350,10 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearchForStream_ContextMapper_LdapQuery() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base(BASE_NAME) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base(BASE_NAME).where("objectclass").is("person").and("sn").is("Person2"), + contextMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -381,8 +361,7 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearch_ContextMapper_LdapQuery_NoBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.search(query().where("objectclass").is("person").and("sn").is("Person2"), contextMapper); assertThat(list).hasSize(1); } @@ -391,9 +370,9 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearchForStream_ContextMapper_LdapQuery_NoBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().where("objectclass").is("person").and("sn").is("Person2"), contextMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -401,11 +380,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearch_ContextMapper_LdapQuery_SearchScope() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base(BASE_NAME) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper); + List list = tested.search(query().base(BASE_NAME).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), contextMapper); assertThat(list).isEmpty(); } @@ -413,11 +389,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearchForStream_ContextMapper_LdapQuery_SearchScope() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base(BASE_NAME) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper).collect(Collectors.toList()); + List list = tested.searchForStream(query().base(BASE_NAME).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), contextMapper).collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -425,10 +398,8 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearch_ContextMapper_LdapQuery_SearchScope_CorrectBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.search(query().base("ou=company1,ou=Sweden") + .searchScope(SearchScope.ONELEVEL).where("objectclass").is("person").and("sn").is("Person2"), contextMapper); assertThat(list).hasSize(1); } @@ -437,18 +408,17 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati public void testSearchForStream_ContextMapper_LdapQuery_SearchScope_CorrectBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base("ou=company1,ou=Sweden").searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), contextMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @Test public void testSearchForContext_LdapQuery() { - DirContextOperations result = tested.searchForContext(query() - .where("objectclass").is("person").and("sn").is("Person2")); + DirContextOperations result = tested + .searchForContext(query().where("objectclass").is("person").and("sn").is("Person2")); assertThat(result).isNotNull(); assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); @@ -456,18 +426,14 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati @Test(expected = EmptyResultDataAccessException.class) public void testSearchForContext_LdapQuery_SearchScopeNotFound() { - tested.searchForContext(query() - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")); + tested.searchForContext( + query().searchScope(SearchScope.ONELEVEL).where("objectclass").is("person").and("sn").is("Person2")); } @Test public void testSearchForContext_LdapQuery_SearchScope_CorrectBase() { - DirContextOperations result = - tested.searchForContext(query() - .searchScope(SearchScope.ONELEVEL) - .base("ou=company1,ou=Sweden") - .where("objectclass").is("person").and("sn").is("Person2")); + DirContextOperations result = tested.searchForContext(query().searchScope(SearchScope.ONELEVEL) + .base("ou=company1,ou=Sweden").where("objectclass").is("person").and("sn").is("Person2")); assertThat(result).isNotNull(); assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); @@ -515,14 +481,13 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati @Test public void verifyThatSearchWithCountLimitReturnsTheEntriesFoundSoFar() { - List result = tested.search(query() - .countLimit(3) - .where("objectclass").is("person"), new ContextMapper() { - @Override - public Object mapFromContext(Object ctx) throws NamingException { - return new Object(); - } - }); + List result = tested.search(query().countLimit(3).where("objectclass").is("person"), + new ContextMapper() { + @Override + public Object mapFromContext(Object ctx) throws NamingException { + return new Object(); + } + }); assertThat(result).hasSize(3); } @@ -530,13 +495,12 @@ public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrati @Test(expected = SizeLimitExceededException.class) public void verifyThatSearchWithCountLimitWithFlagToFalseThrowsException() { tested.setIgnoreSizeLimitExceededException(false); - tested.search(query() - .countLimit(3) - .where("objectclass").is("person"), new ContextMapper() { + tested.search(query().countLimit(3).where("objectclass").is("person"), new ContextMapper() { @Override public Object mapFromContext(Object ctx) throws NamingException { return new Object(); } }); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateSearchResultNamespaceConfigITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateSearchResultNamespaceConfigITest.java index 9f640901..f2384b70 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateSearchResultNamespaceConfigITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateSearchResultNamespaceConfigITest.java @@ -44,13 +44,12 @@ import static org.assertj.core.api.Assertions.fail; import static org.springframework.ldap.query.LdapQueryBuilder.query; /** - * Tests for LdapTemplate's search methods. This test class tests all the - * different versions of the search methods except the generic ones covered in - * other tests. - * + * Tests for LdapTemplate's search methods. This test class tests all the different + * versions of the search methods except the generic ones covered in other tests. + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateNamespaceTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateNamespaceTestContext.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTemplateIntegrationTest { @@ -103,10 +102,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base(BASE_STRING) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); + List list = tested.search( + query().base(BASE_STRING).where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).hasSize(1); } @@ -115,35 +112,31 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base(BASE_STRING) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base(BASE_STRING).where("objectclass").is("person").and("sn").is("Person2"), + attributesMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @Test public void testSearch_LdapQuery_AttributesMapper_FewerAttributes() { - attributesMapper.setExpectedAttributes(new String[] {"cn"}); - attributesMapper.setExpectedValues(new String[]{"Some Person2"}); + attributesMapper.setExpectedAttributes(new String[] { "cn" }); + attributesMapper.setExpectedValues(new String[] { "Some Person2" }); - List list = tested.search(query() - .base(BASE_STRING) - .attributes("cn") - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.search( + query().base(BASE_STRING).attributes("cn").where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).hasSize(1); } @Test public void testSearchForStream_LdapQuery_AttributesMapper_FewerAttributes() { - attributesMapper.setExpectedAttributes(new String[] {"cn"}); - attributesMapper.setExpectedValues(new String[]{"Some Person2"}); + attributesMapper.setExpectedAttributes(new String[] { "cn" }); + attributesMapper.setExpectedValues(new String[] { "Some Person2" }); - List list = tested.searchForStream(query() - .base(BASE_STRING) - .attributes("cn") - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.searchForStream( + query().base(BASE_STRING).attributes("cn").where("objectclass").is("person").and("sn").is("Person2"), attributesMapper).collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -153,11 +146,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base(BASE_STRING) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); + List list = tested.search(query().base(BASE_STRING).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).isEmpty(); } @@ -166,11 +156,9 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base(BASE_STRING) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested.searchForStream(query().base(BASE_STRING).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), attributesMapper) + .collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -179,11 +167,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); + List list = tested.search(query().base("ou=company1,ou=Sweden").searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).hasSize(1); } @@ -192,11 +177,10 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base("ou=company1,ou=Sweden").searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), attributesMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -205,8 +189,7 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.search(query().where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).hasSize(1); } @@ -216,9 +199,9 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().where("objectclass").is("person").and("sn").is("Person2"), attributesMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -227,10 +210,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base("ou=Norway") - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); + List list = tested.search( + query().base("ou=Norway").where("objectclass").is("person").and("sn").is("Person2"), attributesMapper); assertThat(list).isEmpty(); } @@ -239,10 +220,10 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base("ou=Norway") - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base("ou=Norway").where("objectclass").is("person").and("sn").is("Person2"), + attributesMapper) + .collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -285,8 +266,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe attributesMapper.setExpectedAttributes(CN_SN_ATTRS); attributesMapper.setExpectedValues(CN_SN_VALUES); attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested - .search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, attributesMapper); + List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + attributesMapper); assertThat(list).hasSize(1); } @@ -302,8 +283,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearchForObject() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - DirContextAdapter result = (DirContextAdapter) tested - .searchForObject(BASE_STRING, FILTER_STRING, contextMapper); + DirContextAdapter result = (DirContextAdapter) tested.searchForObject(BASE_STRING, FILTER_STRING, + contextMapper); assertThat(result).isNotNull(); } @@ -319,12 +300,13 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe @Test(expected = EmptyResultDataAccessException.class) public void testSearchForObjectNoHits() { - tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=Person does not exist))", new AbstractContextMapper() { - @Override - protected Object doMapFromContext(DirContextOperations ctx) { - return ctx; - } - }); + tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=Person does not exist))", + new AbstractContextMapper() { + @Override + protected Object doMapFromContext(DirContextOperations ctx) { + return ctx; + } + }); } @Test @@ -356,10 +338,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearch_ContextMapper_LdapQuery() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base(BASE_NAME) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper); + List list = tested.search( + query().base(BASE_NAME).where("objectclass").is("person").and("sn").is("Person2"), contextMapper); assertThat(list).hasSize(1); } @@ -367,10 +347,10 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearchForStream_ContextMapper_LdapQuery() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base(BASE_NAME) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base(BASE_NAME).where("objectclass").is("person").and("sn").is("Person2"), + contextMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -378,8 +358,7 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearch_ContextMapper_LdapQuery_NoBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.search(query().where("objectclass").is("person").and("sn").is("Person2"), contextMapper); assertThat(list).hasSize(1); } @@ -388,9 +367,9 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearchForStream_ContextMapper_LdapQuery_NoBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().where("objectclass").is("person").and("sn").is("Person2"), contextMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @@ -398,11 +377,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearch_ContextMapper_LdapQuery_SearchScope() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base(BASE_NAME) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper); + List list = tested.search(query().base(BASE_NAME).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), contextMapper); assertThat(list).isEmpty(); } @@ -410,11 +386,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearchForStream_ContextMapper_LdapQuery_SearchScope() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base(BASE_NAME) - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper).collect(Collectors.toList()); + List list = tested.searchForStream(query().base(BASE_NAME).searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), contextMapper).collect(Collectors.toList()); assertThat(list).isEmpty(); } @@ -422,10 +395,8 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearch_ContextMapper_LdapQuery_SearchScope_CorrectBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), + List list = tested.search(query().base("ou=company1,ou=Sweden") + .searchScope(SearchScope.ONELEVEL).where("objectclass").is("person").and("sn").is("Person2"), contextMapper); assertThat(list).hasSize(1); } @@ -434,18 +405,17 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe public void testSearchForStream_ContextMapper_LdapQuery_SearchScope_CorrectBase() { contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.searchForStream(query() - .base("ou=company1,ou=Sweden") - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2"), - contextMapper).collect(Collectors.toList()); + List list = tested + .searchForStream(query().base("ou=company1,ou=Sweden").searchScope(SearchScope.ONELEVEL) + .where("objectclass").is("person").and("sn").is("Person2"), contextMapper) + .collect(Collectors.toList()); assertThat(list).hasSize(1); } @Test public void testSearchForContext_LdapQuery() { - DirContextOperations result = tested.searchForContext(query() - .where("objectclass").is("person").and("sn").is("Person2")); + DirContextOperations result = tested + .searchForContext(query().where("objectclass").is("person").and("sn").is("Person2")); assertThat(result).isNotNull(); assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); @@ -453,18 +423,14 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe @Test(expected = EmptyResultDataAccessException.class) public void testSearchForContext_LdapQuery_SearchScopeNotFound() { - tested.searchForContext(query() - .searchScope(SearchScope.ONELEVEL) - .where("objectclass").is("person").and("sn").is("Person2")); + tested.searchForContext( + query().searchScope(SearchScope.ONELEVEL).where("objectclass").is("person").and("sn").is("Person2")); } @Test public void testSearchForContext_LdapQuery_SearchScope_CorrectBase() { - DirContextOperations result = - tested.searchForContext(query() - .searchScope(SearchScope.ONELEVEL) - .base("ou=company1,ou=Sweden") - .where("objectclass").is("person").and("sn").is("Person2")); + DirContextOperations result = tested.searchForContext(query().searchScope(SearchScope.ONELEVEL) + .base("ou=company1,ou=Sweden").where("objectclass").is("person").and("sn").is("Person2")); assertThat(result).isNotNull(); assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); @@ -509,4 +475,5 @@ public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTe contextMapper); assertThat(list).isEmpty(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/control/SupportedControlsITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/control/SupportedControlsITest.java index b0d0556c..e856d225 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/control/SupportedControlsITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/control/SupportedControlsITest.java @@ -35,11 +35,12 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Provides tests that verify that the server supports certain controls. - * + * * @author Ulrik Sandberg */ -@ContextConfiguration(locations = {"/conf/rootContextSourceTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/rootContextSourceTestContext.xml" }) public class SupportedControlsITest extends AbstractLdapTemplateIntegrationTest { + /** must use a context source that has no base set */ @Autowired private LdapTemplate tested; @@ -50,7 +51,7 @@ public class SupportedControlsITest extends AbstractLdapTemplateIntegrationTest protected Name getRoot() { return LdapUtils.newLdapName(base); } - + @Test @Category(NoAdTest.class) public void testExpectedControlsSupported() throws Exception { @@ -71,8 +72,10 @@ public class SupportedControlsITest extends AbstractLdapTemplateIntegrationTest HashSet controlsSet = new HashSet(Arrays.asList(controls)); - assertThat(controlsSet.contains("1.3.6.1.4.1.4203.1.10.1")).as("Entry Change Notification LDAPv3 control,").isTrue(); + assertThat(controlsSet.contains("1.3.6.1.4.1.4203.1.10.1")).as("Entry Change Notification LDAPv3 control,") + .isTrue(); assertThat(controlsSet.contains("1.3.6.1.4.1.4203.1.10.1")).as("Subentries Control,").isTrue(); assertThat(controlsSet.contains("2.16.840.1.113730.3.4.2")).as("Manage DSA IT LDAPv3 control,").isTrue(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/DistinguishedNameEditorITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/DistinguishedNameEditorITest.java index f6af448e..faf6b1f1 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/DistinguishedNameEditorITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/DistinguishedNameEditorITest.java @@ -25,10 +25,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Integration tests for {@link org.springframework.ldap.core.DistinguishedNameEditor}. - * + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/distinguishedNameEditorTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/distinguishedNameEditorTestContext.xml" }) public class DistinguishedNameEditorITest extends AbstractJUnit4SpringContextTests { @Autowired @@ -40,4 +40,5 @@ public class DistinguishedNameEditorITest extends AbstractJUnit4SpringContextTes DistinguishedName name = distinguishedNameConsumer.getDistinguishedName(); assertThat(name).isEqualTo(new DistinguishedName("dc=jayway, dc=se")); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/DnParsePerformanceITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/DnParsePerformanceITest.java index 1447e9f5..6be241d0 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/DnParsePerformanceITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/DnParsePerformanceITest.java @@ -22,7 +22,7 @@ import org.springframework.util.StopWatch; /** * Performance test for the {@link DistinguishedName} class. - * + * * @author Ulrik Sandberg */ public class DnParsePerformanceITest { @@ -60,7 +60,7 @@ public class DnParsePerformanceITest { StopWatch stopWatch = new StopWatch("Create from DistinguishedName"); stopWatch.start(); - + for (int i = 0; i < 2000; i++) { migpath = new DistinguishedName(migpath); path1 = new DistinguishedName(path1); @@ -75,4 +75,5 @@ public class DnParsePerformanceITest { stopWatch.stop(); System.out.println(stopWatch.prettyPrint()); } + } \ No newline at end of file diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/simple/SimpleLdapTemplateITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/simple/SimpleLdapTemplateITest.java index 449137b9..4aa0ada2 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/simple/SimpleLdapTemplateITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/simple/SimpleLdapTemplateITest.java @@ -42,8 +42,9 @@ import org.springframework.test.context.ContextConfiguration; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; -@ContextConfiguration(locations = {"/conf/simpleLdapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/simpleLdapTemplateTestContext.xml" }) public class SimpleLdapTemplateITest extends AbstractLdapTemplateIntegrationTest { + private static String DN_STRING = "cn=Some Person4,ou=company1,ou=Sweden"; private static LdapName DN = LdapUtils.newLdapName("cn=Some Person4,ou=company1,ou=Sweden"); @@ -139,8 +140,8 @@ public class SimpleLdapTemplateITest extends AbstractLdapTemplateIntegrationTest @Test public void testModifyAttributesName() { - DirContextOperations ctx = ldapTemplate.lookupContext(LdapUtils.newLdapName( - "cn=Some Person,ou=company1,ou=Sweden")); + DirContextOperations ctx = ldapTemplate + .lookupContext(LdapUtils.newLdapName("cn=Some Person,ou=company1,ou=Sweden")); ctx.setAttributeValue("description", "updated description"); ctx.setAttributeValue("telephoneNumber", "0000001"); @@ -204,7 +205,7 @@ public class SimpleLdapTemplateITest extends AbstractLdapTemplateIntegrationTest filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); assertThat(ldapTemplate.authenticate("", filter.toString(), "password")).isTrue(); } - + private void verifyBoundCorrectData() { DirContextOperations result = ldapTemplate.lookupContext(DN_STRING); assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); @@ -228,6 +229,7 @@ public class SimpleLdapTemplateITest extends AbstractLdapTemplateIntegrationTest return adapter.getStringAttribute("cn"); } + } private static final class DummyDirContextProcessor implements DirContextProcessor { @@ -253,4 +255,5 @@ public class SimpleLdapTemplateITest extends AbstractLdapTemplateIntegrationTest } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorITest.java index 388491cd..bf082c19 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorITest.java @@ -27,8 +27,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Integration tests for {@link org.springframework.ldap.core.support.BaseLdapPathBeanPostProcessor}. - * + * Integration tests for + * {@link org.springframework.ldap.core.support.BaseLdapPathBeanPostProcessor}. + * * @author Mattias Hellborg Arthursson */ public class BaseLdapPathBeanPostprocessorITest { @@ -103,4 +104,5 @@ public class BaseLdapPathBeanPostprocessorITest { assertThat(base).isNotNull(); assertThat(base).isEqualTo(new DistinguishedName("dc=261consulting,dc=com")); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorNamespaceConfigITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorNamespaceConfigITest.java index a2468be7..b31667a1 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorNamespaceConfigITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorNamespaceConfigITest.java @@ -24,8 +24,9 @@ import org.springframework.ldap.support.LdapUtils; import static org.assertj.core.api.Assertions.assertThat; /** - * Integration tests for {@link org.springframework.ldap.core.support.BaseLdapPathBeanPostProcessor}. - * + * Integration tests for + * {@link org.springframework.ldap.core.support.BaseLdapPathBeanPostProcessor}. + * * @author Mattias Hellborg Arthursson */ public class BaseLdapPathBeanPostprocessorNamespaceConfigITest { @@ -58,5 +59,4 @@ public class BaseLdapPathBeanPostprocessorNamespaceConfigITest { assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=jayway,dc=se")); } - } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/LdapContextSourceIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/LdapContextSourceIntegrationTest.java index e9a5d2cd..a7ea6c5a 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/LdapContextSourceIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/LdapContextSourceIntegrationTest.java @@ -43,10 +43,10 @@ import static org.assertj.core.api.Assertions.fail; /** * Integration tests for LdapContextSource. - * + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapContextSourceIntegrationTest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -160,9 +160,12 @@ public class LdapContextSourceIntegrationTest extends AbstractLdapTemplateIntegr } private final static class DnContextMapper extends AbstractContextMapper { + @Override protected String doMapFromContext(DirContextOperations ctx) { return ctx.getNameInNamespace(); } + } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/LdapContextSourceMultiServerIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/LdapContextSourceMultiServerIntegrationTest.java index 3a86b48e..036c500b 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/LdapContextSourceMultiServerIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/LdapContextSourceMultiServerIntegrationTest.java @@ -27,10 +27,10 @@ import static org.assertj.core.api.Assertions.assertThat; /** * Advanced integration tests for LdapContextSource. - * + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapContextSourceTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapContextSourceTestContext.xml" }) public class LdapContextSourceMultiServerIntegrationTest extends AbstractJUnit4SpringContextTests { @Autowired @@ -43,4 +43,5 @@ public class LdapContextSourceMultiServerIntegrationTest extends AbstractJUnit4S assertThat(string).isEqualTo("ldap://127.0.0.1:389 ldap://127.0.0.2:389"); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/filter/HardcodedFilterIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/filter/HardcodedFilterIntegrationTest.java index cff1c762..56ba0763 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/filter/HardcodedFilterIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/filter/HardcodedFilterIntegrationTest.java @@ -30,7 +30,7 @@ import static org.assertj.core.api.Assertions.assertThat; /** * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/hardcodedFilterTestContext.xml", "/conf/ldapTemplateTestContext.xml" }) +@ContextConfiguration(locations = { "/conf/hardcodedFilterTestContext.xml", "/conf/ldapTemplateTestContext.xml" }) public class HardcodedFilterIntegrationTest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -45,7 +45,7 @@ public class HardcodedFilterIntegrationTest extends AbstractLdapTemplateIntegrat assertThat(filter instanceof HardcodedFilter).isTrue(); assertThat(filter.toString()).isEqualTo("(&(objectclass=person)(!(objectclass=computer))"); } - + @Test public void verifyThatWildcardsAreUnescaped() { HardcodedFilter filter = new HardcodedFilter("cn=Some*"); @@ -54,4 +54,5 @@ public class HardcodedFilterIntegrationTest extends AbstractLdapTemplateIntegrat int hits = handler.getNoOfRows(); assertThat(hits > 1).isTrue(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/integration/JiraLdap247ITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/integration/JiraLdap247ITest.java index 513cf687..13f20c98 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/integration/JiraLdap247ITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/integration/JiraLdap247ITest.java @@ -25,12 +25,12 @@ import org.springframework.test.context.ContextConfiguration; import static org.assertj.core.api.Assertions.assertThat; /** - * Tests for https://jira.springsource.org/browse/LDAP-247. - * Thanks to Jürgen Failenschmid for spotting the problem and providing the code for testing this. - * + * Tests for https://jira.springsource.org/browse/LDAP-247. Thanks to Jürgen Failenschmid + * for spotting the problem and providing the code for testing this. + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldap-247-testContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldap-247-testContext.xml" }) public class JiraLdap247ITest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -40,8 +40,11 @@ public class JiraLdap247ITest extends AbstractLdapTemplateIntegrationTest { public void verifyThatBasePathIsProperlyPopulated() { assertThat(ldapGroupDao).isNotNull(); - // The base path should be automatically populated by BaseLdapPathBeanPostProcessor, - // but it doesn't unless it implements Ordered, which caused the assertion below to fail. + // The base path should be automatically populated by + // BaseLdapPathBeanPostProcessor, + // but it doesn't unless it implements Ordered, which caused the assertion below + // to fail. assertThat(ldapGroupDao.getBasePath()).isNotNull(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/ldap321/Ldap321Test.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/ldap321/Ldap321Test.java index aac388e8..568ee0de 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/ldap321/Ldap321Test.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/ldap321/Ldap321Test.java @@ -34,17 +34,19 @@ import org.springframework.transaction.annotation.Transactional; @ContextConfiguration("classpath:ldap321.xml") @Transactional @Rollback -public class Ldap321Test{ +public class Ldap321Test { + @Autowired private RoleRepo roleRepo; @Test public void testQueryRoleMap() throws Exception { - Map roleMap=roleRepo.queryRoleMap(); + Map roleMap = roleRepo.queryRoleMap(); assertThat(roleMap).isNotNull(); - for(String roleName:roleMap.keySet()){ - System.out.println(roleName+":"+ roleMap.get(roleName)); + for (String roleName : roleMap.keySet()) { + System.out.println(roleName + ":" + roleMap.get(roleName)); } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/ldap321/RoleRepo.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/ldap321/RoleRepo.java index 3a961a4e..258ebd25 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/ldap321/RoleRepo.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/ldap321/RoleRepo.java @@ -26,8 +26,8 @@ import org.springframework.transaction.annotation.Transactional; public class RoleRepo { @Transactional - public Map queryRoleMap() { - return new HashMap(); + public Map queryRoleMap() { + return new HashMap(); } } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerIntegrationTest.java index 34fa4532..5f592885 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerIntegrationTest.java @@ -43,14 +43,16 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Integration tests for {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager}. - * + * Integration tests for + * {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager}. + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapAndJdbcTransactionTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapAndJdbcTransactionTestContext.xml" }) public class ContextSourceAndDataSourceTransactionManagerIntegrationTest extends AbstractLdapTemplateIntegrationTest { - private static Logger log = LoggerFactory.getLogger(ContextSourceAndDataSourceTransactionManagerIntegrationTest.class); + private static Logger log = LoggerFactory + .getLogger(ContextSourceAndDataSourceTransactionManagerIntegrationTest.class); @Autowired @Qualifier("dummyDao") @@ -69,9 +71,10 @@ public class ContextSourceAndDataSourceTransactionManagerIntegrationTest extends } jdbcTemplate.execute("drop table PERSON if exists"); - jdbcTemplate.execute("create table PERSON(fullname VARCHAR(256), lastname VARCHAR(256), description VARCHAR(256))"); - jdbcTemplate.update("insert into PERSON values(?, ?, ?)", new Object[] { "Some Person", "Person", - "Sweden, Company1, Some Person" }); + jdbcTemplate + .execute("create table PERSON(fullname VARCHAR(256), lastname VARCHAR(256), description VARCHAR(256))"); + jdbcTemplate.update("insert into PERSON values(?, ?, ?)", + new Object[] { "Some Person", "Person", "Sweden, Company1, Some Person" }); } @After @@ -347,4 +350,5 @@ public class ContextSourceAndDataSourceTransactionManagerIntegrationTest extends assertThat(true).isTrue(); } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest.java index fe69de39..8e8e3ac6 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest.java @@ -36,14 +36,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Integration tests for {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager}. + * Integration tests for + * {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager}. * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/missingLdapAndJdbcTransactionTestContext.xml"}) -public class ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest extends AbstractJUnit4SpringContextTests { +@ContextConfiguration(locations = { "/conf/missingLdapAndJdbcTransactionTestContext.xml" }) +public class ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest + extends AbstractJUnit4SpringContextTests { - private static Logger log = LoggerFactory.getLogger(ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest.class); + private static Logger log = LoggerFactory + .getLogger(ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest.class); @Autowired @Qualifier("dummyDao") @@ -67,13 +70,13 @@ public class ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest jdbcTemplate.execute("drop table PERSON if exists"); } - @Test public void verifyThatJdbcTransactionIsClosedIfLdapServerUnavailable_ldap179() { try { dummyDao.create("Sweden", "company1", "some testperson", "testperson", "some description"); fail("CannotCreateTransactionException expected"); - } catch (CannotCreateTransactionException expected) { + } + catch (CannotCreateTransactionException expected) { assertThat(expected.getCause() instanceof CommunicationException).isTrue(); } @@ -83,8 +86,10 @@ public class ContextSourceAndDataSourceTransactionManagerLdap179IntegrationTest try { dummyDao.create("Sweden", "company1", "some testperson", "testperson", "some description"); fail("CannotCreateTransactionException expected"); - } catch (CannotCreateTransactionException expected) { + } + catch (CannotCreateTransactionException expected) { assertThat(expected.getCause() instanceof CommunicationException).isTrue(); } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerNamespaceITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerNamespaceITest.java index e4083af3..64b4a975 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerNamespaceITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceAndDataSourceTransactionManagerNamespaceITest.java @@ -44,15 +44,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Integration tests for {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager} + * Integration tests for + * {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager} * with namespace configuration. - * + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapAndJdbcTransactionNamespaceTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapAndJdbcTransactionNamespaceTestContext.xml" }) public class ContextSourceAndDataSourceTransactionManagerNamespaceITest extends AbstractLdapTemplateIntegrationTest { - private static Logger log = LoggerFactory.getLogger(ContextSourceAndDataSourceTransactionManagerNamespaceITest.class); + private static Logger log = LoggerFactory + .getLogger(ContextSourceAndDataSourceTransactionManagerNamespaceITest.class); @Autowired @Qualifier("dummyDao") @@ -71,9 +73,10 @@ public class ContextSourceAndDataSourceTransactionManagerNamespaceITest extends } jdbcTemplate.execute("drop table PERSON if exists"); - jdbcTemplate.execute("create table PERSON(fullname VARCHAR(256), lastname VARCHAR(256), description VARCHAR(256))"); - jdbcTemplate.update("insert into PERSON values(?, ?, ?)", new Object[] { "Some Person", "Person", - "Sweden, Company1, Some Person" }); + jdbcTemplate + .execute("create table PERSON(fullname VARCHAR(256), lastname VARCHAR(256), description VARCHAR(256))"); + jdbcTemplate.update("insert into PERSON values(?, ?, ?)", + new Object[] { "Some Person", "Person", "Sweden, Company1, Some Person" }); } @After @@ -349,4 +352,5 @@ public class ContextSourceAndDataSourceTransactionManagerNamespaceITest extends assertThat(true).isTrue(); } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerIntegrationTest.java index f6ca3e9a..8cc6c27f 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerIntegrationTest.java @@ -37,11 +37,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Integration tests for {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceTransactionManager}. - * + * Integration tests for + * {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceTransactionManager}. + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTransactionTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTransactionTestContext.xml" }) public class ContextSourceTransactionManagerIntegrationTest extends AbstractLdapTemplateIntegrationTest { private static Logger log = LoggerFactory.getLogger(ContextSourceTransactionManagerIntegrationTest.class); @@ -269,4 +270,5 @@ public class ContextSourceTransactionManagerIntegrationTest extends AbstractLdap } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerNamespaceIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerNamespaceIntegrationTest.java index eb2ec2aa..ff90411c 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerNamespaceIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerNamespaceIntegrationTest.java @@ -37,12 +37,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Integration tests for {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceTransactionManager} + * Integration tests for + * {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceTransactionManager} * that uses the spring ldap namespace for configuration. - * + * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateNamespaceTransactionTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateNamespaceTransactionTestContext.xml" }) public class ContextSourceTransactionManagerNamespaceIntegrationTest extends AbstractLdapTemplateIntegrationTest { private static Logger log = LoggerFactory.getLogger(ContextSourceTransactionManagerNamespaceIntegrationTest.class); @@ -270,4 +271,5 @@ public class ContextSourceTransactionManagerNamespaceIntegrationTest extends Abs } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerSubtreeIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerSubtreeIntegrationTest.java index de77ef50..ebd044f7 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerSubtreeIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/ContextSourceTransactionManagerSubtreeIntegrationTest.java @@ -34,12 +34,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Integration tests for {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager} + * Integration tests for + * {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndDataSourceTransactionManager} * that tests unbind/rebind of recursive entries. * * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTransactionSubtreeTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTransactionSubtreeTestContext.xml" }) public class ContextSourceTransactionManagerSubtreeIntegrationTest extends AbstractLdapTemplateIntegrationTest { @Autowired @@ -67,7 +68,8 @@ public class ContextSourceTransactionManagerSubtreeIntegrationTest extends Abstr try { ldapTemplate.lookup("ou=company1,ou=Sweden"); fail("NameNotFoundException expected"); - } catch (NameNotFoundException expected) { + } + catch (NameNotFoundException expected) { assertThat(true).isTrue(); } } @@ -77,7 +79,8 @@ public class ContextSourceTransactionManagerSubtreeIntegrationTest extends Abstr try { dummyDao.deleteRecursivelyWithException("ou=company1,ou=Sweden"); fail("DummyException expected"); - } catch (DummyException expected) { + } + catch (DummyException expected) { assertThat(true).isTrue(); } @@ -95,8 +98,10 @@ public class ContextSourceTransactionManagerSubtreeIntegrationTest extends Abstr try { dummyDao.createRecursivelyAndUnbindSubnodeWithException(); fail("DummyException expected"); - } catch (DummyException expected) { + } + catch (DummyException expected) { assertThat(true).isTrue(); } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerIntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerIntegrationTest.java index 1df92510..befe9bb6 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerIntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerIntegrationTest.java @@ -50,10 +50,11 @@ import static org.assertj.core.api.Assertions.fail; * * @author Hans Westerbeek */ -@ContextConfiguration(locations = {"/conf/ldapAndHibernateTransactionTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapAndHibernateTransactionTestContext.xml" }) public class ContextSourceAndHibernateTransactionManagerIntegrationTest extends AbstractLdapTemplateIntegrationTest { - private static Logger log = LoggerFactory.getLogger(ContextSourceAndHibernateTransactionManagerIntegrationTest.class); + private static Logger log = LoggerFactory + .getLogger(ContextSourceAndHibernateTransactionManagerIntegrationTest.class); @Autowired @Qualifier("dummyDao") @@ -367,4 +368,5 @@ public class ContextSourceAndHibernateTransactionManagerIntegrationTest extends person = (OrgPerson) this.hibernateTemplate.get(OrgPerson.class, new Integer(1)); assertThat(person).isNull(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest.java index 3c2e6f13..73f9c2a9 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest.java @@ -33,14 +33,17 @@ import org.springframework.transaction.support.TransactionSynchronizationManager import static org.assertj.core.api.Assertions.assertThat; /** - * Integration tests for {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndHibernateTransactionManager}. + * Integration tests for + * {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndHibernateTransactionManager}. * * @author Hans Westerbeek */ -@ContextConfiguration(locations = {"/conf/missingLdapAndHibernateTransactionTestContext.xml"}) -public class ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest extends AbstractJUnit4SpringContextTests { +@ContextConfiguration(locations = { "/conf/missingLdapAndHibernateTransactionTestContext.xml" }) +public class ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest + extends AbstractJUnit4SpringContextTests { - private static Logger log = LoggerFactory.getLogger(ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest.class); + private static Logger log = LoggerFactory + .getLogger(ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest.class); @Autowired @Qualifier("dummyDao") @@ -66,7 +69,8 @@ public class ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest e try { this.dummyDao.create(person); - } catch (CannotCreateTransactionException expected) { + } + catch (CannotCreateTransactionException expected) { assertThat(expected.getCause() instanceof CommunicationException).isTrue(); } @@ -75,8 +79,10 @@ public class ContextSourceAndHibernateTransactionManagerLdap179IntegrationTest e try { this.dummyDao.create(person); - } catch (CannotCreateTransactionException expected) { + } + catch (CannotCreateTransactionException expected) { assertThat(expected.getCause() instanceof CommunicationException).isTrue(); } } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerNamespaceITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerNamespaceITest.java index e7979e08..c75aabcc 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerNamespaceITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/manager/hibernate/ContextSourceAndHibernateTransactionManagerNamespaceITest.java @@ -45,15 +45,17 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; /** - * Integration tests for {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndHibernateTransactionManager} + * Integration tests for + * {@link org.springframework.ldap.transaction.compensating.manager.ContextSourceAndHibernateTransactionManager} * with namespace configuration. * * @author Hans Westerbeek */ -@ContextConfiguration(locations = {"/conf/ldapAndHibernateTransactionNamespaceTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapAndHibernateTransactionNamespaceTestContext.xml" }) public class ContextSourceAndHibernateTransactionManagerNamespaceITest extends AbstractLdapTemplateIntegrationTest { - private static Logger log = LoggerFactory.getLogger(ContextSourceAndHibernateTransactionManagerNamespaceITest.class); + private static Logger log = LoggerFactory + .getLogger(ContextSourceAndHibernateTransactionManagerNamespaceITest.class); @Autowired @Qualifier("dummyDao") @@ -367,4 +369,5 @@ public class ContextSourceAndHibernateTransactionManagerNamespaceITest extends A person = (OrgPerson) this.hibernateTemplate.get(OrgPerson.class, new Integer(1)); assertThat(person).isNull(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmGroupManipulationITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmGroupManipulationITest.java index 5547d21e..ce7252f4 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmGroupManipulationITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmGroupManipulationITest.java @@ -33,8 +33,9 @@ import static org.springframework.ldap.query.LdapQueryBuilder.query; /** * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateOdmGroupManipulationITest extends AbstractLdapTemplateIntegrationTest { + @Autowired private LdapTemplate tested; @@ -127,10 +128,12 @@ public class LdapTemplateOdmGroupManipulationITest extends AbstractLdapTemplateI public void testSetMembersSyntacticallyEqual() { Group group = tested.findOne(query().where("cn").is("ROLE_USER"), Group.class); - group.setMembers(new HashSet(){{ - add(LdapUtils.newLdapName("CN=Some Person,OU=company1, ou=Sweden, " + base)); - add(LdapUtils.newLdapName("CN=Some Person2, OU=company1,ou=Sweden," + base)); - }}); + group.setMembers(new HashSet() { + { + add(LdapUtils.newLdapName("CN=Some Person,OU=company1, ou=Sweden, " + base)); + add(LdapUtils.newLdapName("CN=Some Person2, OU=company1,ou=Sweden," + base)); + } + }); tested.update(group); Group verification = tested.findOne(query().where("cn").is("ROLE_USER"), Group.class); @@ -141,4 +144,5 @@ public class LdapTemplateOdmGroupManipulationITest extends AbstractLdapTemplateI assertThat(members.contains(LdapUtils.newLdapName("cn=Some Person,ou=company1,ou=Sweden," + base))).isTrue(); assertThat(members.contains(LdapUtils.newLdapName("cn=Some Person2,ou=company1,ou=Sweden," + base))).isTrue(); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmWithDnAnnotationsITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmWithDnAnnotationsITest.java index 4a30e4e7..ac013b84 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmWithDnAnnotationsITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmWithDnAnnotationsITest.java @@ -34,15 +34,16 @@ import org.springframework.test.context.ContextConfiguration; /** * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateOdmWithDnAnnotationsITest extends AbstractLdapTemplateIntegrationTest { + @Autowired private LdapTemplate tested; @Test public void testFindOne() { - PersonWithDnAnnotations person = tested.findOne(query() - .where("cn").is("Some Person3"), PersonWithDnAnnotations.class); + PersonWithDnAnnotations person = tested.findOne(query().where("cn").is("Some Person3"), + PersonWithDnAnnotations.class); assertThat(person).isNotNull(); assertThat(person.getCommonName()).isEqualTo("Some Person3"); @@ -75,9 +76,8 @@ public class LdapTemplateOdmWithDnAnnotationsITest extends AbstractLdapTemplateI @Test public void testFindInCountry() { - List persons = tested.find(query() - .base("ou=Sweden") - .where("cn").isPresent(), PersonWithDnAnnotations.class); + List persons = tested.find(query().base("ou=Sweden").where("cn").isPresent(), + PersonWithDnAnnotations.class); assertThat(persons).hasSize(4); @@ -91,9 +91,8 @@ public class LdapTemplateOdmWithDnAnnotationsITest extends AbstractLdapTemplateI @Test public void testFindForStreamInCountry() { - List persons = tested.findForStream(query() - .base("ou=Sweden") - .where("cn").isPresent(), PersonWithDnAnnotations.class) + List persons = tested + .findForStream(query().base("ou=Sweden").where("cn").isPresent(), PersonWithDnAnnotations.class) .collect(Collectors.toList()); assertThat(persons).hasSize(4); @@ -108,7 +107,7 @@ public class LdapTemplateOdmWithDnAnnotationsITest extends AbstractLdapTemplateI private PersonWithDnAnnotations findPerson(List persons, String cn) { for (PersonWithDnAnnotations person : persons) { - if(person.getCommonName().equals(cn)) { + if (person.getCommonName().equals(cn)) { return person; } } @@ -150,16 +149,15 @@ public class LdapTemplateOdmWithDnAnnotationsITest extends AbstractLdapTemplateI @Test public void testUpdate() { - PersonWithDnAnnotations person = tested.findOne(query() - .where("cn").is("Some Person3"), PersonWithDnAnnotations.class); + PersonWithDnAnnotations person = tested.findOne(query().where("cn").is("Some Person3"), + PersonWithDnAnnotations.class); person.setDesc(Arrays.asList("New Description")); String entryUuid = person.getEntryUuid(); assertThat(entryUuid).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty(); tested.update(person); - person = tested.findByDn( - LdapUtils.newLdapName("cn=Some Person3, ou=company1, ou=Sweden"), + person = tested.findByDn(LdapUtils.newLdapName("cn=Some Person3, ou=company1, ou=Sweden"), PersonWithDnAnnotations.class); assertThat(person.getCommonName()).isEqualTo("Some Person3"); @@ -171,8 +169,8 @@ public class LdapTemplateOdmWithDnAnnotationsITest extends AbstractLdapTemplateI @Test public void testUpdateWithChangedDn() { - PersonWithDnAnnotations person = tested.findOne(query() - .where("cn").is("Some Person3"), PersonWithDnAnnotations.class); + PersonWithDnAnnotations person = tested.findOne(query().where("cn").is("Some Person3"), + PersonWithDnAnnotations.class); // This should make the entry move person.setCountry("Norway"); @@ -180,8 +178,7 @@ public class LdapTemplateOdmWithDnAnnotationsITest extends AbstractLdapTemplateI assertThat(entryUuid).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty(); tested.update(person); - person = tested.findByDn( - LdapUtils.newLdapName("cn=Some Person3, ou=company1, ou=Norway"), + person = tested.findByDn(LdapUtils.newLdapName("cn=Some Person3, ou=company1, ou=Norway"), PersonWithDnAnnotations.class); assertThat(person.getCommonName()).isEqualTo("Some Person3"); @@ -192,4 +189,5 @@ public class LdapTemplateOdmWithDnAnnotationsITest extends AbstractLdapTemplateI assertThat(person.getEntryUuid()).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty(); assertThat(person.getEntryUuid()).isNotEqualTo(entryUuid); } + } diff --git a/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmWithNoDnAnnotationsITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmWithNoDnAnnotationsITest.java index dac29f0f..01dc5232 100644 --- a/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmWithNoDnAnnotationsITest.java +++ b/test/integration-tests/src/test/java/org/springframework/ldap/itest/odm/LdapTemplateOdmWithNoDnAnnotationsITest.java @@ -37,15 +37,15 @@ import org.springframework.test.context.ContextConfiguration; /** * @author Mattias Hellborg Arthursson */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplateIntegrationTest { + @Autowired private LdapTemplate tested; @Test public void testFindOne() { - Person person = tested.findOne(query() - .where("cn").is("Some Person3"), Person.class); + Person person = tested.findOne(query().where("cn").is("Some Person3"), Person.class); assertThat(person).isNotNull(); assertThat(person.getCommonName()).isEqualTo("Some Person3"); @@ -74,14 +74,12 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat @Test(expected = EmptyResultDataAccessException.class) public void testFindOneThrowsEmptyResultIfNotFound() { - tested.findOne(query() - .where("cn").is("This cn does not exist"), Person.class); + tested.findOne(query().where("cn").is("This cn does not exist"), Person.class); } @Test public void testFind() { - List persons = tested.find(query() - .where("cn").is("Some Person3"), Person.class); + List persons = tested.find(query().where("cn").is("Some Person3"), Person.class); assertThat(persons).hasSize(1); Person person = persons.get(0); @@ -96,8 +94,7 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat @Test public void testFindForStream() { - List persons = tested.findForStream(query() - .where("cn").is("Some Person3"), Person.class) + List persons = tested.findForStream(query().where("cn").is("Some Person3"), Person.class) .collect(Collectors.toList()); assertThat(persons).hasSize(1); @@ -113,9 +110,7 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat @Test public void testFindInCountry() { - List persons = tested.find(query() - .base("ou=Sweden") - .where("cn").isPresent(), Person.class); + List persons = tested.find(query().base("ou=Sweden").where("cn").isPresent(), Person.class); assertThat(persons).hasSize(4); Person person = persons.get(0); @@ -125,9 +120,7 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat @Test public void testFindForStreamInCountry() { - List persons = tested.findForStream(query() - .base("ou=Sweden") - .where("cn").isPresent(), Person.class) + List persons = tested.findForStream(query().base("ou=Sweden").where("cn").isPresent(), Person.class) .collect(Collectors.toList()); assertThat(persons).hasSize(4); @@ -145,8 +138,7 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat @Test public void testCreate() { Person person = new Person(); - person.setDn(LdapNameBuilder.newInstance("ou=company1,ou=Sweden") - .add("cn", "New Person").build()); + person.setDn(LdapNameBuilder.newInstance("ou=company1,ou=Sweden").add("cn", "New Person").build()); person.setCommonName("New Person"); person.setSurname("Person"); person.setDesc(Arrays.asList("This is the description")); @@ -156,8 +148,7 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat assertThat(tested.findAll(Person.class)).hasSize(6); - person = tested.findOne(query() - .where("cn").is("New Person"), Person.class); + person = tested.findOne(query().where("cn").is("New Person"), Person.class); assertThat(person.getCommonName()).isEqualTo("New Person"); assertThat(person.getSurname()).isEqualTo("Person"); @@ -168,16 +159,14 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat @Test public void testUpdate() { - Person person = tested.findOne(query() - .where("cn").is("Some Person3"), Person.class); + Person person = tested.findOne(query().where("cn").is("Some Person3"), Person.class); person.setDesc(Arrays.asList("New Description")); String entryUuid = person.getEntryUuid(); assertThat(entryUuid).describedAs("The operational attribute 'entryUUID' was not set").isNotEmpty(); tested.update(person); - person = tested.findOne(query() - .where("cn").is("Some Person3"), Person.class); + person = tested.findOne(query().where("cn").is("Some Person3"), Person.class); assertThat(person.getCommonName()).isEqualTo("Some Person3"); assertThat(person.getSurname()).isEqualTo("Person3"); @@ -188,15 +177,15 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat @Test public void testDelete() { - Person person = tested.findOne(query() - .where("cn").is("Some Person3"), Person.class); + Person person = tested.findOne(query().where("cn").is("Some Person3"), Person.class); tested.delete(person); try { tested.findOne(query().where("cn").is("Some Person3"), Person.class); fail("EmptyResultDataAccessException e"); - } catch (EmptyResultDataAccessException e) { + } + catch (EmptyResultDataAccessException e) { assertThat(true).isTrue(); } } @@ -206,15 +195,14 @@ public class LdapTemplateOdmWithNoDnAnnotationsITest extends AbstractLdapTemplat */ @Test public void testLdap271() { - Person person = tested.findOne(query() - .where("cn").is("Some Person3"), Person.class); + Person person = tested.findOne(query().where("cn").is("Some Person3"), Person.class); // Perform test person.setTelephoneNumber(null); tested.update(person); - person = tested.findOne(query() - .where("cn").is("Some Person3"), Person.class); + person = tested.findOne(query().where("cn").is("Some Person3"), Person.class); assertThat(person.getTelephoneNumber()).as("TelephoneNumber should be null").isNull(); } + }