diff --git a/core/src/itest-openldap/java/org/springframework/ldap/LdapTemplateLookupOpenLdapITest.java b/core/src/itest-openldap/java/org/springframework/ldap/LdapTemplateLookupOpenLdapITest.java index e490a7fa..508d6dd4 100644 --- a/core/src/itest-openldap/java/org/springframework/ldap/LdapTemplateLookupOpenLdapITest.java +++ b/core/src/itest-openldap/java/org/springframework/ldap/LdapTemplateLookupOpenLdapITest.java @@ -1,220 +1,220 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -import javax.naming.NamingException; -import javax.naming.directory.Attributes; - -import org.springframework.ldap.core.AttributesMapper; -import org.springframework.ldap.core.ContextMapper; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.test.AbstractDependencyInjectionSpringContextTests; - -/** - * Tests the lookup methods of LdapTemplate on OpenLdap. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public class LdapTemplateLookupOpenLdapITest extends - AbstractDependencyInjectionSpringContextTests { - - private LdapTemplate tested; - - protected String[] getConfigLocations() { - return new String[] { "/conf/ldapTemplateTestContext-openldap.xml" }; - } - - /** - * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. - */ - public void testLookup_Plain() { - DirContextAdapter result = (DirContextAdapter) tested - .lookup("cn=Some Person2, ou=company1,c=Sweden"); - - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); - assertEquals("Sweden, Company1, Some Person2", result - .getStringAttribute("description")); - } - - public void testLookup_AttributesMapper() { - AttributesMapper mapper = new PersonAttributesMapper(); - Person person = (Person) tested.lookup( - "cn=Some Person2, ou=company1,c=Sweden", mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).isEqualTo("Person2"); - assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); - } - - public void testLookup_AttributesMapper_DistinguishedName() { - AttributesMapper mapper = new PersonAttributesMapper(); - Person person = (Person) tested.lookup(new DistinguishedName( - "cn=Some Person2, ou=company1,c=Sweden"), mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).isEqualTo("Person2"); - assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); - } - - /** - * 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. - * - * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes) - */ - public Object mapFromAttributes(Attributes attributes) - throws NamingException { - Person person = new Person(); - person.setFullname((String) attributes.get("cn").get()); - assertThat(attributes.get("sn")).as("sn should be null").isNull(); - assertNull("description should be null", attributes - .get("description")); - return person; - } - } - - /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. - */ - public void testLookup_ReturnAttributes_AttributesMapper() { - AttributesMapper mapper = new SubsetPersonAttributesMapper(); - - Person person = (Person) tested.lookup( - "cn=Some Person2, ou=company1,c=Sweden", new String[] { "cn" }, - mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).as("lastName should not be set").isNull(); - assertThat(person.getDescription()).as("description should not be set").isNull(); - } - - /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. Uses DistinguishedName instead - * of plain string as name. - */ - public void testLookup_ReturnAttributes_AttributesMapper_DistinguishedName() { - AttributesMapper mapper = new SubsetPersonAttributesMapper(); - Person person = (Person) tested.lookup(new DistinguishedName( - "cn=Some Person2, ou=company1,c=Sweden"), - new String[] { "cn" }, mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).as("lastName should not be set").isNull(); - assertThat(person.getDescription()).as("description should not be set").isNull(); - } - - /** - * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. - */ - public void testLookup_ContextMapper() { - ContextMapper mapper = new PersonContextMapper(); - Person person = (Person) tested.lookup( - "cn=Some Person2, ou=company1,c=Sweden", mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).isEqualTo("Person2"); - assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); - } - - /** - * Verifies that only the subset is used when specifying a subset of the - * available attributes as return attributes. - */ - public void testLookup_ReturnAttributes_ContextMapper() { - ContextMapper mapper = new PersonContextMapper(); - - Person person = (Person) tested.lookup( - "cn=Some Person2, ou=company1,c=Sweden", new String[] { "cn" }, - mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).as("lastName should not be set").isNull(); - assertThat(person.getDescription()).as("description should not be set").isNull(); - } - - /** - * 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. - */ - public void testLookup_MultiValuedRdn() { - AttributesMapper mapper = new PersonAttributesMapper(); - Person person = (Person) tested.lookup( - "cn=Some Person+sn=Person, ou=company1,c=Norway", mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person"); - assertThat(person.getLastname()).isEqualTo("Person"); - assertEquals("Norway, Company1, Some Person+Person", person - .getDescription()); - } - - /** - * 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. - */ - public void testLookup_MultiValuedRdn_DirContextAdapter() { - DirContextAdapter result = (DirContextAdapter) tested - .lookup("cn=Some Person+sn=Person, ou=company1,c=Norway"); - - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person"); - assertEquals("Norway, Company1, Some Person+Person", result - .getStringAttribute("description")); - } - - public void testLookup_GetNameInNamespace_Plain() { - DirContextAdapter result = (DirContextAdapter) tested - .lookup("cn=Some Person2, ou=company1,c=Sweden"); - - assertThat(result.getDn().isEqualTo("cn=Some Person2, ou=company1, c=Sweden") - .toString()); - assertEquals( - "cn=Some Person2, ou=company1, c=Sweden, dc=jayway, dc=se", - result.getNameInNamespace()); - } - - public void testLookup_GetNameInNamespace_MultiRdn() { - DirContextAdapter result = (DirContextAdapter) tested - .lookup("cn=Some Person+sn=Person, ou=company1,c=Norway"); - - assertEquals("cn=Some Person+sn=Person, ou=company1, c=Norway", result - .getDn().toString()); - assertEquals( - "cn=Some Person+sn=Person, ou=company1, c=Norway, dc=jayway, dc=se", - result.getNameInNamespace()); - } - - public void setTested(LdapTemplate tested) { - this.tested = tested; - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +import javax.naming.NamingException; +import javax.naming.directory.Attributes; + +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.ContextMapper; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.test.AbstractDependencyInjectionSpringContextTests; + +/** + * Tests the lookup methods of LdapTemplate on OpenLdap. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public class LdapTemplateLookupOpenLdapITest extends + AbstractDependencyInjectionSpringContextTests { + + private LdapTemplate tested; + + protected String[] getConfigLocations() { + return new String[] { "/conf/ldapTemplateTestContext-openldap.xml" }; + } + + /** + * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) + * being set in the ContextSource. + */ + public void testLookup_Plain() { + DirContextAdapter result = (DirContextAdapter) tested + .lookup("cn=Some Person2, ou=company1,c=Sweden"); + + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); + assertEquals("Sweden, Company1, Some Person2", result + .getStringAttribute("description")); + } + + public void testLookup_AttributesMapper() { + AttributesMapper mapper = new PersonAttributesMapper(); + Person person = (Person) tested.lookup( + "cn=Some Person2, ou=company1,c=Sweden", mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).isEqualTo("Person2"); + assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); + } + + public void testLookup_AttributesMapper_DistinguishedName() { + AttributesMapper mapper = new PersonAttributesMapper(); + Person person = (Person) tested.lookup(new DistinguishedName( + "cn=Some Person2, ou=company1,c=Sweden"), mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).isEqualTo("Person2"); + assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); + } + + /** + * 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. + * + * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes) + */ + public Object mapFromAttributes(Attributes attributes) + throws NamingException { + Person person = new Person(); + person.setFullname((String) attributes.get("cn").get()); + assertThat(attributes.get("sn")).as("sn should be null").isNull(); + assertNull("description should be null", attributes + .get("description")); + return person; + } + } + + /** + * Verifies that only the subset is used when specifying a subset of the + * available attributes as return attributes. + */ + public void testLookup_ReturnAttributes_AttributesMapper() { + AttributesMapper mapper = new SubsetPersonAttributesMapper(); + + Person person = (Person) tested.lookup( + "cn=Some Person2, ou=company1,c=Sweden", new String[] { "cn" }, + mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).as("lastName should not be set").isNull(); + assertThat(person.getDescription()).as("description should not be set").isNull(); + } + + /** + * Verifies that only the subset is used when specifying a subset of the + * available attributes as return attributes. Uses DistinguishedName instead + * of plain string as name. + */ + public void testLookup_ReturnAttributes_AttributesMapper_DistinguishedName() { + AttributesMapper mapper = new SubsetPersonAttributesMapper(); + Person person = (Person) tested.lookup(new DistinguishedName( + "cn=Some Person2, ou=company1,c=Sweden"), + new String[] { "cn" }, mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).as("lastName should not be set").isNull(); + assertThat(person.getDescription()).as("description should not be set").isNull(); + } + + /** + * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) + * being set in the ContextSource. + */ + public void testLookup_ContextMapper() { + ContextMapper mapper = new PersonContextMapper(); + Person person = (Person) tested.lookup( + "cn=Some Person2, ou=company1,c=Sweden", mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).isEqualTo("Person2"); + assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); + } + + /** + * Verifies that only the subset is used when specifying a subset of the + * available attributes as return attributes. + */ + public void testLookup_ReturnAttributes_ContextMapper() { + ContextMapper mapper = new PersonContextMapper(); + + Person person = (Person) tested.lookup( + "cn=Some Person2, ou=company1,c=Sweden", new String[] { "cn" }, + mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).as("lastName should not be set").isNull(); + assertThat(person.getDescription()).as("description should not be set").isNull(); + } + + /** + * 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. + */ + public void testLookup_MultiValuedRdn() { + AttributesMapper mapper = new PersonAttributesMapper(); + Person person = (Person) tested.lookup( + "cn=Some Person+sn=Person, ou=company1,c=Norway", mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person"); + assertThat(person.getLastname()).isEqualTo("Person"); + assertEquals("Norway, Company1, Some Person+Person", person + .getDescription()); + } + + /** + * 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. + */ + public void testLookup_MultiValuedRdn_DirContextAdapter() { + DirContextAdapter result = (DirContextAdapter) tested + .lookup("cn=Some Person+sn=Person, ou=company1,c=Norway"); + + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person"); + assertEquals("Norway, Company1, Some Person+Person", result + .getStringAttribute("description")); + } + + public void testLookup_GetNameInNamespace_Plain() { + DirContextAdapter result = (DirContextAdapter) tested + .lookup("cn=Some Person2, ou=company1,c=Sweden"); + + assertThat(result.getDn().isEqualTo("cn=Some Person2, ou=company1, c=Sweden") + .toString()); + assertEquals( + "cn=Some Person2, ou=company1, c=Sweden, dc=jayway, dc=se", + result.getNameInNamespace()); + } + + public void testLookup_GetNameInNamespace_MultiRdn() { + DirContextAdapter result = (DirContextAdapter) tested + .lookup("cn=Some Person+sn=Person, ou=company1,c=Norway"); + + assertEquals("cn=Some Person+sn=Person, ou=company1, c=Norway", result + .getDn().toString()); + assertEquals( + "cn=Some Person+sn=Person, ou=company1, c=Norway, dc=jayway, dc=se", + result.getNameInNamespace()); + } + + public void setTested(LdapTemplate tested) { + this.tested = tested; + } +} diff --git a/core/src/itest-openldap/java/org/springframework/ldap/control/LdapTemplatePagedSearchITest.java b/core/src/itest-openldap/java/org/springframework/ldap/control/LdapTemplatePagedSearchITest.java index dcc9b05e..3d152fa2 100644 --- a/core/src/itest-openldap/java/org/springframework/ldap/control/LdapTemplatePagedSearchITest.java +++ b/core/src/itest-openldap/java/org/springframework/ldap/control/LdapTemplatePagedSearchITest.java @@ -1,157 +1,157 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.control; - -import java.util.List; - -import javax.naming.Name; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.directory.SearchControls; - -import org.springframework.ldap.Person; -import org.springframework.ldap.PersonAttributesMapper; -import org.springframework.ldap.core.AttributesMapperCallbackHandler; -import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.SearchExecutor; -import org.springframework.test.AbstractDependencyInjectionSpringContextTests; - -/** - * Tests the paged search result capability of LdapTemplate. - *

- * Note: Currently, ApacheDS does not support paged results controls, so this - * test must be run under another directory server, for example OpenLdap. This - * test will not run under ApacheDS, and the other integration tests assume - * ApacheDS and will probably not run under OpenLdap. - * - * @author Ulrik Sandberg - */ -public class LdapTemplatePagedSearchITest extends - AbstractDependencyInjectionSpringContextTests { - - private static final Name BASE = DistinguishedName.EMPTY_PATH; - - private static final String FILTER_STRING = "(&(objectclass=person))"; - - private LdapTemplate tested; - - private CollectingNameClassPairCallbackHandler callbackHandler; - - private SearchControls searchControls; - - protected String[] getConfigLocations() { - return new String[] { "/conf/ldapTemplateTestContext-openldap.xml" }; - } - - protected void onSetUp() throws Exception { - super.onSetUp(); - PersonAttributesMapper mapper = new PersonAttributesMapper(); - callbackHandler = new AttributesMapperCallbackHandler(mapper); - searchControls = new SearchControls(); - searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); - } - - protected void onTearDown() throws Exception { - super.onTearDown(); - callbackHandler = null; - tested = null; - searchControls = null; - } - - public void testSearch_PagedResult() { - SearchExecutor searchExecutor = new SearchExecutor() { - public NamingEnumeration executeSearch(DirContext ctx) - throws NamingException { - return ctx.search(BASE, FILTER_STRING, searchControls); - } - }; - Person person; - List list; - PagedResultsCookie cookie; - PagedResultsRequestControl requestControl; - - // Prepare for first search - requestControl = new PagedResultsRequestControl(3); - tested.search(searchExecutor, callbackHandler, requestControl); - cookie = requestControl.getCookie(); - assertThat(cookie.getCookie()).as("Cookie should not be null yet").isNotNull(); - list = callbackHandler.getList(); - assertThat(list).hasSize(3); - person = (Person) list.get(0); - assertThat(person.getFullname()).isEqualTo("Some Person"); - assertThat(person.getPhone()).isEqualTo("+46 555-123456"); - person = (Person) list.get(1); - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getPhone()).isEqualTo("+46 555-654321"); - person = (Person) list.get(2); - assertThat(person.getFullname()).isEqualTo("Some Person3"); - assertThat(person.getPhone()).isEqualTo("+46 555-123654"); - - // Prepare for second and last search - requestControl = new PagedResultsRequestControl(3, cookie); - tested.search(searchExecutor, callbackHandler, requestControl); - cookie = requestControl.getCookie(); - assertThat(cookie.getCookie()).as("Cookie should be null now").isNull(); - assertThat(list).hasSize(5); - person = (Person) list.get(3); - assertThat(person.getFullname()).isEqualTo("Some Person"); - assertThat(person.getPhone()).isEqualTo("+46 555-456321"); - person = (Person) list.get(4); - assertThat(person.getFullname()).isEqualTo("Some Person"); - assertThat(person.getPhone()).isEqualTo("+45 555-654123"); - } - - public void testSearch_PagedResult_ConvenienceMethod() { - Person person; - List list; - PagedResultsCookie cookie; - PagedResultsRequestControl requestControl; - - // Prepare for first search - requestControl = new PagedResultsRequestControl(3); - tested.search(BASE, FILTER_STRING, searchControls, - callbackHandler, requestControl); - cookie = requestControl.getCookie(); - assertThat(cookie.getCookie()).as("Cookie should not be null yet").isNotNull(); - list = callbackHandler.getList(); - assertThat(list).hasSize(3); - person = (Person) list.get(0); - assertThat(person.getFullname()).isEqualTo("Some Person"); - person = (Person) list.get(1); - assertThat(person.getFullname()).isEqualTo("Some Person2"); - person = (Person) list.get(2); - assertThat(person.getFullname()).isEqualTo("Some Person3"); - - // Prepare for second and last search - requestControl = new PagedResultsRequestControl(3, cookie); - tested.search(BASE, FILTER_STRING, searchControls, - callbackHandler, requestControl); - cookie = requestControl.getCookie(); - assertThat(cookie.getCookie()).as("Cookie should be null now").isNull(); - assertThat(list).hasSize(5); - person = (Person) list.get(3); - assertThat(person.getFullname()).isEqualTo("Some Person"); - person = (Person) list.get(4); - assertThat(person.getFullname()).isEqualTo("Some Person"); - } - - public void setTested(LdapTemplate tested) { - this.tested = tested; - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.control; + +import java.util.List; + +import javax.naming.Name; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.directory.SearchControls; + +import org.springframework.ldap.Person; +import org.springframework.ldap.PersonAttributesMapper; +import org.springframework.ldap.core.AttributesMapperCallbackHandler; +import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.SearchExecutor; +import org.springframework.test.AbstractDependencyInjectionSpringContextTests; + +/** + * Tests the paged search result capability of LdapTemplate. + *

+ * Note: Currently, ApacheDS does not support paged results controls, so this + * test must be run under another directory server, for example OpenLdap. This + * test will not run under ApacheDS, and the other integration tests assume + * ApacheDS and will probably not run under OpenLdap. + * + * @author Ulrik Sandberg + */ +public class LdapTemplatePagedSearchITest extends + AbstractDependencyInjectionSpringContextTests { + + private static final Name BASE = DistinguishedName.EMPTY_PATH; + + private static final String FILTER_STRING = "(&(objectclass=person))"; + + private LdapTemplate tested; + + private CollectingNameClassPairCallbackHandler callbackHandler; + + private SearchControls searchControls; + + protected String[] getConfigLocations() { + return new String[] { "/conf/ldapTemplateTestContext-openldap.xml" }; + } + + protected void onSetUp() throws Exception { + super.onSetUp(); + PersonAttributesMapper mapper = new PersonAttributesMapper(); + callbackHandler = new AttributesMapperCallbackHandler(mapper); + searchControls = new SearchControls(); + searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); + } + + protected void onTearDown() throws Exception { + super.onTearDown(); + callbackHandler = null; + tested = null; + searchControls = null; + } + + public void testSearch_PagedResult() { + SearchExecutor searchExecutor = new SearchExecutor() { + public NamingEnumeration executeSearch(DirContext ctx) + throws NamingException { + return ctx.search(BASE, FILTER_STRING, searchControls); + } + }; + Person person; + List list; + PagedResultsCookie cookie; + PagedResultsRequestControl requestControl; + + // Prepare for first search + requestControl = new PagedResultsRequestControl(3); + tested.search(searchExecutor, callbackHandler, requestControl); + cookie = requestControl.getCookie(); + assertThat(cookie.getCookie()).as("Cookie should not be null yet").isNotNull(); + list = callbackHandler.getList(); + assertThat(list).hasSize(3); + person = (Person) list.get(0); + assertThat(person.getFullname()).isEqualTo("Some Person"); + assertThat(person.getPhone()).isEqualTo("+46 555-123456"); + person = (Person) list.get(1); + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getPhone()).isEqualTo("+46 555-654321"); + person = (Person) list.get(2); + assertThat(person.getFullname()).isEqualTo("Some Person3"); + assertThat(person.getPhone()).isEqualTo("+46 555-123654"); + + // Prepare for second and last search + requestControl = new PagedResultsRequestControl(3, cookie); + tested.search(searchExecutor, callbackHandler, requestControl); + cookie = requestControl.getCookie(); + assertThat(cookie.getCookie()).as("Cookie should be null now").isNull(); + assertThat(list).hasSize(5); + person = (Person) list.get(3); + assertThat(person.getFullname()).isEqualTo("Some Person"); + assertThat(person.getPhone()).isEqualTo("+46 555-456321"); + person = (Person) list.get(4); + assertThat(person.getFullname()).isEqualTo("Some Person"); + assertThat(person.getPhone()).isEqualTo("+45 555-654123"); + } + + public void testSearch_PagedResult_ConvenienceMethod() { + Person person; + List list; + PagedResultsCookie cookie; + PagedResultsRequestControl requestControl; + + // Prepare for first search + requestControl = new PagedResultsRequestControl(3); + tested.search(BASE, FILTER_STRING, searchControls, + callbackHandler, requestControl); + cookie = requestControl.getCookie(); + assertThat(cookie.getCookie()).as("Cookie should not be null yet").isNotNull(); + list = callbackHandler.getList(); + assertThat(list).hasSize(3); + person = (Person) list.get(0); + assertThat(person.getFullname()).isEqualTo("Some Person"); + person = (Person) list.get(1); + assertThat(person.getFullname()).isEqualTo("Some Person2"); + person = (Person) list.get(2); + assertThat(person.getFullname()).isEqualTo("Some Person3"); + + // Prepare for second and last search + requestControl = new PagedResultsRequestControl(3, cookie); + tested.search(BASE, FILTER_STRING, searchControls, + callbackHandler, requestControl); + cookie = requestControl.getCookie(); + assertThat(cookie.getCookie()).as("Cookie should be null now").isNull(); + assertThat(list).hasSize(5); + person = (Person) list.get(3); + assertThat(person.getFullname()).isEqualTo("Some Person"); + person = (Person) list.get(4); + assertThat(person.getFullname()).isEqualTo("Some Person"); + } + + public void setTested(LdapTemplate tested) { + this.tested = tested; + } +} diff --git a/core/src/itest-openldap/java/org/springframework/ldap/control/LdapTemplateSortedSearchITest.java b/core/src/itest-openldap/java/org/springframework/ldap/control/LdapTemplateSortedSearchITest.java index c90b87a7..d84680b4 100644 --- a/core/src/itest-openldap/java/org/springframework/ldap/control/LdapTemplateSortedSearchITest.java +++ b/core/src/itest-openldap/java/org/springframework/ldap/control/LdapTemplateSortedSearchITest.java @@ -1,143 +1,143 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.control; - -import java.util.List; - -import javax.naming.Name; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.SearchControls; - -import org.springframework.ldap.Person; -import org.springframework.ldap.core.AttributesMapper; -import org.springframework.ldap.core.AttributesMapperCallbackHandler; -import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.SearchExecutor; -import org.springframework.test.AbstractDependencyInjectionSpringContextTests; - -/** - * Tests the still experimental sorted search result capability of LdapTemplate. - * - * @author Ulrik Sandberg - */ -public class LdapTemplateSortedSearchITest extends - AbstractDependencyInjectionSpringContextTests { - - private static final Name BASE = DistinguishedName.EMPTY_PATH; - - private static final String FILTER_STRING = "(&(objectclass=ikeaperson)(cn=gor*))"; - - private LdapTemplate tested; - - private CollectingNameClassPairCallbackHandler callbackHandler; - - private SearchControls searchControls; - - protected String[] getConfigLocations() { - return new String[] { "/conf/ldapTemplateTestContext-openldap.xml" }; - } - - protected void onSetUp() throws Exception { - super.onSetUp(); - PersonAttributesMapper mapper = new PersonAttributesMapper(); - callbackHandler = new AttributesMapperCallbackHandler(mapper); - searchControls = new SearchControls(); - searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); - } - - protected void onTearDown() throws Exception { - super.onTearDown(); - callbackHandler = null; - tested = null; - searchControls = null; - } - - public void testSearch_SortControl() { - SearchExecutor searchExecutor = new SearchExecutor() { - public NamingEnumeration executeSearch(DirContext ctx) - throws NamingException { - return ctx.search(BASE, FILTER_STRING, searchControls); - } - }; - SortControlDirContextProcessor requestControl; - - // Prepare for first search - requestControl = new SortControlDirContextProcessor("cn"); - tested.search(searchExecutor, callbackHandler, requestControl); - int resultCode = requestControl.getResultCode(); - boolean sorted = requestControl.isSorted(); - assertThat("Search result should have been sorted: " + resultCode, sorted).isTrue(); - List list = callbackHandler.getList(); - assertSortedList(list); - } - - public void testSearch_SortControl_ConvenienceMethod() { - SortControlDirContextProcessor requestControl; - - // Prepare for first search - requestControl = new SortControlDirContextProcessor("cn"); - tested.search(BASE, FILTER_STRING, searchControls, callbackHandler, - requestControl); - int resultCode = requestControl.getResultCode(); - boolean sorted = requestControl.isSorted(); - assertThat("Search result should have been sorted: " + resultCode, sorted).isTrue(); - List list = callbackHandler.getList(); - assertSortedList(list); - } - - private void assertSortedList(List list) { - Person person; - assertThat(list).hasSize(6); - person = (Person) list.get(0); - assertThat(person.getFullname()).isEqualTo("Goran Milenkovic"); - person = (Person) list.get(1); - assertThat(person.getFullname()).isEqualTo("Goran Sundberg"); - person = (Person) list.get(2); - assertThat(person.getFullname()).isEqualTo("Goran Westerberg"); - person = (Person) list.get(3); - assertThat(person.getFullname()).isEqualTo("Gorana Milicevic"); - person = (Person) list.get(4); - assertThat(person.getFullname()).isEqualTo("Gordana Canic"); - person = (Person) list.get(5); - assertThat(person.getFullname()).isEqualTo("Gordana Russ"); - } - - public void setTested(LdapTemplate tested) { - this.tested = tested; - } - - private 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 Object mapFromAttributes(Attributes attributes) - throws NamingException { - Person person = new Person(); - person.setFullname((String) attributes.get("cn").get()); - person.setLastname((String) attributes.get("sn").get()); - person.setDescription((String) attributes.get("givenName").get()); - return person; - } - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.control; + +import java.util.List; + +import javax.naming.Name; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.SearchControls; + +import org.springframework.ldap.Person; +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.AttributesMapperCallbackHandler; +import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.SearchExecutor; +import org.springframework.test.AbstractDependencyInjectionSpringContextTests; + +/** + * Tests the still experimental sorted search result capability of LdapTemplate. + * + * @author Ulrik Sandberg + */ +public class LdapTemplateSortedSearchITest extends + AbstractDependencyInjectionSpringContextTests { + + private static final Name BASE = DistinguishedName.EMPTY_PATH; + + private static final String FILTER_STRING = "(&(objectclass=ikeaperson)(cn=gor*))"; + + private LdapTemplate tested; + + private CollectingNameClassPairCallbackHandler callbackHandler; + + private SearchControls searchControls; + + protected String[] getConfigLocations() { + return new String[] { "/conf/ldapTemplateTestContext-openldap.xml" }; + } + + protected void onSetUp() throws Exception { + super.onSetUp(); + PersonAttributesMapper mapper = new PersonAttributesMapper(); + callbackHandler = new AttributesMapperCallbackHandler(mapper); + searchControls = new SearchControls(); + searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); + } + + protected void onTearDown() throws Exception { + super.onTearDown(); + callbackHandler = null; + tested = null; + searchControls = null; + } + + public void testSearch_SortControl() { + SearchExecutor searchExecutor = new SearchExecutor() { + public NamingEnumeration executeSearch(DirContext ctx) + throws NamingException { + return ctx.search(BASE, FILTER_STRING, searchControls); + } + }; + SortControlDirContextProcessor requestControl; + + // Prepare for first search + requestControl = new SortControlDirContextProcessor("cn"); + tested.search(searchExecutor, callbackHandler, requestControl); + int resultCode = requestControl.getResultCode(); + boolean sorted = requestControl.isSorted(); + assertThat("Search result should have been sorted: " + resultCode, sorted).isTrue(); + List list = callbackHandler.getList(); + assertSortedList(list); + } + + public void testSearch_SortControl_ConvenienceMethod() { + SortControlDirContextProcessor requestControl; + + // Prepare for first search + requestControl = new SortControlDirContextProcessor("cn"); + tested.search(BASE, FILTER_STRING, searchControls, callbackHandler, + requestControl); + int resultCode = requestControl.getResultCode(); + boolean sorted = requestControl.isSorted(); + assertThat("Search result should have been sorted: " + resultCode, sorted).isTrue(); + List list = callbackHandler.getList(); + assertSortedList(list); + } + + private void assertSortedList(List list) { + Person person; + assertThat(list).hasSize(6); + person = (Person) list.get(0); + assertThat(person.getFullname()).isEqualTo("Goran Milenkovic"); + person = (Person) list.get(1); + assertThat(person.getFullname()).isEqualTo("Goran Sundberg"); + person = (Person) list.get(2); + assertThat(person.getFullname()).isEqualTo("Goran Westerberg"); + person = (Person) list.get(3); + assertThat(person.getFullname()).isEqualTo("Gorana Milicevic"); + person = (Person) list.get(4); + assertThat(person.getFullname()).isEqualTo("Gordana Canic"); + person = (Person) list.get(5); + assertThat(person.getFullname()).isEqualTo("Gordana Russ"); + } + + public void setTested(LdapTemplate tested) { + this.tested = tested; + } + + private 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 Object mapFromAttributes(Attributes attributes) + throws NamingException { + Person person = new Person(); + person.setFullname((String) attributes.get("cn").get()); + person.setLastname((String) attributes.get("sn").get()); + person.setDescription((String) attributes.get("givenName").get()); + return person; + } + } +} diff --git a/core/src/main/java/org/springframework/ldap/AttributeInUseException.java b/core/src/main/java/org/springframework/ldap/AttributeInUseException.java index 62929877..418f1d0f 100644 --- a/core/src/main/java/org/springframework/ldap/AttributeInUseException.java +++ b/core/src/main/java/org/springframework/ldap/AttributeInUseException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 65b3b18b..3b74aaf2 100644 --- a/core/src/main/java/org/springframework/ldap/AttributeModificationException.java +++ b/core/src/main/java/org/springframework/ldap/AttributeModificationException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 0f0c392d..456120e8 100644 --- a/core/src/main/java/org/springframework/ldap/AuthenticationException.java +++ b/core/src/main/java/org/springframework/ldap/AuthenticationException.java @@ -1,35 +1,35 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI AuthenticationException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.AuthenticationException - */ -public class AuthenticationException extends NamingSecurityException { - - public AuthenticationException(javax.naming.AuthenticationException cause) { - super(cause); - } - - public AuthenticationException() { - this(null); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI AuthenticationException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.AuthenticationException + */ +public class AuthenticationException extends NamingSecurityException { + + public AuthenticationException(javax.naming.AuthenticationException cause) { + super(cause); + } + + 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 7e47a35c..839acbc6 100644 --- a/core/src/main/java/org/springframework/ldap/AuthenticationNotSupportedException.java +++ b/core/src/main/java/org/springframework/ldap/AuthenticationNotSupportedException.java @@ -1,33 +1,33 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI AuthenticationNotSupportedException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.AuthenticationNotSupportedException - */ -public class AuthenticationNotSupportedException extends - NamingSecurityException { - - public AuthenticationNotSupportedException( - javax.naming.AuthenticationNotSupportedException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI AuthenticationNotSupportedException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.AuthenticationNotSupportedException + */ +public class AuthenticationNotSupportedException extends + NamingSecurityException { + + 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 2128039c..acbe79ce 100644 --- a/core/src/main/java/org/springframework/ldap/BadLdapGrammarException.java +++ b/core/src/main/java/org/springframework/ldap/BadLdapGrammarException.java @@ -1,36 +1,36 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * 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 { - - private static final long serialVersionUID = 961612585331409470L; - - public BadLdapGrammarException(String message) { - super(message); - } - - public BadLdapGrammarException(String message, Throwable cause) { - super(message, cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * 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 { + + private static final long serialVersionUID = 961612585331409470L; + + public BadLdapGrammarException(String message) { + super(message); + } + + 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 17e6561e..68c04a15 100644 --- a/core/src/main/java/org/springframework/ldap/CannotProceedException.java +++ b/core/src/main/java/org/springframework/ldap/CannotProceedException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI CannotProceedException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.CannotProceedException - */ -public class CannotProceedException extends NamingException { - - public CannotProceedException(javax.naming.CannotProceedException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI CannotProceedException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.CannotProceedException + */ +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 f85e8779..ee1348d3 100644 --- a/core/src/main/java/org/springframework/ldap/CommunicationException.java +++ b/core/src/main/java/org/springframework/ldap/CommunicationException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI CommunicationException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.CommunicationException - */ -public class CommunicationException extends NamingException { - - public CommunicationException(javax.naming.CommunicationException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI CommunicationException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.CommunicationException + */ +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 e561d6cd..8fb33bd1 100644 --- a/core/src/main/java/org/springframework/ldap/ConfigurationException.java +++ b/core/src/main/java/org/springframework/ldap/ConfigurationException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI ConfigurationException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.ConfigurationException - */ -public class ConfigurationException extends NamingException { - - public ConfigurationException(javax.naming.ConfigurationException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI ConfigurationException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.ConfigurationException + */ +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 e3d60a68..5fddd0b5 100644 --- a/core/src/main/java/org/springframework/ldap/ContextNotEmptyException.java +++ b/core/src/main/java/org/springframework/ldap/ContextNotEmptyException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI ContextNotEmptyException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.ContextNotEmptyException - */ -public class ContextNotEmptyException extends NamingException { - - public ContextNotEmptyException(javax.naming.ContextNotEmptyException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI ContextNotEmptyException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.ContextNotEmptyException + */ +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 8a5a4f55..656f1325 100644 --- a/core/src/main/java/org/springframework/ldap/InsufficientResourcesException.java +++ b/core/src/main/java/org/springframework/ldap/InsufficientResourcesException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 6d579382..dc3a0d51 100644 --- a/core/src/main/java/org/springframework/ldap/InterruptedNamingException.java +++ b/core/src/main/java/org/springframework/ldap/InterruptedNamingException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 ad489e18..927d438e 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidAttributeIdentifierException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidAttributeIdentifierException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 8483b42b..fe6c1f99 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidAttributeValueException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidAttributeValueException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 9f2dd12d..92a120cd 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidAttributesException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidAttributesException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 71e4c93f..48dfb57b 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidNameException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidNameException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI InvalidNameException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.InvalidNameException - */ -public class InvalidNameException extends NamingException { - - public InvalidNameException(javax.naming.InvalidNameException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI InvalidNameException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.InvalidNameException + */ +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 8e554f39..0cb3c206 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidSearchControlsException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidSearchControlsException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 89b3077a..71da99ec 100644 --- a/core/src/main/java/org/springframework/ldap/InvalidSearchFilterException.java +++ b/core/src/main/java/org/springframework/ldap/InvalidSearchFilterException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 ee675a4f..2bd876d1 100644 --- a/core/src/main/java/org/springframework/ldap/LdapReferralException.java +++ b/core/src/main/java/org/springframework/ldap/LdapReferralException.java @@ -1,35 +1,35 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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 - * {@link javax.naming.ldap.LdapReferralException}. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.ldap.LdapReferralException - */ -public class LdapReferralException extends ReferralException { - - public LdapReferralException(javax.naming.ldap.LdapReferralException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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 + * {@link javax.naming.ldap.LdapReferralException}. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.ldap.LdapReferralException + */ +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 22d5c3f2..6e16646d 100644 --- a/core/src/main/java/org/springframework/ldap/LimitExceededException.java +++ b/core/src/main/java/org/springframework/ldap/LimitExceededException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI LimitExceededException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.LimitExceededException - */ -public class LimitExceededException extends NamingException { - - public LimitExceededException(javax.naming.LimitExceededException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI LimitExceededException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.LimitExceededException + */ +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 a58747d9..b8a19d0d 100644 --- a/core/src/main/java/org/springframework/ldap/LinkException.java +++ b/core/src/main/java/org/springframework/ldap/LinkException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI LinkException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.LinkException - */ -public class LinkException extends NamingException { - - public LinkException(javax.naming.LinkException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI LinkException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.LinkException + */ +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 14426d11..76ea09a3 100644 --- a/core/src/main/java/org/springframework/ldap/LinkLoopException.java +++ b/core/src/main/java/org/springframework/ldap/LinkLoopException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI LinkLoopException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.LinkLoopException - */ -public class LinkLoopException extends LinkException { - - public LinkLoopException(javax.naming.LinkLoopException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI LinkLoopException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.LinkLoopException + */ +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 7a0e6dcd..a0d5e427 100644 --- a/core/src/main/java/org/springframework/ldap/MalformedLinkException.java +++ b/core/src/main/java/org/springframework/ldap/MalformedLinkException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI MalformedLinkException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.MalformedLinkException - */ -public class MalformedLinkException extends LinkException { - - public MalformedLinkException(javax.naming.MalformedLinkException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI MalformedLinkException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.MalformedLinkException + */ +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 35c93431..ffd7cc0d 100644 --- a/core/src/main/java/org/springframework/ldap/NameAlreadyBoundException.java +++ b/core/src/main/java/org/springframework/ldap/NameAlreadyBoundException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 e56bb97d..78516293 100644 --- a/core/src/main/java/org/springframework/ldap/NameNotFoundException.java +++ b/core/src/main/java/org/springframework/ldap/NameNotFoundException.java @@ -1,35 +1,35 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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); - } - - public NameNotFoundException(javax.naming.NameNotFoundException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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); + } + + 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 b76b2e0a..785dff19 100644 --- a/core/src/main/java/org/springframework/ldap/NamingException.java +++ b/core/src/main/java/org/springframework/ldap/NamingException.java @@ -1,186 +1,186 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.io.Serializable; - -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. - * - * @author Ulrik Sandberg - * @since 1.2 - */ -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. - */ - public Throwable getCause() { - // Even if you cannot set the cause of this exception other than through - // the constructor, we check for the cause being "this" here, as the cause - // could still be set to "this" via reflection: for example, by a remoting - // deserializer like Hessian's. - return (this.cause == this ? null : this.cause); - } - - /** - * Constructor that takes a message. - * - * @param msg - * the detail message - */ - public NamingException(String msg) { - super(msg); - } - - /** - * 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}. - */ - public NamingException(String msg, Throwable cause) { - super(msg); - this.cause = cause; - } - - /** - * 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 - */ - public String getExplanation() { - if (getCause() instanceof javax.naming.NamingException) { - return ((javax.naming.NamingException) getCause()).getExplanation(); - } - return null; - } - - /** - * 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 - */ - public Name getRemainingName() { - if (getCause() instanceof javax.naming.NamingException) { - 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 - * {@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 - */ - public Name getResolvedName() { - if (getCause() instanceof javax.naming.NamingException) { - 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 - */ - public Object getResolvedObj() { - if (getCause() instanceof javax.naming.NamingException) { - return ((javax.naming.NamingException) getCause()).getResolvedObj(); - } - return null; - } - - /** - * 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(); - boolean serializable = resolvedObj instanceof Serializable; - if (resolvedObj != null && !serializable) { - // the cause is of this type, since resolvedObj is not null - javax.naming.NamingException namingException = (javax.naming.NamingException) getCause(); - namingException.setResolvedObj(null); - try { - stream.defaultWriteObject(); - } finally { - namingException.setResolvedObj(resolvedObj); - } - } else { - stream.defaultWriteObject(); - } - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +import java.io.IOException; +import java.io.ObjectOutputStream; +import java.io.Serializable; + +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. + * + * @author Ulrik Sandberg + * @since 1.2 + */ +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. + */ + public Throwable getCause() { + // Even if you cannot set the cause of this exception other than through + // the constructor, we check for the cause being "this" here, as the cause + // could still be set to "this" via reflection: for example, by a remoting + // deserializer like Hessian's. + return (this.cause == this ? null : this.cause); + } + + /** + * Constructor that takes a message. + * + * @param msg + * the detail message + */ + public NamingException(String msg) { + super(msg); + } + + /** + * 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}. + */ + public NamingException(String msg, Throwable cause) { + super(msg); + this.cause = cause; + } + + /** + * 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 + */ + public String getExplanation() { + if (getCause() instanceof javax.naming.NamingException) { + return ((javax.naming.NamingException) getCause()).getExplanation(); + } + return null; + } + + /** + * 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 + */ + public Name getRemainingName() { + if (getCause() instanceof javax.naming.NamingException) { + 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 + * {@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 + */ + public Name getResolvedName() { + if (getCause() instanceof javax.naming.NamingException) { + 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 + */ + public Object getResolvedObj() { + if (getCause() instanceof javax.naming.NamingException) { + return ((javax.naming.NamingException) getCause()).getResolvedObj(); + } + return null; + } + + /** + * 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(); + boolean serializable = resolvedObj instanceof Serializable; + if (resolvedObj != null && !serializable) { + // the cause is of this type, since resolvedObj is not null + javax.naming.NamingException namingException = (javax.naming.NamingException) getCause(); + namingException.setResolvedObj(null); + try { + stream.defaultWriteObject(); + } finally { + namingException.setResolvedObj(resolvedObj); + } + } 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 bf0ccbb5..e339be08 100644 --- a/core/src/main/java/org/springframework/ldap/NamingSecurityException.java +++ b/core/src/main/java/org/springframework/ldap/NamingSecurityException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI NamingSecurityException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.NamingSecurityException - */ -public class NamingSecurityException extends NamingException { - - public NamingSecurityException(javax.naming.NamingSecurityException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI NamingSecurityException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.NamingSecurityException + */ +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 254734eb..01538e85 100644 --- a/core/src/main/java/org/springframework/ldap/NoInitialContextException.java +++ b/core/src/main/java/org/springframework/ldap/NoInitialContextException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 8f09cbed..9f73df94 100644 --- a/core/src/main/java/org/springframework/ldap/NoPermissionException.java +++ b/core/src/main/java/org/springframework/ldap/NoPermissionException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI NoPermissionException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.NoPermissionException - */ -public class NoPermissionException extends NamingSecurityException { - - public NoPermissionException(javax.naming.NoPermissionException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI NoPermissionException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.NoPermissionException + */ +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 13d8fccd..befa8546 100644 --- a/core/src/main/java/org/springframework/ldap/NoSuchAttributeException.java +++ b/core/src/main/java/org/springframework/ldap/NoSuchAttributeException.java @@ -1,35 +1,35 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI NoSuchAttributeException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.directory.NoSuchAttributeException - */ -public class NoSuchAttributeException extends NamingException { - - public NoSuchAttributeException(String message) { - super(message); - } - - public NoSuchAttributeException(javax.naming.directory.NoSuchAttributeException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI NoSuchAttributeException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.directory.NoSuchAttributeException + */ +public class NoSuchAttributeException extends NamingException { + + public NoSuchAttributeException(String message) { + super(message); + } + + 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 3a4c84c4..f1dc1650 100644 --- a/core/src/main/java/org/springframework/ldap/NotContextException.java +++ b/core/src/main/java/org/springframework/ldap/NotContextException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI NotContextException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.NotContextException - */ -public class NotContextException extends NamingException { - - public NotContextException(javax.naming.NotContextException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI NotContextException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.NotContextException + */ +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 3c3e2947..41e33b57 100644 --- a/core/src/main/java/org/springframework/ldap/OperationNotSupportedException.java +++ b/core/src/main/java/org/springframework/ldap/OperationNotSupportedException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 e208b5bf..639e6217 100644 --- a/core/src/main/java/org/springframework/ldap/PartialResultException.java +++ b/core/src/main/java/org/springframework/ldap/PartialResultException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI PartialResultException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.PartialResultException - */ -public class PartialResultException extends NamingException { - - public PartialResultException(javax.naming.PartialResultException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI PartialResultException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.PartialResultException + */ +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 8bc12329..4536c850 100644 --- a/core/src/main/java/org/springframework/ldap/ReferralException.java +++ b/core/src/main/java/org/springframework/ldap/ReferralException.java @@ -1,31 +1,31 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * Runtime exception mirroring the JNDI ReferralException. - * - * @author Ulrik Sandberg - * @since 1.2 - * @see javax.naming.ReferralException - */ -public class ReferralException extends NamingException { - - public ReferralException(javax.naming.ReferralException cause) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * Runtime exception mirroring the JNDI ReferralException. + * + * @author Ulrik Sandberg + * @since 1.2 + * @see javax.naming.ReferralException + */ +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 f4ea33ed..913bf000 100644 --- a/core/src/main/java/org/springframework/ldap/SchemaViolationException.java +++ b/core/src/main/java/org/springframework/ldap/SchemaViolationException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 1f8095e8..a9b8401d 100644 --- a/core/src/main/java/org/springframework/ldap/ServiceUnavailableException.java +++ b/core/src/main/java/org/springframework/ldap/ServiceUnavailableException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 e42d28a9..197b968c 100644 --- a/core/src/main/java/org/springframework/ldap/SizeLimitExceededException.java +++ b/core/src/main/java/org/springframework/ldap/SizeLimitExceededException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 3035cad8..f63a9400 100644 --- a/core/src/main/java/org/springframework/ldap/TimeLimitExceededException.java +++ b/core/src/main/java/org/springframework/ldap/TimeLimitExceededException.java @@ -1,32 +1,32 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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) { - super(cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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) { + 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 1cd8a289..3ac3db00 100644 --- a/core/src/main/java/org/springframework/ldap/UncategorizedLdapException.java +++ b/core/src/main/java/org/springframework/ldap/UncategorizedLdapException.java @@ -1,38 +1,38 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap; - -/** - * NamingException to be thrown when no other matching subclass is found. - * - * @author Ulrik Sandberg - * @since 1.2 - */ -public class UncategorizedLdapException extends NamingException { - - public UncategorizedLdapException(String msg) { - super(msg); - } - - public UncategorizedLdapException(String msg, Throwable cause) { - super(msg, cause); - } - - public UncategorizedLdapException(Throwable cause) { - super("Uncategorized exception occured during LDAP processing", cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap; + +/** + * NamingException to be thrown when no other matching subclass is found. + * + * @author Ulrik Sandberg + * @since 1.2 + */ +public class UncategorizedLdapException extends NamingException { + + public UncategorizedLdapException(String msg) { + super(msg); + } + + public UncategorizedLdapException(String msg, Throwable cause) { + super(msg, cause); + } + + public UncategorizedLdapException(Throwable cause) { + super("Uncategorized exception occured during LDAP processing", cause); + } +} 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 692b2579..1c9961b3 100644 --- a/core/src/main/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecorator.java +++ b/core/src/main/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecorator.java @@ -1,156 +1,156 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.authentication; - -import org.springframework.util.StringUtils; -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. - *

- * 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 { - - private AuthenticationSource target; - - private String defaultUser; - - private String defaultPassword; - - /** - * Constructor for bean usage. - */ - public DefaultValuesAuthenticationSourceDecorator() { - } - - /** - * 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. - */ - public DefaultValuesAuthenticationSourceDecorator( - AuthenticationSource target, String defaultUser, - String defaultPassword) { - this.target = target; - this.defaultUser = defaultUser; - this.defaultPassword = 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. - */ - public String getCredentials() { - if (StringUtils.hasText(target.getPrincipal())) { - return target.getCredentials(); - } 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. - */ - public String getPrincipal() { - String principal = target.getPrincipal(); - if (StringUtils.hasText(principal)) { - return principal; - } else { - return defaultUser; - } - } - - /** - * Set 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. - */ - public void setDefaultUser(String defaultUser) { - this.defaultUser = defaultUser; - } - - /** - * Set the target AuthenticationSource. - * - * @param target - * the target AuthenticationSource. - */ - public void setTarget(AuthenticationSource target) { - this.target = target; - } - - /* - * (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.'"); - } - - if (defaultUser == null) { - throw new IllegalArgumentException( - "Property 'defaultUser' must be set.'"); - } - - if (defaultPassword == null) { - throw new IllegalArgumentException( - "Property 'defaultPassword' must be set.'"); - } - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.authentication; + +import org.springframework.util.StringUtils; +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. + *

+ * 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 { + + private AuthenticationSource target; + + private String defaultUser; + + private String defaultPassword; + + /** + * Constructor for bean usage. + */ + public DefaultValuesAuthenticationSourceDecorator() { + } + + /** + * 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. + */ + public DefaultValuesAuthenticationSourceDecorator( + AuthenticationSource target, String defaultUser, + String defaultPassword) { + this.target = target; + this.defaultUser = defaultUser; + this.defaultPassword = 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. + */ + public String getCredentials() { + if (StringUtils.hasText(target.getPrincipal())) { + return target.getCredentials(); + } 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. + */ + public String getPrincipal() { + String principal = target.getPrincipal(); + if (StringUtils.hasText(principal)) { + return principal; + } else { + return defaultUser; + } + } + + /** + * Set 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. + */ + public void setDefaultUser(String defaultUser) { + this.defaultUser = defaultUser; + } + + /** + * Set the target AuthenticationSource. + * + * @param target + * the target AuthenticationSource. + */ + public void setTarget(AuthenticationSource target) { + this.target = target; + } + + /* + * (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.'"); + } + + if (defaultUser == null) { + throw new IllegalArgumentException( + "Property 'defaultUser' must be set.'"); + } + + if (defaultPassword == null) { + throw new IllegalArgumentException( + "Property 'defaultPassword' must be set.'"); + } + } +} 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 fa2124ee..3e5c7f96 100644 --- a/core/src/main/java/org/springframework/ldap/control/CreateControlFailedException.java +++ b/core/src/main/java/org/springframework/ldap/control/CreateControlFailedException.java @@ -1,51 +1,51 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.control; - -import org.springframework.ldap.NamingException; - -/** - * Thrown by an AbstractRequestControlDirContextProcessor when it cannot create - * a request control. - * - * @author Ulrik Sandberg - * @since 1.2 - */ -public class CreateControlFailedException extends NamingException { - - /** - * Create a new CreateControlFailedException. - * - * @param msg - * the detail message - */ - public CreateControlFailedException(String msg) { - super(msg); - } - - /** - * Create a new CreateControlFailedException. - * - * @param msg - * the detail message - * @param cause - * the root cause (if any) - */ - public CreateControlFailedException(String msg, Throwable cause) { - super(msg, cause); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.control; + +import org.springframework.ldap.NamingException; + +/** + * Thrown by an AbstractRequestControlDirContextProcessor when it cannot create + * a request control. + * + * @author Ulrik Sandberg + * @since 1.2 + */ +public class CreateControlFailedException extends NamingException { + + /** + * Create a new CreateControlFailedException. + * + * @param msg + * the detail message + */ + public CreateControlFailedException(String msg) { + super(msg); + } + + /** + * Create a new CreateControlFailedException. + * + * @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 648108b3..3dc7a0a0 100644 --- a/core/src/main/java/org/springframework/ldap/control/PagedResult.java +++ b/core/src/main/java/org/springframework/ldap/control/PagedResult.java @@ -1,85 +1,85 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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}. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - * @deprecated - */ -public class PagedResult { - - private List resultList; - - private PagedResultsCookie 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; - this.cookie = cookie; - } - - /** - * Get the cookie. - * - * @return the cookie. - */ - public PagedResultsCookie getCookie() { - return cookie; - } - - /** - * Get the result list. - * - * @return the result list. - */ - public List getResultList() { - return resultList; - } - - @Override - public boolean equals(Object o) { - 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; - - return true; - } - - @Override - public int hashCode() { - int result = resultList != null ? resultList.hashCode() : 0; - result = 31 * result + (cookie != null ? cookie.hashCode() : 0); - return result; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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}. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + * @deprecated + */ +public class PagedResult { + + private List resultList; + + private PagedResultsCookie 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; + this.cookie = cookie; + } + + /** + * Get the cookie. + * + * @return the cookie. + */ + public PagedResultsCookie getCookie() { + return cookie; + } + + /** + * Get the result list. + * + * @return the result list. + */ + public List getResultList() { + return resultList; + } + + @Override + public boolean equals(Object o) { + 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; + + return true; + } + + @Override + public int hashCode() { + int result = resultList != null ? resultList.hashCode() : 0; + 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 bfb9e373..cc470e24 100644 --- a/core/src/main/java/org/springframework/ldap/control/PagedResultsCookie.java +++ b/core/src/main/java/org/springframework/ldap/control/PagedResultsCookie.java @@ -1,76 +1,76 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.control; - -import javax.naming.ldap.PagedResultsControl; -import java.util.Arrays; - -/** - * Wrapper class for the cookie returned when using the - * {@link PagedResultsControl}. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public class PagedResultsCookie { - - private byte[] cookie; - - /** - * Constructor. - * - * @param cookie - * the cookie returned by a PagedResultsResponseControl. - */ - public PagedResultsCookie(byte[] cookie) { - if (cookie != null) { - this.cookie = Arrays.copyOf(cookie, cookie.length); - } 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. - */ - public byte[] getCookie() { - if (cookie != null) { - return Arrays.copyOf(cookie, cookie.length); - } else { - return null; - } - } - - @Override - public boolean equals(Object o) { - 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; - - return true; - } - - @Override - public int hashCode() { - return cookie != null ? Arrays.hashCode(cookie) : 0; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.control; + +import javax.naming.ldap.PagedResultsControl; +import java.util.Arrays; + +/** + * Wrapper class for the cookie returned when using the + * {@link PagedResultsControl}. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public class PagedResultsCookie { + + private byte[] cookie; + + /** + * Constructor. + * + * @param cookie + * the cookie returned by a PagedResultsResponseControl. + */ + public PagedResultsCookie(byte[] cookie) { + if (cookie != null) { + this.cookie = Arrays.copyOf(cookie, cookie.length); + } 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. + */ + public byte[] getCookie() { + if (cookie != null) { + return Arrays.copyOf(cookie, cookie.length); + } else { + return null; + } + } + + @Override + public boolean equals(Object o) { + 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; + + return true; + } + + @Override + 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 2d2a417b..1c58d373 100644 --- a/core/src/main/java/org/springframework/ldap/control/PagedResultsDirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/control/PagedResultsDirContextProcessor.java @@ -1,155 +1,155 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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). - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndResponseControlDirContextProcessor { - - private static final String DEFAULT_REQUEST_CONTROL = "javax.naming.ldap.PagedResultsControl"; - - private static final String FALLBACK_REQUEST_CONTROL = "com.sun.jndi.ldap.ctl.PagedResultsControl"; - - private static final String DEFAULT_RESPONSE_CONTROL = "javax.naming.ldap.PagedResultsResponseControl"; - - private static final String FALLBACK_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.PagedResultsResponseControl"; - - private int pageSize; - - private PagedResultsCookie cookie; - - private int resultSize; - - 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. - * - * @param pageSize the page size. - */ - public PagedResultsDirContextProcessor(int pageSize) { - this(pageSize, null); - } - - /** - * 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. - */ - public PagedResultsDirContextProcessor(int pageSize, PagedResultsCookie cookie) { - this.pageSize = pageSize; - this.cookie = cookie; - - defaultRequestControl = DEFAULT_REQUEST_CONTROL; - 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. - * @see #hasMore() - */ - public PagedResultsCookie getCookie() { - return cookie; - } - - /** - * Get the page size. - * - * @return the page size. - */ - public int getPageSize() { - return pageSize; - } - - /** - * 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() { - return resultSize; - } - - /* - * @see - * org.springframework.ldap.control.AbstractRequestControlDirContextProcessor - * #createRequestControl() - */ - public Control createRequestControl() { - byte[] actualCookie = null; - if (cookie != null) { - actualCookie = cookie.getCookie(); - } - return super.createRequestControl(new Class[] { int.class, byte[].class, boolean.class }, - 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. - * @since 2.0 - */ - public boolean hasMore() { - return more; - } - - /* - * @seeorg.springframework.ldap.control. - * AbstractFallbackRequestAndResponseControlDirContextProcessor - * #handleResponse(java.lang.Object) - */ - protected void handleResponse(Object control) { - byte[] result = (byte[]) invokeMethod("getCookie", responseControlClass, control); - if(result == null) { - more = false; - } - this.cookie = new PagedResultsCookie(result); - this.resultSize = (Integer) invokeMethod("getResultSize", responseControlClass, control); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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). + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public class PagedResultsDirContextProcessor extends AbstractFallbackRequestAndResponseControlDirContextProcessor { + + private static final String DEFAULT_REQUEST_CONTROL = "javax.naming.ldap.PagedResultsControl"; + + private static final String FALLBACK_REQUEST_CONTROL = "com.sun.jndi.ldap.ctl.PagedResultsControl"; + + private static final String DEFAULT_RESPONSE_CONTROL = "javax.naming.ldap.PagedResultsResponseControl"; + + private static final String FALLBACK_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.PagedResultsResponseControl"; + + private int pageSize; + + private PagedResultsCookie cookie; + + private int resultSize; + + 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. + * + * @param pageSize the page size. + */ + public PagedResultsDirContextProcessor(int pageSize) { + this(pageSize, null); + } + + /** + * 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. + */ + public PagedResultsDirContextProcessor(int pageSize, PagedResultsCookie cookie) { + this.pageSize = pageSize; + this.cookie = cookie; + + defaultRequestControl = DEFAULT_REQUEST_CONTROL; + 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. + * @see #hasMore() + */ + public PagedResultsCookie getCookie() { + return cookie; + } + + /** + * Get the page size. + * + * @return the page size. + */ + public int getPageSize() { + return pageSize; + } + + /** + * 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() { + return resultSize; + } + + /* + * @see + * org.springframework.ldap.control.AbstractRequestControlDirContextProcessor + * #createRequestControl() + */ + public Control createRequestControl() { + byte[] actualCookie = null; + if (cookie != null) { + actualCookie = cookie.getCookie(); + } + return super.createRequestControl(new Class[] { int.class, byte[].class, boolean.class }, + 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. + * @since 2.0 + */ + public boolean hasMore() { + return more; + } + + /* + * @seeorg.springframework.ldap.control. + * AbstractFallbackRequestAndResponseControlDirContextProcessor + * #handleResponse(java.lang.Object) + */ + protected void handleResponse(Object control) { + byte[] result = (byte[]) invokeMethod("getCookie", responseControlClass, control); + 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 7906a758..1afafe3d 100644 --- a/core/src/main/java/org/springframework/ldap/control/PagedResultsRequestControl.java +++ b/core/src/main/java/org/springframework/ldap/control/PagedResultsRequestControl.java @@ -1,223 +1,223 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.control; - -import org.springframework.ldap.UncategorizedLdapException; -import org.springframework.util.ClassUtils; -import org.springframework.util.ReflectionUtils; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.ldap.Control; -import javax.naming.ldap.LdapContext; -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). - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - * @deprecated Use PagedResultsDirContextProcessor instead. - */ -public class PagedResultsRequestControl extends AbstractRequestControlDirContextProcessor { - - private static final boolean CRITICAL_CONTROL = true; - - private static final String DEFAULT_REQUEST_CONTROL = "javax.naming.ldap.PagedResultsControl"; - - private static final String LDAPBP_REQUEST_CONTROL = "com.sun.jndi.ldap.ctl.PagedResultsControl"; - - private static final String DEFAULT_RESPONSE_CONTROL = "javax.naming.ldap.PagedResultsResponseControl"; - - private static final String LDAPBP_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.PagedResultsResponseControl"; - - private int pageSize; - - private PagedResultsCookie cookie; - - private int resultSize; - - private boolean critical = CRITICAL_CONTROL; - - private Class responseControlClass; - - 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. - * - * @param pageSize the page size. - */ - public PagedResultsRequestControl(int pageSize) { - this(pageSize, null); - } - - /** - * 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. - */ - public PagedResultsRequestControl(int pageSize, PagedResultsCookie cookie) { - this.pageSize = pageSize; - this.cookie = cookie; - - loadControlClasses(); - } - - private void loadControlClasses() { - try { - requestControlClass = Class.forName(DEFAULT_REQUEST_CONTROL); - responseControlClass = Class.forName(DEFAULT_RESPONSE_CONTROL); - } - catch (ClassNotFoundException e) { - log.debug("Default control classes not found - falling back to LdapBP classes", e); - - try { - requestControlClass = Class.forName(LDAPBP_REQUEST_CONTROL); - responseControlClass = Class.forName(LDAPBP_RESPONSE_CONTROL); - } - catch (ClassNotFoundException e1) { - throw new UncategorizedLdapException( - "Neither default nor fallback classes are available - unable to proceed", e); - } - - } - } - - /** - * Get the cookie. - * - * @return the cookie. - */ - public PagedResultsCookie getCookie() { - return cookie; - } - - /** - * Get the page size. - * - * @return the page size. - */ - public int getPageSize() { - return pageSize; - } - - /** - * 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() { - return resultSize; - } - - /** - * 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) { - this.responseControlClass = responseControlClass; - } - - public void setRequestControlClass(Class requestControlClass) { - this.requestControlClass = requestControlClass; - } - - /* - * @see - * org.springframework.ldap.control.AbstractRequestControlDirContextProcessor - * #createRequestControl() - */ - - public Control createRequestControl() { - byte[] actualCookie = null; - if (cookie != null) { - actualCookie = cookie.getCookie(); - } - 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); - } - catch (Exception e) { - ReflectionUtils.handleReflectionException(e); - } - - return result; - } - - /* - * @see - * org.springframework.ldap.core.DirContextProcessor#postProcess(javax.naming - * .directory.DirContext) - */ - - public void postProcess(DirContext ctx) throws NamingException { - - LdapContext ldapContext = (LdapContext) ctx; - Control[] responseControls = ldapContext.getResponseControls(); - if (responseControls == null) { - responseControls = new Control[0]; - } - - // Go through response controls and get info, regardless of class - for (int i = 0; i < responseControls.length; i++) { - Control responseControl = responseControls[i]; - - // check for match, try fallback otherwise - if (responseControl.getClass().isAssignableFrom(responseControlClass)) { - Object control = responseControl; - byte[] result = (byte[]) invokeMethod("getCookie", responseControlClass, control); - this.cookie = new PagedResultsCookie(result); - Integer wrapper = (Integer) invokeMethod("getResultSize", responseControlClass, control); - this.resultSize = wrapper.intValue(); - return; - } - } - - log.error("No matching response control found for paged results - looking for '{}", responseControlClass); - } - - private Object invokeMethod(String method, Class clazz, Object control) { - Method actualMethod = ReflectionUtils.findMethod(clazz, method); - return ReflectionUtils.invokeMethod(actualMethod, control); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.control; + +import org.springframework.ldap.UncategorizedLdapException; +import org.springframework.util.ClassUtils; +import org.springframework.util.ReflectionUtils; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.ldap.Control; +import javax.naming.ldap.LdapContext; +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). + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + * @deprecated Use PagedResultsDirContextProcessor instead. + */ +public class PagedResultsRequestControl extends AbstractRequestControlDirContextProcessor { + + private static final boolean CRITICAL_CONTROL = true; + + private static final String DEFAULT_REQUEST_CONTROL = "javax.naming.ldap.PagedResultsControl"; + + private static final String LDAPBP_REQUEST_CONTROL = "com.sun.jndi.ldap.ctl.PagedResultsControl"; + + private static final String DEFAULT_RESPONSE_CONTROL = "javax.naming.ldap.PagedResultsResponseControl"; + + private static final String LDAPBP_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.PagedResultsResponseControl"; + + private int pageSize; + + private PagedResultsCookie cookie; + + private int resultSize; + + private boolean critical = CRITICAL_CONTROL; + + private Class responseControlClass; + + 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. + * + * @param pageSize the page size. + */ + public PagedResultsRequestControl(int pageSize) { + this(pageSize, null); + } + + /** + * 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. + */ + public PagedResultsRequestControl(int pageSize, PagedResultsCookie cookie) { + this.pageSize = pageSize; + this.cookie = cookie; + + loadControlClasses(); + } + + private void loadControlClasses() { + try { + requestControlClass = Class.forName(DEFAULT_REQUEST_CONTROL); + responseControlClass = Class.forName(DEFAULT_RESPONSE_CONTROL); + } + catch (ClassNotFoundException e) { + log.debug("Default control classes not found - falling back to LdapBP classes", e); + + try { + requestControlClass = Class.forName(LDAPBP_REQUEST_CONTROL); + responseControlClass = Class.forName(LDAPBP_RESPONSE_CONTROL); + } + catch (ClassNotFoundException e1) { + throw new UncategorizedLdapException( + "Neither default nor fallback classes are available - unable to proceed", e); + } + + } + } + + /** + * Get the cookie. + * + * @return the cookie. + */ + public PagedResultsCookie getCookie() { + return cookie; + } + + /** + * Get the page size. + * + * @return the page size. + */ + public int getPageSize() { + return pageSize; + } + + /** + * 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() { + return resultSize; + } + + /** + * 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) { + this.responseControlClass = responseControlClass; + } + + public void setRequestControlClass(Class requestControlClass) { + this.requestControlClass = requestControlClass; + } + + /* + * @see + * org.springframework.ldap.control.AbstractRequestControlDirContextProcessor + * #createRequestControl() + */ + + public Control createRequestControl() { + byte[] actualCookie = null; + if (cookie != null) { + actualCookie = cookie.getCookie(); + } + 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); + } + catch (Exception e) { + ReflectionUtils.handleReflectionException(e); + } + + return result; + } + + /* + * @see + * org.springframework.ldap.core.DirContextProcessor#postProcess(javax.naming + * .directory.DirContext) + */ + + public void postProcess(DirContext ctx) throws NamingException { + + LdapContext ldapContext = (LdapContext) ctx; + Control[] responseControls = ldapContext.getResponseControls(); + if (responseControls == null) { + responseControls = new Control[0]; + } + + // Go through response controls and get info, regardless of class + for (int i = 0; i < responseControls.length; i++) { + Control responseControl = responseControls[i]; + + // check for match, try fallback otherwise + if (responseControl.getClass().isAssignableFrom(responseControlClass)) { + Object control = responseControl; + byte[] result = (byte[]) invokeMethod("getCookie", responseControlClass, control); + this.cookie = new PagedResultsCookie(result); + Integer wrapper = (Integer) invokeMethod("getResultSize", responseControlClass, control); + this.resultSize = wrapper.intValue(); + return; + } + } + + log.error("No matching response control found for paged results - looking for '{}", responseControlClass); + } + + private Object invokeMethod(String method, Class clazz, Object control) { + 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 9b372b5d..9708b644 100644 --- a/core/src/main/java/org/springframework/ldap/control/SortControlDirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/control/SortControlDirContextProcessor.java @@ -1,119 +1,119 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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. - * - * @author Ulrik Sandberg - */ -public class SortControlDirContextProcessor extends AbstractFallbackRequestAndResponseControlDirContextProcessor { - - private static final String DEFAULT_REQUEST_CONTROL = "javax.naming.ldap.SortControl"; - - private static final String FALLBACK_REQUEST_CONTROL = "com.sun.jndi.ldap.ctl.SortControl"; - - private static final String DEFAULT_RESPONSE_CONTROL = "javax.naming.ldap.SortResponseControl"; - - private static final String FALLBACK_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.SortResponseControl"; - - /** - * What key to sort on. - */ - String sortKey; - - /** - * Whether the search result actually was sorted. - */ - private boolean sorted; - - /** - * The result code of the supposedly sorted search. - */ - private int resultCode; - - /** - * 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) { - this.sortKey = sortKey; - this.sorted = false; - this.resultCode = -1; - - defaultRequestControl = DEFAULT_REQUEST_CONTROL; - defaultResponseControl = DEFAULT_RESPONSE_CONTROL; - - fallbackRequestControl = FALLBACK_REQUEST_CONTROL; - fallbackResponseControl = FALLBACK_RESPONSE_CONTROL; - - loadControlClasses(); - } - - /** - * Check whether the returned values were actually sorted by the server. - * - * @return true if the result was sorted, false - * otherwise. - */ - public boolean isSorted() { - return sorted; - } - - /** - * Get the result code returned by the control. - * - * @return result code. - */ - public int getResultCode() { - return resultCode; - } - - /** - * Get the sort key. - * - * @return the sort key. - */ - public String getSortKey() { - return sortKey; - } - - /* - * @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}); - } - - /* - * @see org.springframework.ldap.control. - * AbstractFallbackRequestAndResponseControlDirContextProcessor - * #handleResponse(java.lang.Object) - */ - protected void handleResponse(Object control) { - this.sorted = (Boolean) invokeMethod("isSorted", responseControlClass, control); - this.resultCode = (Integer) invokeMethod("getResultCode", responseControlClass, control); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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. + * + * @author Ulrik Sandberg + */ +public class SortControlDirContextProcessor extends AbstractFallbackRequestAndResponseControlDirContextProcessor { + + private static final String DEFAULT_REQUEST_CONTROL = "javax.naming.ldap.SortControl"; + + private static final String FALLBACK_REQUEST_CONTROL = "com.sun.jndi.ldap.ctl.SortControl"; + + private static final String DEFAULT_RESPONSE_CONTROL = "javax.naming.ldap.SortResponseControl"; + + private static final String FALLBACK_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.SortResponseControl"; + + /** + * What key to sort on. + */ + String sortKey; + + /** + * Whether the search result actually was sorted. + */ + private boolean sorted; + + /** + * The result code of the supposedly sorted search. + */ + private int resultCode; + + /** + * 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) { + this.sortKey = sortKey; + this.sorted = false; + this.resultCode = -1; + + defaultRequestControl = DEFAULT_REQUEST_CONTROL; + defaultResponseControl = DEFAULT_RESPONSE_CONTROL; + + fallbackRequestControl = FALLBACK_REQUEST_CONTROL; + fallbackResponseControl = FALLBACK_RESPONSE_CONTROL; + + loadControlClasses(); + } + + /** + * Check whether the returned values were actually sorted by the server. + * + * @return true if the result was sorted, false + * otherwise. + */ + public boolean isSorted() { + return sorted; + } + + /** + * Get the result code returned by the control. + * + * @return result code. + */ + public int getResultCode() { + return resultCode; + } + + /** + * Get the sort key. + * + * @return the sort key. + */ + public String getSortKey() { + return sortKey; + } + + /* + * @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}); + } + + /* + * @see org.springframework.ldap.control. + * AbstractFallbackRequestAndResponseControlDirContextProcessor + * #handleResponse(java.lang.Object) + */ + protected void handleResponse(Object control) { + 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 9cd28368..aacbd491 100644 --- a/core/src/main/java/org/springframework/ldap/core/AttributeModificationsAware.java +++ b/core/src/main/java/org/springframework/ldap/core/AttributeModificationsAware.java @@ -1,37 +1,37 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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. - * - * @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. - * - * @return an array of modification items. - */ - ModificationItem[] getModificationItems(); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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. + * + * @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. + * + * @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 3288ba9f..3ab1b38c 100644 --- a/core/src/main/java/org/springframework/ldap/core/AttributesMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/AttributesMapper.java @@ -1,55 +1,55 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import javax.naming.Name; -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. - *

- * 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. - * @return an object built from the attributes. - * @throws NamingException - * if any error occurs mapping the attributes - */ - T mapFromAttributes(Attributes attributes) - throws NamingException; -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import javax.naming.Name; +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. + *

+ * 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. + * @return an object built from the attributes. + * @throws NamingException + * if any error occurs mapping the attributes + */ + T mapFromAttributes(Attributes attributes) + throws NamingException; +} 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 8db5ff5c..ba3c396b 100644 --- a/core/src/main/java/org/springframework/ldap/core/AuthenticationSource.java +++ b/core/src/main/java/org/springframework/ldap/core/AuthenticationSource.java @@ -1,40 +1,40 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -/** - * 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(); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +/** + * 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/CollectingNameClassPairCallbackHandler.java b/core/src/main/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandler.java index bae7b6a9..7f785157 100644 --- a/core/src/main/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandler.java +++ b/core/src/main/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandler.java @@ -1,64 +1,64 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core; - -import javax.naming.NameClassPair; -import javax.naming.NamingException; -import java.util.LinkedList; -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 { - - private List list = new LinkedList(); - - /** - * Get the assembled list. - * - * @return the list of all assembled objects. - */ - public List getList() { - return list; - } - - /** - * Pass on the supplied NameClassPair to - * {@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. - * @return an object constructed from the data in the NameClassPair. - * @throws NamingException if an error occurs. - */ - public abstract T getObjectFromNameClassPair( - NameClassPair nameClassPair) throws NamingException; -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core; + +import javax.naming.NameClassPair; +import javax.naming.NamingException; +import java.util.LinkedList; +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 { + + private List list = new LinkedList(); + + /** + * Get the assembled list. + * + * @return the list of all assembled objects. + */ + public List getList() { + return list; + } + + /** + * Pass on the supplied NameClassPair to + * {@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. + * @return an object constructed from the data in the NameClassPair. + * @throws NamingException if an error occurs. + */ + 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 be735682..323552f0 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextAssembler.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextAssembler.java @@ -1,36 +1,36 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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. - * - * @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. - */ - void mapToContext(Object obj, Object ctx); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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. + * + * @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. + */ + 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 f4db2062..bedb77ff 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextExecutor.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextExecutor.java @@ -1,50 +1,50 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core; - -import javax.naming.NamingException; -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.: - * - *

- * ContextExecutor executor = new ContextExecutor() {
- *     public Object executeWithContext(DirContext ctx) throws NamingException {
- *         return ctx.lookup(dn);
- *     }
- * };
- * 
- * - * @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. - * @return any object resulting from the operation - might be null. - * @throws NamingException - * if the operation resulted in one. - */ - T executeWithContext(DirContext ctx) throws NamingException; -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core; + +import javax.naming.NamingException; +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.: + * + *
+ * ContextExecutor executor = new ContextExecutor() {
+ *     public Object executeWithContext(DirContext ctx) throws NamingException {
+ *         return ctx.lookup(dn);
+ *     }
+ * };
+ * 
+ * + * @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. + * @return any object resulting from the operation - might be null. + * @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 2325331c..d4c2af14 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextMapper.java @@ -1,67 +1,67 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.springframework.ldap.core.support.AbstractContextMapper; -import org.springframework.ldap.core.support.DefaultDirObjectFactory; - -import javax.naming.Binding; -import javax.naming.Name; -import javax.naming.NamingException; -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 - * 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. - *

- * Alternatively, consider using an {@link AttributesMapper} in stead. - * - * @see LdapTemplate#search(Name, String, ContextMapper) - * @see LdapTemplate#listBindings(Name, ContextMapper) - * @see LdapTemplate#lookup(Name, ContextMapper) - * @see AttributesMapper - * @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. - * @return an object built from the data in the context. - * @throws NamingException if an error occurs. - */ - T mapFromContext(Object ctx) throws NamingException; -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.springframework.ldap.core.support.AbstractContextMapper; +import org.springframework.ldap.core.support.DefaultDirObjectFactory; + +import javax.naming.Binding; +import javax.naming.Name; +import javax.naming.NamingException; +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 + * 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. + *

+ * Alternatively, consider using an {@link AttributesMapper} in stead. + * + * @see LdapTemplate#search(Name, String, ContextMapper) + * @see LdapTemplate#listBindings(Name, ContextMapper) + * @see LdapTemplate#lookup(Name, ContextMapper) + * @see AttributesMapper + * @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. + * @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/ContextSource.java b/core/src/main/java/org/springframework/ldap/core/ContextSource.java index 81d7b452..ae8a6915 100644 --- a/core/src/main/java/org/springframework/ldap/core/ContextSource.java +++ b/core/src/main/java/org/springframework/ldap/core/ContextSource.java @@ -1,71 +1,71 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.springframework.ldap.NamingException; - -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. - * - * @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. - * - * @return A DirContext instance, never null. - * @throws NamingException if some error occurs creating an DirContext. - */ - DirContext getReadOnlyContext() throws NamingException; - - /** - * Gets a read-write DirContext instance. - * - * @return A DirContext instance, never null. - * @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. - * @param credentials The credentials to use for authentication. - * @return an authenticated DirContext instance, never - * null. - * @since 1.3 - */ - DirContext getContext(String principal, String credentials) throws NamingException; +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.springframework.ldap.NamingException; + +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. + * + * @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. + * + * @return A DirContext instance, never null. + * @throws NamingException if some error occurs creating an DirContext. + */ + DirContext getReadOnlyContext() throws NamingException; + + /** + * Gets a read-write DirContext instance. + * + * @return A DirContext instance, never null. + * @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. + * @param credentials The credentials to use for authentication. + * @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 7b8938a0..9299833f 100644 --- a/core/src/main/java/org/springframework/ldap/core/DefaultDnParserFactory.java +++ b/core/src/main/java/org/springframework/ldap/core/DefaultDnParserFactory.java @@ -1,45 +1,45 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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. - * - * @author Mattias Hellborg Arthursson - * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. - */ -public final class DefaultDnParserFactory { - /** - * Not to be instantiated. - */ - private DefaultDnParserFactory() { - - } - - /** - * Create a new DnParser instance. - * - * @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)); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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. + * + * @author Mattias Hellborg Arthursson + * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. + */ +public final class DefaultDnParserFactory { + /** + * Not to be instantiated. + */ + private DefaultDnParserFactory() { + + } + + /** + * Create a new DnParser instance. + * + * @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/DefaultNameClassPairMapper.java b/core/src/main/java/org/springframework/ldap/core/DefaultNameClassPairMapper.java index 8db126d5..71edb54c 100644 --- a/core/src/main/java/org/springframework/ldap/core/DefaultNameClassPairMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/DefaultNameClassPairMapper.java @@ -1,47 +1,47 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -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. - * - * @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. - * @return the Name string from the NameClassPair. - */ - @Override - public String mapFromNameClassPair(NameClassPair nameClassPair) - throws NamingException { - - return nameClassPair.getName(); - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +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. + * + * @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. + * @return the Name string from the NameClassPair. + */ + @Override + public String mapFromNameClassPair(NameClassPair nameClassPair) + throws NamingException { + + return nameClassPair.getName(); + } + +} 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 6ffe1ff6..3b859fcb 100644 --- a/core/src/main/java/org/springframework/ldap/core/DirContextProcessor.java +++ b/core/src/main/java/org/springframework/ldap/core/DirContextProcessor.java @@ -1,51 +1,51 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -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. - * - * @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. - */ - 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. - */ - void postProcess(DirContext ctx) throws NamingException; -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +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. + * + * @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. + */ + 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. + */ + 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 1d14f17e..f7f25aaf 100644 --- a/core/src/main/java/org/springframework/ldap/core/DirContextProxy.java +++ b/core/src/main/java/org/springframework/ldap/core/DirContextProxy.java @@ -1,34 +1,34 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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. - * - * @author Mattias Hellborg Arthursson - * @since 1.2 - */ -public interface DirContextProxy { - /** - * Get the target DirContext of the proxy. - * - * @return the target DirContext. - */ - DirContext getTargetContext(); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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. + * + * @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/DistinguishedNameEditor.java b/core/src/main/java/org/springframework/ldap/core/DistinguishedNameEditor.java index 61b99354..0188408f 100644 --- a/core/src/main/java/org/springframework/ldap/core/DistinguishedNameEditor.java +++ b/core/src/main/java/org/springframework/ldap/core/DistinguishedNameEditor.java @@ -1,58 +1,58 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core; - -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. - * - * @author Mattias Hellborg Arthursson - * @since 1.2 - * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. - */ -public class DistinguishedNameEditor extends PropertyEditorSupport { - - /* - * (non-Javadoc) - * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String) - */ - public void setAsText(String text) throws IllegalArgumentException { - if (text == null) { - setValue(null); - } - else { - setValue(new DistinguishedName(text).immutableDistinguishedName()); - } - } - - /* - * (non-Javadoc) - * @see java.beans.PropertyEditorSupport#getAsText() - */ - public String getAsText() { - Object theValue = getValue(); - if (theValue == null) { - return null; - } - else { - return ((DistinguishedName) theValue).toString(); - } - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core; + +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. + * + * @author Mattias Hellborg Arthursson + * @since 1.2 + * @deprecated {@link DistinguishedName} and associated classes are deprecated as of 2.0. + */ +public class DistinguishedNameEditor extends PropertyEditorSupport { + + /* + * (non-Javadoc) + * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String) + */ + public void setAsText(String text) throws IllegalArgumentException { + if (text == null) { + setValue(null); + } + else { + setValue(new DistinguishedName(text).immutableDistinguishedName()); + } + } + + /* + * (non-Javadoc) + * @see java.beans.PropertyEditorSupport#getAsText() + */ + public String getAsText() { + Object theValue = getValue(); + if (theValue == null) { + return null; + } + else { + return ((DistinguishedName) theValue).toString(); + } + } + +} 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 13416dde..3b20fa99 100644 --- a/core/src/main/java/org/springframework/ldap/core/DnParser.java +++ b/core/src/main/java/org/springframework/ldap/core/DnParser.java @@ -1,39 +1,39 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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. - */ - public DistinguishedName dn() throws ParseException; - - /** - * Parse a Relative Distinguished Name. - * - * @return the next rdn on the stream. - */ - public LdapRdn rdn() throws ParseException; -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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. + */ + 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/LdapAttribute.java b/core/src/main/java/org/springframework/ldap/core/LdapAttribute.java index cfe8f052..037f5272 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapAttribute.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapAttribute.java @@ -1,224 +1,224 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core; - -import javax.naming.directory.BasicAttribute; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -/** - * 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 - * {@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. - */ - public LdapAttribute(String id) { - super(id); - } - - /** - * Creates an unordered attribute with the specified ID and value. - * - * @param id {@link java.lang.String} ID of the attribute. - * @param value Attribute value. - */ - public LdapAttribute(String id, Object value) { - super(id, value); - } - - /** - * Creates an unordered attribute with the specified ID, value, and options. - * - * @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. - */ - public LdapAttribute(String id, Object value, Collection options) { - super(id, value); - this.options.addAll(options); - } - - /** - * Creates an attribute with the specified ID whose values may be ordered. - * - * @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) { - super(id, ordered); - } - - /** - * 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 ordered boolean indicating whether or not the attributes values are ordered. - */ - public LdapAttribute(String id, Collection options, boolean ordered) { - super(id, ordered); - this.options.addAll(options); - } - - /** - * 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 value Attribute value. - * @param ordered boolean indicating whether or not the attributes values are ordered. - */ - public LdapAttribute(String id, Object value, boolean ordered) { - super(id, value, 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 ordered boolean indicating whether or not the attributes values are ordered. - */ - public LdapAttribute(String id, Object value, Collection options, boolean ordered) { - super(id, value, ordered); - this.options.addAll(options); - } - - /** - * 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); - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core; + +import javax.naming.directory.BasicAttribute; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +/** + * 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 + * {@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. + */ + public LdapAttribute(String id) { + super(id); + } + + /** + * Creates an unordered attribute with the specified ID and value. + * + * @param id {@link java.lang.String} ID of the attribute. + * @param value Attribute value. + */ + public LdapAttribute(String id, Object value) { + super(id, value); + } + + /** + * Creates an unordered attribute with the specified ID, value, and options. + * + * @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. + */ + public LdapAttribute(String id, Object value, Collection options) { + super(id, value); + this.options.addAll(options); + } + + /** + * Creates an attribute with the specified ID whose values may be ordered. + * + * @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) { + super(id, ordered); + } + + /** + * 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 ordered boolean indicating whether or not the attributes values are ordered. + */ + public LdapAttribute(String id, Collection options, boolean ordered) { + super(id, ordered); + this.options.addAll(options); + } + + /** + * 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 value Attribute value. + * @param ordered boolean indicating whether or not the attributes values are ordered. + */ + public LdapAttribute(String id, Object value, boolean ordered) { + super(id, value, 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 ordered boolean indicating whether or not the attributes values are ordered. + */ + public LdapAttribute(String id, Object value, Collection options, boolean ordered) { + super(id, value, ordered); + this.options.addAll(options); + } + + /** + * 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/LdapOperations.java b/core/src/main/java/org/springframework/ldap/core/LdapOperations.java index 8c20ff21..89141be7 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapOperations.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapOperations.java @@ -1,1854 +1,1854 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.ldap.ContextNotEmptyException; -import org.springframework.ldap.NamingException; -import org.springframework.ldap.core.support.AbstractContextSource; -import org.springframework.ldap.filter.Filter; -import org.springframework.ldap.odm.core.ObjectDirectoryMapper; -import org.springframework.ldap.query.LdapQuery; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.Binding; -import javax.naming.Name; -import javax.naming.NameClassPair; -import javax.naming.directory.Attributes; -import javax.naming.directory.ModificationItem; -import javax.naming.directory.SearchControls; -import java.util.List; - -/** - * Interface that specifies a basic set of LDAP operations. Implemented by - * LdapTemplate, but it might be a useful option to use this interface in order - * to enhance testability. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public interface LdapOperations { - /** - * 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 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. - */ - 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 - * {@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. - * @throws NamingException if any error occurs. Note that a - * 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. - * @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) - */ - 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. - * @return the result from the ContextExecutor's operation. - * @throws NamingException if the operation resulted in a - * NamingException. - * @see #bind(Name, Object, Attributes) - * @see #unbind(Name) - * @see #rebind(Name, Object, Attributes) - * @see #rename(Name, Name) - * @see #modifyAttributes(Name, ModificationItem[]) - */ - 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @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. - * @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. - */ - 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. - * - * @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. - * @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. - */ - 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. - * - * @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. - * @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, 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. - * - * @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. - * @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, 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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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 - * 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. - * @throws NamingException if any error occurs. Note that a - * 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 - * 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. - * @throws NamingException if any error occurs. Note that a - * 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 - * 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. - * @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. - */ - 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 - * 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. - * @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. - */ - 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 - * 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. - * @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. - */ - 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 - * 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. - * @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. - */ - 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 - * 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. - * @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. - */ - 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 - * 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. - * @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. - */ - 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. - * - * @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. - * @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, 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. - * - * @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. - * @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, 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. - * - * @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. - * @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, 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. - * - * @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. - * @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, 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. - * - * @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(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. - * - * @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, 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 - * 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. - * @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, AttributesMapper 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. - * @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, 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. - * - * @param base The base DN where the list should be performed. - * @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. - */ - 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. - * - * @param base The base DN where the list should be performed. - * @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. - */ - 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @param base The base DN where the list should be performed. - * @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. - */ - List list(String base) throws NamingException; - - /** - * 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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @param base The base DN where the list should be performed. - * @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. - */ - 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. - * - * @param base The base DN where the list should be performed. - * @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. - */ - 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @param base The base DN where the list should be performed. - * @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. - */ - List listBindings(final String base) throws NamingException; - - /** - * 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. - * @throws NamingException if any error occurs. Note that a - * 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. - * - * @param base The base DN where the list should be performed. - * @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. - */ - 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. - * - * @param base The base DN where the list should be performed. - * @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. - */ - 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. - * - * @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. - * @see #lookupContext(Name) - * @see AbstractContextSource#setDirObjectFactory(Class) - */ - 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. - * - * @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. - * @see #lookupContext(String) - * @see AbstractContextSource#setDirObjectFactory(Class) - */ - Object lookup(String dn) throws NamingException; - - /** - * 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. - * @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. - * - * @param dn The distinguished name to find. - * @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. - * - * @param dn The distinguished name to find. - * @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. - * - * @param dn The distinguished name to find. - * @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, ContextMapper mapper) throws NamingException; - - /** - * 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. - * @return the object returned from the mapper. - * @throws NamingException if any error occurs. - */ - T lookup(Name dn, String[] attributes, AttributesMapper mapper) throws NamingException; - - /** - * 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. - * @return the object returned from the mapper. - * @throws NamingException if any error occurs. - */ - T lookup(String dn, String[] attributes, AttributesMapper mapper) throws NamingException; - - /** - * 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. - * @return the object returned from the mapper. - * @throws NamingException if any error occurs. - */ - T lookup(Name dn, String[] attributes, ContextMapper mapper) throws NamingException; - - /** - * 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. - * @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. - * - * @param dn The distinguished name of the node to modify. - * @param mods The modifications to perform. - * @throws NamingException if any error occurs. - * @see #modifyAttributes(DirContextOperations) - */ - void modifyAttributes(Name dn, ModificationItem[] mods) throws NamingException; - - /** - * 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. - * @see #modifyAttributes(DirContextOperations) - */ - 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. - * - * @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. - * @param attributes The attributes to bind, may be null. - * @throws NamingException if any error occurs. - * @see DirContextAdapter - */ - 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. - * - * @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. - * @param attributes The attributes to bind, may be null. - * @throws NamingException if any error occurs. - * @see DirContextAdapter - */ - 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. - * - * @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. - * - * @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. - * - * @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. - * @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. - * - * @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. - * @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. - * - * @param dn The distinguished name to rebind. - * @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 - */ - 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. - * - * @param dn The distinguished name to rebind. - * @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 - */ - void rebind(String dn, Object obj, Attributes attributes) throws NamingException; - - /** - * 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. - * @throws ContextNotEmptyException if newDn is already bound - * @throws NamingException if any other error occurs. - */ - void rename(final Name oldDn, final Name newDn) throws NamingException; - - /** - * 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. - * @throws ContextNotEmptyException if newDn is already bound - * @throws NamingException if any other error occurs. - */ - void rename(final String oldDn, final String newDn) throws NamingException; - - /** - * 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 NamingException if any other error occurs. - * @see #lookup(Name) - * @see #modifyAttributes(DirContextOperations) - * @since 1.2 - */ - DirContextOperations lookupContext(Name dn) throws NamingException, ClassCastException; - - /** - * 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 NamingException if any other error occurs. - * @see #lookup(String) - * @see #modifyAttributes(DirContextOperations) - * @since 1.2 - */ - DirContextOperations lookupContext(String dn) throws NamingException, ClassCastException; - - /** - * 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 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 NamingException if any other error occurs. - * @since 1.2 - * @see #lookupContext(Name) - * @see DirContextAdapter - */ - 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. - *

- * 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. - * @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. - *

- * 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. - * @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. - *

- * 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. - * @since 1.3 - * @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. - *

- * 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. - * @since 1.3 - * @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. - * - * @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. - * @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)} - */ - 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. - * - * @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. - * @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)} - */ - 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. - * - * @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 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) - * @since 1.3.1 - * @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, - 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. - * - * @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 errorCallback the callback that will be called if an exception is caught. - * @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)} - */ - 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. - * - * @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) - * @since 1.3.1 - * @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); - - /** - * 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. - * @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)} - */ - 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. - *

- * 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. - * @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 NamingException if something went wrong in authentication. - * - * @since 2.0 - * @see org.springframework.ldap.query.LdapQueryBuilder - */ - 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. - *

- * 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. - * @throws IncorrectResultSizeDataAccessException if more than one users were found - * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was found - * @throws NamingException if something went wrong in authentication. - * - * @since 2.0 - * @see org.springframework.ldap.query.LdapQueryBuilder - */ - 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. - * @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 - * @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. - * @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 - * @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. - * @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 - * @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. - * @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 - * @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. - * - * @param query the LDAP query specification. - * @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 - * @see org.springframework.ldap.core.support.CountNameClassPairCallbackHandler - */ - 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. - * - * @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 - */ - 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. - * - * @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 - */ - 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. - * @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 - * @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. - * @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 - * @since 2.0 - * @see org.springframework.ldap.query.LdapQueryBuilder - */ - T searchForObject(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. - * - * @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}. - * 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. - * - * @throws org.springframework.ldap.NamingException on error. - * @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. - * - * @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. - * @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}. - * - * @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. - * @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. - * - * @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 - * - * @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. - * - * @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 clazz The Java type to return - * @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. - * - * @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 clazz The Java type to return - * @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. - *

- * 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 - */ - 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 - * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. - * @param query the LDAP query specification - * @param clazz The Java type to return - * @param The Java type to return - * @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 - */ - T findOne(LdapQuery query, Class clazz); - - /** - * Get the configured ObjectDirectoryMapper. For internal use. - * - * @return the configured ObjectDirectoryMapper. - * @since 2.0 - */ - ObjectDirectoryMapper getObjectDirectoryMapper(); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.ldap.ContextNotEmptyException; +import org.springframework.ldap.NamingException; +import org.springframework.ldap.core.support.AbstractContextSource; +import org.springframework.ldap.filter.Filter; +import org.springframework.ldap.odm.core.ObjectDirectoryMapper; +import org.springframework.ldap.query.LdapQuery; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.Binding; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.directory.Attributes; +import javax.naming.directory.ModificationItem; +import javax.naming.directory.SearchControls; +import java.util.List; + +/** + * Interface that specifies a basic set of LDAP operations. Implemented by + * LdapTemplate, but it might be a useful option to use this interface in order + * to enhance testability. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public interface LdapOperations { + /** + * 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 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. + */ + 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 + * {@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. + * @throws NamingException if any error occurs. Note that a + * 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. + * @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) + */ + 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. + * @return the result from the ContextExecutor's operation. + * @throws NamingException if the operation resulted in a + * NamingException. + * @see #bind(Name, Object, Attributes) + * @see #unbind(Name) + * @see #rebind(Name, Object, Attributes) + * @see #rename(Name, Name) + * @see #modifyAttributes(Name, ModificationItem[]) + */ + 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @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. + * @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. + */ + 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. + * + * @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. + * @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. + */ + 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. + * + * @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. + * @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, 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. + * + * @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. + * @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, 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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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 + * 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. + * @throws NamingException if any error occurs. Note that a + * 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 + * 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. + * @throws NamingException if any error occurs. Note that a + * 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 + * 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. + * @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. + */ + 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 + * 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. + * @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. + */ + 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 + * 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. + * @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. + */ + 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 + * 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. + * @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. + */ + 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 + * 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. + * @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. + */ + 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 + * 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. + * @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. + */ + 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. + * + * @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. + * @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, 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. + * + * @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. + * @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, 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. + * + * @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. + * @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, 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. + * + * @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. + * @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, 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. + * + * @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(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. + * + * @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, 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 + * 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. + * @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, AttributesMapper 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. + * @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, 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. + * + * @param base The base DN where the list should be performed. + * @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. + */ + 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. + * + * @param base The base DN where the list should be performed. + * @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. + */ + 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @param base The base DN where the list should be performed. + * @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. + */ + List list(String base) throws NamingException; + + /** + * 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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @param base The base DN where the list should be performed. + * @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. + */ + 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. + * + * @param base The base DN where the list should be performed. + * @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. + */ + 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @param base The base DN where the list should be performed. + * @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. + */ + List listBindings(final String base) throws NamingException; + + /** + * 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. + * @throws NamingException if any error occurs. Note that a + * 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. + * + * @param base The base DN where the list should be performed. + * @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. + */ + 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. + * + * @param base The base DN where the list should be performed. + * @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. + */ + 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. + * + * @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. + * @see #lookupContext(Name) + * @see AbstractContextSource#setDirObjectFactory(Class) + */ + 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. + * + * @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. + * @see #lookupContext(String) + * @see AbstractContextSource#setDirObjectFactory(Class) + */ + Object lookup(String dn) throws NamingException; + + /** + * 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. + * @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. + * + * @param dn The distinguished name to find. + * @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. + * + * @param dn The distinguished name to find. + * @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. + * + * @param dn The distinguished name to find. + * @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, ContextMapper mapper) throws NamingException; + + /** + * 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. + * @return the object returned from the mapper. + * @throws NamingException if any error occurs. + */ + T lookup(Name dn, String[] attributes, AttributesMapper mapper) throws NamingException; + + /** + * 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. + * @return the object returned from the mapper. + * @throws NamingException if any error occurs. + */ + T lookup(String dn, String[] attributes, AttributesMapper mapper) throws NamingException; + + /** + * 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. + * @return the object returned from the mapper. + * @throws NamingException if any error occurs. + */ + T lookup(Name dn, String[] attributes, ContextMapper mapper) throws NamingException; + + /** + * 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. + * @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. + * + * @param dn The distinguished name of the node to modify. + * @param mods The modifications to perform. + * @throws NamingException if any error occurs. + * @see #modifyAttributes(DirContextOperations) + */ + void modifyAttributes(Name dn, ModificationItem[] mods) throws NamingException; + + /** + * 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. + * @see #modifyAttributes(DirContextOperations) + */ + 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. + * + * @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. + * @param attributes The attributes to bind, may be null. + * @throws NamingException if any error occurs. + * @see DirContextAdapter + */ + 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. + * + * @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. + * @param attributes The attributes to bind, may be null. + * @throws NamingException if any error occurs. + * @see DirContextAdapter + */ + 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. + * + * @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. + * + * @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. + * + * @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. + * @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. + * + * @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. + * @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. + * + * @param dn The distinguished name to rebind. + * @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 + */ + 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. + * + * @param dn The distinguished name to rebind. + * @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 + */ + void rebind(String dn, Object obj, Attributes attributes) throws NamingException; + + /** + * 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. + * @throws ContextNotEmptyException if newDn is already bound + * @throws NamingException if any other error occurs. + */ + void rename(final Name oldDn, final Name newDn) throws NamingException; + + /** + * 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. + * @throws ContextNotEmptyException if newDn is already bound + * @throws NamingException if any other error occurs. + */ + void rename(final String oldDn, final String newDn) throws NamingException; + + /** + * 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 NamingException if any other error occurs. + * @see #lookup(Name) + * @see #modifyAttributes(DirContextOperations) + * @since 1.2 + */ + DirContextOperations lookupContext(Name dn) throws NamingException, ClassCastException; + + /** + * 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 NamingException if any other error occurs. + * @see #lookup(String) + * @see #modifyAttributes(DirContextOperations) + * @since 1.2 + */ + DirContextOperations lookupContext(String dn) throws NamingException, ClassCastException; + + /** + * 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 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 NamingException if any other error occurs. + * @since 1.2 + * @see #lookupContext(Name) + * @see DirContextAdapter + */ + 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. + *

+ * 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. + * @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. + *

+ * 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. + * @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. + *

+ * 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. + * @since 1.3 + * @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. + *

+ * 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. + * @since 1.3 + * @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. + * + * @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. + * @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)} + */ + 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. + * + * @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. + * @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)} + */ + 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. + * + * @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 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) + * @since 1.3.1 + * @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, + 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. + * + * @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 errorCallback the callback that will be called if an exception is caught. + * @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)} + */ + 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. + * + * @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) + * @since 1.3.1 + * @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); + + /** + * 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. + * @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)} + */ + 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. + *

+ * 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. + * @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 NamingException if something went wrong in authentication. + * + * @since 2.0 + * @see org.springframework.ldap.query.LdapQueryBuilder + */ + 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. + *

+ * 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. + * @throws IncorrectResultSizeDataAccessException if more than one users were found + * @throws org.springframework.dao.EmptyResultDataAccessException if only one user was found + * @throws NamingException if something went wrong in authentication. + * + * @since 2.0 + * @see org.springframework.ldap.query.LdapQueryBuilder + */ + 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. + * @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 + * @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. + * @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 + * @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. + * @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 + * @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. + * @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 + * @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. + * + * @param query the LDAP query specification. + * @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 + * @see org.springframework.ldap.core.support.CountNameClassPairCallbackHandler + */ + 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. + * + * @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 + */ + 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. + * + * @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 + */ + 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. + * @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 + * @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. + * @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 + * @since 2.0 + * @see org.springframework.ldap.query.LdapQueryBuilder + */ + T searchForObject(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. + * + * @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}. + * 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. + * + * @throws org.springframework.ldap.NamingException on error. + * @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. + * + * @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. + * @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}. + * + * @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. + * @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. + * + * @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 + * + * @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. + * + * @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 clazz The Java type to return + * @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. + * + * @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 clazz The Java type to return + * @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. + *

+ * 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 + */ + 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 + * {@link org.springframework.ldap.odm.annotations.Entry} and associated annotations. + * @param query the LDAP query specification + * @param clazz The Java type to return + * @param The Java type to return + * @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 + */ + T findOne(LdapQuery query, Class clazz); + + /** + * 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 91e9fbf7..64065738 100644 --- a/core/src/main/java/org/springframework/ldap/core/LdapRdn.java +++ b/core/src/main/java/org/springframework/ldap/core/LdapRdn.java @@ -1,308 +1,308 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.springframework.ldap.BadLdapGrammarException; -import org.springframework.util.ObjectUtils; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -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(); - - /** - * Default constructor. Create an empty, uninitialized LdapRdn. - */ - public LdapRdn() { - } - - /** - * Parse the supplied string and construct this instance accordingly. - * - * @param string the string to parse. - */ - public LdapRdn(String string) { - DnParser parser = DefaultDnParserFactory.createDnParser(string); - LdapRdn rdn; - try { - rdn = parser.rdn(); - } - catch (ParseException e) { - throw new BadLdapGrammarException("Failed to parse Rdn", e); - } - catch (TokenMgrError e) { - throw new BadLdapGrammarException("Failed to parse Rdn", e); - } - this.components = rdn.components; - } - - /** - * Construct an LdapRdn using the supplied key and value. - * - * @param key the attribute name. - * @param value the attribute value. - */ - public LdapRdn(String key, String value) { - components.put(key, new LdapRdnComponent(key, value)); - } - - /** - * Add an LdapRdnComponent to this LdapRdn. - * - * @param rdnComponent the LdapRdnComponent to add.s - */ - public void addComponent(LdapRdnComponent rdnComponent) { - components.put(rdnComponent.getKey(), rdnComponent); - } - - /** - * Gets all components in this LdapRdn. - * - * @return the List of all LdapRdnComponents composing this LdapRdn. - */ - public List getComponents() { - return new ArrayList(components.values()); - } - - /** - * 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) { - throw new IndexOutOfBoundsException("No components"); - } - - return components.values().iterator().next(); - } - - /** - * 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()) { - throw new IndexOutOfBoundsException(); - } - - return (LdapRdnComponent) new ArrayList(components.values()).get(idx); - } - - /** - * 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. - */ - public String getLdapEncoded() { - if (components.size() == 0) { - throw new IndexOutOfBoundsException("No components in Rdn."); - } - StringBuffer sb = new StringBuffer(DEFAULT_BUFFER_SIZE); - for (Iterator iter = components.values().iterator(); iter.hasNext();) { - LdapRdnComponent component = (LdapRdnComponent) iter.next(); - sb.append(component.encodeLdap()); - if (iter.hasNext()) { - sb.append("+"); - } - } - - return sb.toString(); - } - - /** - * 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() { - StringBuffer sb = new StringBuffer(DEFAULT_BUFFER_SIZE); - for (Iterator iter = components.values().iterator(); iter.hasNext();) { - LdapRdnComponent component = (LdapRdnComponent) iter.next(); - sb.append(component.encodeUrl()); - if (iter.hasNext()) { - sb.append("+"); - } - } - - return sb.toString(); - } - - /** - * Compare this LdapRdn to another object. - * - * @param obj the object to compare to. - * @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()) { - return this.components.size() - that.components.size(); - } - - Set> theseEntries = this.components.entrySet(); - for (Map.Entry oneEntry : theseEntries) { - LdapRdnComponent thatEntry = that.components.get(oneEntry.getKey()); - if(thatEntry == null) { - return -1; - } - - int compared = oneEntry.getValue().compareTo(thatEntry); - if(compared != 0) { - return compared; - } - } - - return 0; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - public boolean equals(Object obj) { - if (obj == null || obj.getClass() != this.getClass()) { - return false; - } - - LdapRdn that = (LdapRdn) obj; - - if(this.components.size() != that.components.size()) { - return false; - } - - Set> theseEntries = this.components.entrySet(); - for (Map.Entry oneEntry : theseEntries) { - if(!oneEntry.getValue().equals(that.components.get(oneEntry.getKey()))) { - return false; - } - } - - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - public int hashCode() { - return this.getClass().hashCode() ^ new HashSet(getComponents()).hashCode(); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - public String toString() { - return getLdapEncoded(); - } - - /** - * 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. - */ - public String getValue() { - return getComponent().getValue(); - } - - /** - * 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. - */ - public String getKey() { - return getComponent().getKey(); - } - - /** - * 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. - */ - public String getValue(String key) { - for (Iterator iter = components.values().iterator(); iter.hasNext();) { - LdapRdnComponent component = (LdapRdnComponent) iter.next(); - if (ObjectUtils.nullSafeEquals(component.getKey(), key)) { - return component.getValue(); - } - } - - throw new IllegalArgumentException("No RdnComponent with the key " + key); - } - - /** - * 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()); - for (Iterator iterator = components.values().iterator(); iterator.hasNext();) { - LdapRdnComponent rdnComponent = (LdapRdnComponent) iterator.next(); - mapWithImmutableRdns.put(rdnComponent.getKey(), rdnComponent.immutableLdapRdnComponent()); - } - Map unmodifiableMapOfImmutableRdns = Collections.unmodifiableMap(mapWithImmutableRdns); - LdapRdn immutableRdn = new LdapRdn(); - immutableRdn.components = unmodifiableMapOfImmutableRdns; - return immutableRdn; - } +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.springframework.ldap.BadLdapGrammarException; +import org.springframework.util.ObjectUtils; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +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(); + + /** + * Default constructor. Create an empty, uninitialized LdapRdn. + */ + public LdapRdn() { + } + + /** + * Parse the supplied string and construct this instance accordingly. + * + * @param string the string to parse. + */ + public LdapRdn(String string) { + DnParser parser = DefaultDnParserFactory.createDnParser(string); + LdapRdn rdn; + try { + rdn = parser.rdn(); + } + catch (ParseException e) { + throw new BadLdapGrammarException("Failed to parse Rdn", e); + } + catch (TokenMgrError e) { + throw new BadLdapGrammarException("Failed to parse Rdn", e); + } + this.components = rdn.components; + } + + /** + * Construct an LdapRdn using the supplied key and value. + * + * @param key the attribute name. + * @param value the attribute value. + */ + public LdapRdn(String key, String value) { + components.put(key, new LdapRdnComponent(key, value)); + } + + /** + * Add an LdapRdnComponent to this LdapRdn. + * + * @param rdnComponent the LdapRdnComponent to add.s + */ + public void addComponent(LdapRdnComponent rdnComponent) { + components.put(rdnComponent.getKey(), rdnComponent); + } + + /** + * Gets all components in this LdapRdn. + * + * @return the List of all LdapRdnComponents composing this LdapRdn. + */ + public List getComponents() { + return new ArrayList(components.values()); + } + + /** + * 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) { + throw new IndexOutOfBoundsException("No components"); + } + + return components.values().iterator().next(); + } + + /** + * 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()) { + throw new IndexOutOfBoundsException(); + } + + return (LdapRdnComponent) new ArrayList(components.values()).get(idx); + } + + /** + * 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. + */ + public String getLdapEncoded() { + if (components.size() == 0) { + throw new IndexOutOfBoundsException("No components in Rdn."); + } + StringBuffer sb = new StringBuffer(DEFAULT_BUFFER_SIZE); + for (Iterator iter = components.values().iterator(); iter.hasNext();) { + LdapRdnComponent component = (LdapRdnComponent) iter.next(); + sb.append(component.encodeLdap()); + if (iter.hasNext()) { + sb.append("+"); + } + } + + return sb.toString(); + } + + /** + * 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() { + StringBuffer sb = new StringBuffer(DEFAULT_BUFFER_SIZE); + for (Iterator iter = components.values().iterator(); iter.hasNext();) { + LdapRdnComponent component = (LdapRdnComponent) iter.next(); + sb.append(component.encodeUrl()); + if (iter.hasNext()) { + sb.append("+"); + } + } + + return sb.toString(); + } + + /** + * Compare this LdapRdn to another object. + * + * @param obj the object to compare to. + * @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()) { + return this.components.size() - that.components.size(); + } + + Set> theseEntries = this.components.entrySet(); + for (Map.Entry oneEntry : theseEntries) { + LdapRdnComponent thatEntry = that.components.get(oneEntry.getKey()); + if(thatEntry == null) { + return -1; + } + + int compared = oneEntry.getValue().compareTo(thatEntry); + if(compared != 0) { + return compared; + } + } + + return 0; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + public boolean equals(Object obj) { + if (obj == null || obj.getClass() != this.getClass()) { + return false; + } + + LdapRdn that = (LdapRdn) obj; + + if(this.components.size() != that.components.size()) { + return false; + } + + Set> theseEntries = this.components.entrySet(); + for (Map.Entry oneEntry : theseEntries) { + if(!oneEntry.getValue().equals(that.components.get(oneEntry.getKey()))) { + return false; + } + } + + return true; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + public int hashCode() { + return this.getClass().hashCode() ^ new HashSet(getComponents()).hashCode(); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + public String toString() { + return getLdapEncoded(); + } + + /** + * 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. + */ + public String getValue() { + return getComponent().getValue(); + } + + /** + * 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. + */ + public String getKey() { + return getComponent().getKey(); + } + + /** + * 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. + */ + public String getValue(String key) { + for (Iterator iter = components.values().iterator(); iter.hasNext();) { + LdapRdnComponent component = (LdapRdnComponent) iter.next(); + if (ObjectUtils.nullSafeEquals(component.getKey(), key)) { + return component.getValue(); + } + } + + throw new IllegalArgumentException("No RdnComponent with the key " + key); + } + + /** + * 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()); + for (Iterator iterator = components.values().iterator(); iterator.hasNext();) { + LdapRdnComponent rdnComponent = (LdapRdnComponent) iterator.next(); + mapWithImmutableRdns.put(rdnComponent.getKey(), rdnComponent.immutableLdapRdnComponent()); + } + 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/NameClassPairCallbackHandler.java b/core/src/main/java/org/springframework/ldap/core/NameClassPairCallbackHandler.java index 4e751db5..079dc6bf 100644 --- a/core/src/main/java/org/springframework/ldap/core/NameClassPairCallbackHandler.java +++ b/core/src/main/java/org/springframework/ldap/core/NameClassPairCallbackHandler.java @@ -1,43 +1,43 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -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(). - * - * @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. - * @throws NamingException if an error occurs. - */ - void handleNameClassPair(NameClassPair nameClassPair) throws NamingException; -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +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(). + * + * @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. + * @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 5a645bf4..c9b1746e 100644 --- a/core/src/main/java/org/springframework/ldap/core/NameClassPairMapper.java +++ b/core/src/main/java/org/springframework/ldap/core/NameClassPairMapper.java @@ -1,44 +1,44 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import javax.naming.NameClassPair; -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. - * @return and Object built from the NameClassPair. - * @throws NamingException - * if one is encountered in the operation. - */ - T mapFromNameClassPair(NameClassPair nameClassPair) - throws NamingException; -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import javax.naming.NameClassPair; +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. + * @return and Object built from the NameClassPair. + * @throws NamingException + * if one is encountered in the operation. + */ + 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 0586459f..f8681045 100644 --- a/core/src/main/java/org/springframework/ldap/core/ObjectRetrievalException.java +++ b/core/src/main/java/org/springframework/ldap/core/ObjectRetrievalException.java @@ -1,53 +1,53 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.springframework.ldap.NamingException; - -/** - * Thrown by a {@link ContextMapperCallbackHandler} when it cannot retrieve an - * object from the given Binding. - * - * @author Ulrik Sandberg - * @since 1.2 - */ -public class ObjectRetrievalException extends NamingException { - - /** - * Create a new ObjectRetrievalException. - * - * @param msg - * the detail message - * - */ - public ObjectRetrievalException(String msg) { - super(msg); - } - - /** - * Create a new ObjectRetrievalException. - * - * @param msg - * the detail message - * @param cause - * the root cause (if any) - */ - public ObjectRetrievalException(String msg, Throwable cause) { - super(msg, cause); - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.springframework.ldap.NamingException; + +/** + * Thrown by a {@link ContextMapperCallbackHandler} when it cannot retrieve an + * object from the given Binding. + * + * @author Ulrik Sandberg + * @since 1.2 + */ +public class ObjectRetrievalException extends NamingException { + + /** + * Create a new ObjectRetrievalException. + * + * @param msg + * the detail message + * + */ + public ObjectRetrievalException(String msg) { + super(msg); + } + + /** + * Create a new ObjectRetrievalException. + * + * @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 5ecd07c4..f94c6a15 100644 --- a/core/src/main/java/org/springframework/ldap/core/SearchExecutor.java +++ b/core/src/main/java/org/springframework/ldap/core/SearchExecutor.java @@ -1,52 +1,52 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core; - -import javax.naming.NamingEnumeration; -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: - * - *

- * SearchExecutor executor = new SearchExecutor(){
- *   public NamingEnumeration executeSearch(DirContext ctx) throws NamingException{
- *     return ctx.search(dn, filter, searchControls);
- *   }
- * }
- * 
- * - * @see org.springframework.ldap.core.LdapTemplate#search(SearchExecutor, - * 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. - */ - NamingEnumeration executeSearch(DirContext ctx) - throws NamingException; -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core; + +import javax.naming.NamingEnumeration; +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: + * + *
+ * SearchExecutor executor = new SearchExecutor(){
+ *   public NamingEnumeration executeSearch(DirContext ctx) throws NamingException{
+ *     return ctx.search(dn, filter, searchControls);
+ *   }
+ * }
+ * 
+ * + * @see org.springframework.ldap.core.LdapTemplate#search(SearchExecutor, + * 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. + */ + NamingEnumeration executeSearch(DirContext ctx) + throws NamingException; +} 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 1ecb5a04..ce0c9ee4 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 @@ -1,206 +1,206 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import org.springframework.ldap.UncategorizedLdapException; -import org.springframework.ldap.core.DirContextProxy; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.ldap.LdapContext; -import javax.naming.ldap.StartTlsRequest; -import javax.naming.ldap.StartTlsResponse; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSocketFactory; -import java.io.IOException; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -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. - *

- * 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. - *

- * 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. - * - * @author Mattias Hellborg Arthursson - */ -public abstract class AbstractTlsDirContextAuthenticationStrategy implements DirContextAuthenticationStrategy { - - /** Hostname verifier to use for cert subject validation */ - private HostnameVerifier hostnameVerifier; - - /** Flag to cause graceful shutdown required by some LDAP DSAs */ - private boolean shutdownTlsGracefully = false; - - /** 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. - */ - 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. - * - * @param hostnameVerifier The HostnameVerifier to use, if any. - */ - public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { - this.hostnameVerifier = hostnameVerifier; - } - - /** - * 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) - */ - 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) - */ - public final DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) - throws NamingException { - - if (ctx instanceof LdapContext) { - final LdapContext ldapCtx = (LdapContext) ctx; - final StartTlsResponse tlsResponse = (StartTlsResponse) ldapCtx.extendedOperation(new StartTlsRequest()); - try { - if (hostnameVerifier != null) { - tlsResponse.setHostnameVerifier(hostnameVerifier); - } - 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)); - } - else { - return ctx; - } - } - catch (IOException e) { - LdapUtils.closeContext(ctx); - throw new UncategorizedLdapException("Failed to negotiate TLS session", e); - } - } - else { - throw new IllegalArgumentException( - "Processed Context must be an LDAPv3 context, i.e. an LdapContext implementation"); - } - - } - - /** - * 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. - * @throws NamingException if any error occurs. - */ - protected abstract void applyAuthentication(LdapContext ctx, String userDn, String password) throws NamingException; - - private static final class TlsAwareDirContextProxy implements DirContextProxy, InvocationHandler { - - private static final String GET_TARGET_CONTEXT_METHOD_NAME = "getTargetContext"; - - private static final String CLOSE_METHOD_NAME = "close"; - - private final LdapContext target; - - private final StartTlsResponse tlsResponse; - - public TlsAwareDirContextProxy(LdapContext target, StartTlsResponse tlsResponse) { - this.target = target; - this.tlsResponse = tlsResponse; - } - - public DirContext getTargetContext() { - return target; - } - - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - if (method.getName().equals(CLOSE_METHOD_NAME)) { - tlsResponse.close(); - return method.invoke(target, args); - } - else if (method.getName().equals(GET_TARGET_CONTEXT_METHOD_NAME)) { - return target; - } - else { - return method.invoke(target, args); - } - } - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import org.springframework.ldap.UncategorizedLdapException; +import org.springframework.ldap.core.DirContextProxy; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.ldap.LdapContext; +import javax.naming.ldap.StartTlsRequest; +import javax.naming.ldap.StartTlsResponse; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSocketFactory; +import java.io.IOException; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +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. + *

+ * 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. + *

+ * 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. + * + * @author Mattias Hellborg Arthursson + */ +public abstract class AbstractTlsDirContextAuthenticationStrategy implements DirContextAuthenticationStrategy { + + /** Hostname verifier to use for cert subject validation */ + private HostnameVerifier hostnameVerifier; + + /** Flag to cause graceful shutdown required by some LDAP DSAs */ + private boolean shutdownTlsGracefully = false; + + /** 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. + */ + 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. + * + * @param hostnameVerifier The HostnameVerifier to use, if any. + */ + public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { + this.hostnameVerifier = hostnameVerifier; + } + + /** + * 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) + */ + 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) + */ + public final DirContext processContextAfterCreation(DirContext ctx, String userDn, String password) + throws NamingException { + + if (ctx instanceof LdapContext) { + final LdapContext ldapCtx = (LdapContext) ctx; + final StartTlsResponse tlsResponse = (StartTlsResponse) ldapCtx.extendedOperation(new StartTlsRequest()); + try { + if (hostnameVerifier != null) { + tlsResponse.setHostnameVerifier(hostnameVerifier); + } + 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)); + } + else { + return ctx; + } + } + catch (IOException e) { + LdapUtils.closeContext(ctx); + throw new UncategorizedLdapException("Failed to negotiate TLS session", e); + } + } + else { + throw new IllegalArgumentException( + "Processed Context must be an LDAPv3 context, i.e. an LdapContext implementation"); + } + + } + + /** + * 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. + * @throws NamingException if any error occurs. + */ + protected abstract void applyAuthentication(LdapContext ctx, String userDn, String password) throws NamingException; + + private static final class TlsAwareDirContextProxy implements DirContextProxy, InvocationHandler { + + private static final String GET_TARGET_CONTEXT_METHOD_NAME = "getTargetContext"; + + private static final String CLOSE_METHOD_NAME = "close"; + + private final LdapContext target; + + private final StartTlsResponse tlsResponse; + + public TlsAwareDirContextProxy(LdapContext target, StartTlsResponse tlsResponse) { + this.target = target; + this.tlsResponse = tlsResponse; + } + + public DirContext getTargetContext() { + return target; + } + + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + if (method.getName().equals(CLOSE_METHOD_NAME)) { + tlsResponse.close(); + return method.invoke(target, args); + } + else if (method.getName().equals(GET_TARGET_CONTEXT_METHOD_NAME)) { + return target; + } + else { + 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 935ece3a..fdb462db 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 @@ -1,85 +1,85 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core.support; - -import org.springframework.ldap.core.DirContextProcessor; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import java.util.ArrayList; -import java.util.LinkedList; -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. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public class AggregateDirContextProcessor implements DirContextProcessor { - - private List dirContextProcessors = new LinkedList(); - - /** - * Add the supplied DirContextProcessor to the list of managed objects. - * - * @param processor - * the DirContextpProcessor to add. - */ - public void addDirContextProcessor(DirContextProcessor processor) { - dirContextProcessors.add(processor); - } - - /** - * Get the list of managed {@link DirContextProcessor} instances. - * - * @return the managed list of {@link DirContextProcessor} instances. - */ - public List getDirContextProcessors() { - return dirContextProcessors; - } - - /** - * Set the list of managed {@link DirContextProcessor} instances. - * - * @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) - */ - public void preProcess(DirContext ctx) throws NamingException { - for (DirContextProcessor processor : dirContextProcessors) { - processor.preProcess(ctx); - } - } - - /* - * @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); - } - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core.support; + +import org.springframework.ldap.core.DirContextProcessor; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import java.util.ArrayList; +import java.util.LinkedList; +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. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public class AggregateDirContextProcessor implements DirContextProcessor { + + private List dirContextProcessors = new LinkedList(); + + /** + * Add the supplied DirContextProcessor to the list of managed objects. + * + * @param processor + * the DirContextpProcessor to add. + */ + public void addDirContextProcessor(DirContextProcessor processor) { + dirContextProcessors.add(processor); + } + + /** + * Get the list of managed {@link DirContextProcessor} instances. + * + * @return the managed list of {@link DirContextProcessor} instances. + */ + public List getDirContextProcessors() { + return dirContextProcessors; + } + + /** + * Set the list of managed {@link DirContextProcessor} instances. + * + * @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) + */ + public void preProcess(DirContext ctx) throws NamingException { + for (DirContextProcessor processor : dirContextProcessors) { + processor.preProcess(ctx); + } + } + + /* + * @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/BaseLdapPathAware.java b/core/src/main/java/org/springframework/ldap/core/support/BaseLdapPathAware.java index a7a0fb67..73a3f299 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 @@ -1,51 +1,51 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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. - *

- * 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. - */ -public interface BaseLdapPathAware { - - /** - * Set the base LDAP path specified in the current - * ApplicationContext. - * @param baseLdapPath the base path used in the ContextSource - */ - void setBaseLdapPath(DistinguishedName baseLdapPath); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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. + *

+ * 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. + */ +public interface BaseLdapPathAware { + + /** + * 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 aedadcfa..772ab15c 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 @@ -1,183 +1,183 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core.support; - -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.config.BeanPostProcessor; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.core.Ordered; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.util.StringUtils; - -import javax.naming.ldap.LdapName; -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. - *

- * 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 - */ -public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware, Ordered { - - private ApplicationContext applicationContext; - - private LdapName basePath; - - private String baseLdapPathSourceName; - - private int order = Ordered.LOWEST_PRECEDENCE; - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) { - if(bean instanceof BaseLdapNameAware) { - BaseLdapNameAware baseLdapNameAware = (BaseLdapNameAware) bean; - - if (basePath != null) { - baseLdapNameAware.setBaseLdapPath(LdapUtils.newLdapName(basePath)); - } - else { - BaseLdapPathSource ldapPathSource = getBaseLdapPathSourceFromApplicationContext(); - baseLdapNameAware.setBaseLdapPath(LdapUtils.newLdapName(ldapPathSource.getBaseLdapName())); - } - } else if (bean instanceof BaseLdapPathAware) { - BaseLdapPathAware baseLdapPathAware = (BaseLdapPathAware) bean; - - if (basePath != null) { - baseLdapPathAware.setBaseLdapPath(new DistinguishedName(basePath)); - } - else { - BaseLdapPathSource ldapPathSource = getBaseLdapPathSourceFromApplicationContext(); - baseLdapPathAware.setBaseLdapPath(ldapPathSource.getBaseLdapPath().immutableDistinguishedName()); - } - } - return bean; - } - - BaseLdapPathSource getBaseLdapPathSourceFromApplicationContext() { - if (StringUtils.hasLength(baseLdapPathSourceName)) { - return applicationContext.getBean(baseLdapPathSourceName, BaseLdapPathSource.class); - } - - Collection beans = applicationContext.getBeansOfType(BaseLdapPathSource.class).values(); - if (beans.isEmpty()) { - throw new NoSuchBeanDefinitionException("No BaseLdapPathSource implementation definition found"); - } else if (beans.size() == 1) { - return beans.iterator().next(); - } else { - BaseLdapPathSource found = null; - - // Try to find the correct one - for (BaseLdapPathSource bean : beans) { - 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'"); - } - - found = bean; - } - } - - 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'"); - } - - return found; - } - } - - @Override - public Object postProcessAfterInitialization(Object bean, String beanName) { - // Do nothing for this implementation - return bean; - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - /** - * 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. - */ - public void setBasePath(DistinguishedName basePath) { - this.basePath = LdapUtils.newLdapName(basePath); - } - - public void setBasePath(String basePath) { - this.basePath = LdapUtils.newLdapName(basePath); - } - - /** - * 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; - } - - /** - * Set the order value of this object for sorting purposes. - * - * @param order the order of this instance. Defaults to Ordered.LOWEST_PRECEDENCE. - * @see Ordered - * @since 1.3.2 - */ - public void setOrder(int order) { - this.order = order; - } - - public int getOrder() { - return order; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core.support; + +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.BeanPostProcessor; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.Ordered; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.util.StringUtils; + +import javax.naming.ldap.LdapName; +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. + *

+ * 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 + */ +public class BaseLdapPathBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware, Ordered { + + private ApplicationContext applicationContext; + + private LdapName basePath; + + private String baseLdapPathSourceName; + + private int order = Ordered.LOWEST_PRECEDENCE; + + @Override + public Object postProcessBeforeInitialization(Object bean, String beanName) { + if(bean instanceof BaseLdapNameAware) { + BaseLdapNameAware baseLdapNameAware = (BaseLdapNameAware) bean; + + if (basePath != null) { + baseLdapNameAware.setBaseLdapPath(LdapUtils.newLdapName(basePath)); + } + else { + BaseLdapPathSource ldapPathSource = getBaseLdapPathSourceFromApplicationContext(); + baseLdapNameAware.setBaseLdapPath(LdapUtils.newLdapName(ldapPathSource.getBaseLdapName())); + } + } else if (bean instanceof BaseLdapPathAware) { + BaseLdapPathAware baseLdapPathAware = (BaseLdapPathAware) bean; + + if (basePath != null) { + baseLdapPathAware.setBaseLdapPath(new DistinguishedName(basePath)); + } + else { + BaseLdapPathSource ldapPathSource = getBaseLdapPathSourceFromApplicationContext(); + baseLdapPathAware.setBaseLdapPath(ldapPathSource.getBaseLdapPath().immutableDistinguishedName()); + } + } + return bean; + } + + BaseLdapPathSource getBaseLdapPathSourceFromApplicationContext() { + if (StringUtils.hasLength(baseLdapPathSourceName)) { + return applicationContext.getBean(baseLdapPathSourceName, BaseLdapPathSource.class); + } + + Collection beans = applicationContext.getBeansOfType(BaseLdapPathSource.class).values(); + if (beans.isEmpty()) { + throw new NoSuchBeanDefinitionException("No BaseLdapPathSource implementation definition found"); + } else if (beans.size() == 1) { + return beans.iterator().next(); + } else { + BaseLdapPathSource found = null; + + // Try to find the correct one + for (BaseLdapPathSource bean : beans) { + 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'"); + } + + found = bean; + } + } + + 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'"); + } + + return found; + } + } + + @Override + public Object postProcessAfterInitialization(Object bean, String beanName) { + // Do nothing for this implementation + return bean; + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + /** + * 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. + */ + public void setBasePath(DistinguishedName basePath) { + this.basePath = LdapUtils.newLdapName(basePath); + } + + public void setBasePath(String basePath) { + this.basePath = LdapUtils.newLdapName(basePath); + } + + /** + * 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; + } + + /** + * Set the order value of this object for sorting purposes. + * + * @param order the order of this instance. Defaults to Ordered.LOWEST_PRECEDENCE. + * @see Ordered + * @since 1.3.2 + */ + public void setOrder(int order) { + this.order = order; + } + + public int getOrder() { + return order; + } +} 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 26cf3332..8d163239 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 @@ -1,51 +1,51 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import javax.naming.NameClassPair; - -import org.springframework.ldap.core.NameClassPairCallbackHandler; - -/** - * A {@link NameClassPairCallbackHandler} for counting all returned entries. - * - * @author Mattias Hellborg Arthursson - * - */ -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() { - return noOfRows; - } - - /* - * (non-Javadoc) - * - * @see org.springframework.ldap.SearchResultCallbackHandler#handleSearchResult(javax.naming.directory.SearchResult) - */ - public void handleNameClassPair(NameClassPair nameClassPair) { - noOfRows++; - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import javax.naming.NameClassPair; + +import org.springframework.ldap.core.NameClassPairCallbackHandler; + +/** + * A {@link NameClassPairCallbackHandler} for counting all returned entries. + * + * @author Mattias Hellborg Arthursson + * + */ +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() { + return noOfRows; + } + + /* + * (non-Javadoc) + * + * @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/DefaultTlsDirContextAuthenticationStrategy.java b/core/src/main/java/org/springframework/ldap/core/support/DefaultTlsDirContextAuthenticationStrategy.java index 354a0ae7..1c98c594 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 @@ -1,43 +1,43 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import javax.naming.Context; -import javax.naming.NamingException; -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. - * - * @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 { - ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SIMPLE_AUTHENTICATION); - ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDn); - ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); - // Force a server call as we have updated the environment (gh-430, gh-502) - ctx.lookup(""); - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import javax.naming.Context; +import javax.naming.NamingException; +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. + * + * @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 { + ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, SIMPLE_AUTHENTICATION); + ctx.addToEnvironment(Context.SECURITY_PRINCIPAL, userDn); + ctx.addToEnvironment(Context.SECURITY_CREDENTIALS, password); + // Force a server call as we have updated the environment (gh-430, gh-502) + ctx.lookup(""); + } + +} 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 3d1e3a2e..f8b3df3f 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 @@ -1,85 +1,85 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import org.springframework.ldap.core.AuthenticationSource; -import org.springframework.ldap.core.ContextSource; - -import javax.naming.NamingException; -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. - * - * @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. - * @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. - */ - 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. - * @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 processContextAfterCreation(DirContext ctx, String userDn, String password) - throws NamingException; - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import org.springframework.ldap.core.AuthenticationSource; +import org.springframework.ldap.core.ContextSource; + +import javax.naming.NamingException; +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. + * + * @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. + * @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. + */ + 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. + * @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 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 3f79cd79..5644bd41 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 @@ -1,48 +1,48 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core.support; - -import java.util.Hashtable; - -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}. - * - * @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. - * @return a new InitialDirContext implementation. - */ - protected DirContext getDirContextInstance(Hashtable environment) - throws NamingException { - return new InitialDirContext(environment); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core.support; + +import java.util.Hashtable; + +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}. + * + * @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. + * @return a new InitialDirContext implementation. + */ + 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 72a228e4..4f766318 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 @@ -1,43 +1,43 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core.support; - -import javax.naming.Context; -import javax.naming.NamingException; -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. - * - * @author Mattias Hellborg Arthursson - * @see AbstractTlsDirContextAuthenticationStrategy - * @see AbstractContextSource - */ -public class ExternalTlsDirContextAuthenticationStrategy extends AbstractTlsDirContextAuthenticationStrategy { - - private static final String EXTERNAL_AUTHENTICATION = "EXTERNAL"; - - protected void applyAuthentication(LdapContext ctx, String userDn, String password) throws NamingException { - ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, EXTERNAL_AUTHENTICATION); - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core.support; + +import javax.naming.Context; +import javax.naming.NamingException; +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. + * + * @author Mattias Hellborg Arthursson + * @see AbstractTlsDirContextAuthenticationStrategy + * @see AbstractContextSource + */ +public class ExternalTlsDirContextAuthenticationStrategy extends AbstractTlsDirContextAuthenticationStrategy { + + private static final String EXTERNAL_AUTHENTICATION = "EXTERNAL"; + + protected void applyAuthentication(LdapContext ctx, String userDn, String password) throws NamingException { + ctx.addToEnvironment(Context.SECURITY_AUTHENTICATION, EXTERNAL_AUTHENTICATION); + } + +} 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 2bc64e04..d6699274 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 @@ -1,44 +1,44 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core.support; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -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}. - * - * @see org.springframework.ldap.core.support.AbstractContextSource - * - * @author Mattias Hellborg Arthursson - * @author Adam Skogman - * @author Ulrik Sandberg - */ -public class LdapContextSource extends AbstractContextSource { - - /* - * @see org.springframework.ldap.support.AbstractContextSource#getDirContextInstance(java.util.Hashtable) - */ - protected DirContext getDirContextInstance(Hashtable environment) - throws NamingException { - return new InitialLdapContext(environment, null); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core.support; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +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}. + * + * @see org.springframework.ldap.core.support.AbstractContextSource + * + * @author Mattias Hellborg Arthursson + * @author Adam Skogman + * @author Ulrik Sandberg + */ +public class LdapContextSource extends AbstractContextSource { + + /* + * @see org.springframework.ldap.support.AbstractContextSource#getDirContextInstance(java.util.Hashtable) + */ + protected DirContext getDirContextInstance(Hashtable environment) + throws NamingException { + return new InitialLdapContext(environment, null); + } +} 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 32e5a022..d3714a5b 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 @@ -1,55 +1,55 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import javax.naming.Context; -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. - * - * @author Mattias Hellborg Arthursson - */ -public class SimpleDirContextAuthenticationStrategy implements DirContextAuthenticationStrategy { - - private static final String SIMPLE_AUTHENTICATION = "simple"; - - /* - * (non-Javadoc) - * @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); - env.put(Context.SECURITY_PRINCIPAL, userDn); - env.put(Context.SECURITY_CREDENTIALS, password); - } - - /* - * (non-Javadoc) - * @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; - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import javax.naming.Context; +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. + * + * @author Mattias Hellborg Arthursson + */ +public class SimpleDirContextAuthenticationStrategy implements DirContextAuthenticationStrategy { + + private static final String SIMPLE_AUTHENTICATION = "simple"; + + /* + * (non-Javadoc) + * @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); + env.put(Context.SECURITY_PRINCIPAL, userDn); + env.put(Context.SECURITY_CREDENTIALS, password); + } + + /* + * (non-Javadoc) + * @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/filter/AbstractFilter.java b/core/src/main/java/org/springframework/ldap/filter/AbstractFilter.java index 066eddbe..63486bc1 100644 --- a/core/src/main/java/org/springframework/ldap/filter/AbstractFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/AbstractFilter.java @@ -1,40 +1,40 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -/** - * Convenience class that implements most of the methods in the Filter - * interface. - * - * @author Adam Skogman - */ -public abstract class AbstractFilter implements Filter { - - private static final int DEFAULT_BUFFER_SIZE = 256; - - @Override - public String encode() { - StringBuffer buf = new StringBuffer(DEFAULT_BUFFER_SIZE); - buf = encode(buf); - return buf.toString(); - } - - @Override - public String toString() { - return encode(); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +/** + * Convenience class that implements most of the methods in the Filter + * interface. + * + * @author Adam Skogman + */ +public abstract class AbstractFilter implements Filter { + + private static final int DEFAULT_BUFFER_SIZE = 256; + + @Override + public String encode() { + StringBuffer buf = new StringBuffer(DEFAULT_BUFFER_SIZE); + buf = encode(buf); + return buf.toString(); + } + + @Override + 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 6429aaf7..5321c04b 100644 --- a/core/src/main/java/org/springframework/ldap/filter/AndFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/AndFilter.java @@ -1,57 +1,57 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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 - */ -public class AndFilter extends BinaryLogicalFilter { - - private static final String AMPERSAND = "&"; - - /* - * @see org.springframework.ldap.filter.BinaryLogicalFilter#getLogicalOperator() - */ - protected String getLogicalOperator() { - return AMPERSAND; - } - - /** - * Add a query to the AND expression. - * - * @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; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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 + */ +public class AndFilter extends BinaryLogicalFilter { + + private static final String AMPERSAND = "&"; + + /* + * @see org.springframework.ldap.filter.BinaryLogicalFilter#getLogicalOperator() + */ + protected String getLogicalOperator() { + return AMPERSAND; + } + + /** + * Add a query to the AND expression. + * + * @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 6fa9dbaa..75acb477 100644 --- a/core/src/main/java/org/springframework/ldap/filter/BinaryLogicalFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/BinaryLogicalFilter.java @@ -1,99 +1,99 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.filter; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -/** - * Abstract superclass for binary logical operations, that is "AND" - * and "OR" operations. - * - * @author Mattias Hellborg Arthursson - */ -public abstract class BinaryLogicalFilter extends AbstractFilter { - - private List queryList = new LinkedList(); - - public StringBuffer encode(StringBuffer buff) { - if (queryList.size() <= 0) { - - // only output query if contains anything - return buff; - - } - else if (queryList.size() == 1) { - - // don't add the & - Filter query = queryList.get(0); - return query.encode(buff); - - } - else { - buff.append("(").append(getLogicalOperator()); - - for (Filter query : queryList) { - query.encode(buff); - } - - buff.append(")"); - - return buff; - } - } - - /** - * 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; - - BinaryLogicalFilter that = (BinaryLogicalFilter) o; - - if (queryList != null ? !queryList.equals(that.queryList) : that.queryList != null) return false; - - return true; - } - - @Override - public int hashCode() { - return queryList != null ? queryList.hashCode() : 0; - } - - /** - * Add a query to this logical operation. - * - * @param query the query to add. - * @return This instance. - */ - public final BinaryLogicalFilter append(Filter query) { - queryList.add(query); - return this; - } - - public final BinaryLogicalFilter appendAll(Collection subQueries) { - queryList.addAll(subQueries); - return this; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.filter; + +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +/** + * Abstract superclass for binary logical operations, that is "AND" + * and "OR" operations. + * + * @author Mattias Hellborg Arthursson + */ +public abstract class BinaryLogicalFilter extends AbstractFilter { + + private List queryList = new LinkedList(); + + public StringBuffer encode(StringBuffer buff) { + if (queryList.size() <= 0) { + + // only output query if contains anything + return buff; + + } + else if (queryList.size() == 1) { + + // don't add the & + Filter query = queryList.get(0); + return query.encode(buff); + + } + else { + buff.append("(").append(getLogicalOperator()); + + for (Filter query : queryList) { + query.encode(buff); + } + + buff.append(")"); + + return buff; + } + } + + /** + * 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; + + BinaryLogicalFilter that = (BinaryLogicalFilter) o; + + if (queryList != null ? !queryList.equals(that.queryList) : that.queryList != null) return false; + + return true; + } + + @Override + public int hashCode() { + return queryList != null ? queryList.hashCode() : 0; + } + + /** + * Add a query to this logical operation. + * + * @param query the query to add. + * @return This instance. + */ + public final BinaryLogicalFilter append(Filter query) { + queryList.add(query); + return this; + } + + public final BinaryLogicalFilter appendAll(Collection subQueries) { + 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 8917e251..63f2aa04 100644 --- a/core/src/main/java/org/springframework/ldap/filter/CompareFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/CompareFilter.java @@ -1,110 +1,110 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.filter; - -import org.springframework.ldap.support.LdapEncoder; - -/** - * Abstract superclass for filters that compare values. - * - * @author Mattias Hellborg Arthursson - */ -public abstract class CompareFilter extends AbstractFilter { - - private final String attribute; - - private final String value; - - private final String encodedValue; - - public CompareFilter(String attribute, String value) { - this.attribute = attribute; - this.value = value; - this.encodedValue = encodeValue(value); - } - - /** - * For testing purposes. - * - * @return the encoded value. - */ - String getEncodedValue() { - return encodedValue; - } - - /** - * Override to perform special encoding in subclass. - * - * @param value the value to encode. - * @return properly escaped value. - */ - protected String encodeValue(String value) { - return LdapEncoder.filterEncode(value); - } - - /** - * Convenience constructor for int values. - * - * @param attribute Name of attribute in filter. - * @param value The value of the attribute in the filter. - */ - public CompareFilter(String attribute, int value) { - this.attribute = attribute; - this.value = String.valueOf(value); - this.encodedValue = LdapEncoder.filterEncode(this.value); - } - - /* - * @see org.springframework.ldap.filter.AbstractFilter#encode(java.lang.StringBuffer) - */ - public StringBuffer encode(StringBuffer buff) { - buff.append('('); - buff.append(attribute).append(getCompareString()).append(encodedValue); - buff.append(')'); - - return buff; - } - - @Override - public boolean equals(Object o) { - 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; - - return true; - } - - @Override - public int hashCode() { - int result = attribute != null ? attribute.hashCode() : 0; - result = 31 * result + (value != null ? value.hashCode() : 0); - return result; - } - - /** - * 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(); -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.filter; + +import org.springframework.ldap.support.LdapEncoder; + +/** + * Abstract superclass for filters that compare values. + * + * @author Mattias Hellborg Arthursson + */ +public abstract class CompareFilter extends AbstractFilter { + + private final String attribute; + + private final String value; + + private final String encodedValue; + + public CompareFilter(String attribute, String value) { + this.attribute = attribute; + this.value = value; + this.encodedValue = encodeValue(value); + } + + /** + * For testing purposes. + * + * @return the encoded value. + */ + String getEncodedValue() { + return encodedValue; + } + + /** + * Override to perform special encoding in subclass. + * + * @param value the value to encode. + * @return properly escaped value. + */ + protected String encodeValue(String value) { + return LdapEncoder.filterEncode(value); + } + + /** + * Convenience constructor for int values. + * + * @param attribute Name of attribute in filter. + * @param value The value of the attribute in the filter. + */ + public CompareFilter(String attribute, int value) { + this.attribute = attribute; + this.value = String.valueOf(value); + this.encodedValue = LdapEncoder.filterEncode(this.value); + } + + /* + * @see org.springframework.ldap.filter.AbstractFilter#encode(java.lang.StringBuffer) + */ + public StringBuffer encode(StringBuffer buff) { + buff.append('('); + buff.append(attribute).append(getCompareString()).append(encodedValue); + buff.append(')'); + + return buff; + } + + @Override + public boolean equals(Object o) { + 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; + + return true; + } + + @Override + public int hashCode() { + int result = attribute != null ? attribute.hashCode() : 0; + result = 31 * result + (value != null ? value.hashCode() : 0); + return result; + } + + /** + * 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 8d1d7ba2..c34ecb7f 100644 --- a/core/src/main/java/org/springframework/ldap/filter/EqualsFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/EqualsFilter.java @@ -1,59 +1,59 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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 { - - private static final String EQUALS_SIGN = "="; - - public EqualsFilter(String attribute, String value) { - super(attribute, value); - } - - /** - * Convenience constructor for int values. - * - * @param attribute Name of attribute in filter. - * @param value The value of the attribute in the filter. - */ - public EqualsFilter(String attribute, int value) { - super(attribute, value); - } - - /* - * @see org.springframework.ldap.filter.CompareFilter#getCompareString() - */ - protected String getCompareString() { - return EQUALS_SIGN; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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 { + + private static final String EQUALS_SIGN = "="; + + public EqualsFilter(String attribute, String value) { + super(attribute, value); + } + + /** + * Convenience constructor for int values. + * + * @param attribute Name of attribute in filter. + * @param value The value of the attribute in the filter. + */ + public EqualsFilter(String attribute, int value) { + super(attribute, value); + } + + /* + * @see org.springframework.ldap.filter.CompareFilter#getCompareString() + */ + 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 10fd1538..d5dab99b 100644 --- a/core/src/main/java/org/springframework/ldap/filter/Filter.java +++ b/core/src/main/java/org/springframework/ldap/filter/Filter.java @@ -1,58 +1,58 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -/** - * Common interface for LDAP filters. - * - * @author Adam Skogman - * @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 - */ - StringBuffer encode(StringBuffer buf); - - /** - * All filters must implement equals. - * - * @param o - * @return true if the objects are equal. - */ - boolean equals(Object o); - - /** - * All filters must implement hashCode. - * - * @return the hash code according to the contract in - * {@link Object#hashCode()} - */ - int hashCode(); +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +/** + * Common interface for LDAP filters. + * + * @author Adam Skogman + * @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 + */ + StringBuffer encode(StringBuffer buf); + + /** + * All filters must implement equals. + * + * @param o + * @return true if the objects are equal. + */ + boolean equals(Object o); + + /** + * All filters must implement 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/GreaterThanOrEqualsFilter.java b/core/src/main/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilter.java index b214a864..ce20876e 100644 --- a/core/src/main/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilter.java @@ -1,51 +1,51 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -/** - * 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 { - - private static final String GREATER_THAN_OR_EQUALS = ">="; - - public GreaterThanOrEqualsFilter(String attribute, String value) { - super(attribute, value); - } - - public GreaterThanOrEqualsFilter(String attribute, int value) { - super(attribute, value); - } - - protected String getCompareString() { - return GREATER_THAN_OR_EQUALS; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +/** + * 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 { + + private static final String GREATER_THAN_OR_EQUALS = ">="; + + public GreaterThanOrEqualsFilter(String attribute, String value) { + super(attribute, value); + } + + public GreaterThanOrEqualsFilter(String attribute, int value) { + super(attribute, value); + } + + protected String getCompareString() { + return GREATER_THAN_OR_EQUALS; + } +} 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 14e787b4..edabd7cb 100644 --- a/core/src/main/java/org/springframework/ldap/filter/LessThanOrEqualsFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/LessThanOrEqualsFilter.java @@ -1,51 +1,51 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -/** - * 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 { - - private static final String LESS_THAN_OR_EQUALS = "<="; - - public LessThanOrEqualsFilter(String attribute, String value) { - super(attribute, value); - } - - public LessThanOrEqualsFilter(String attribute, int value) { - super(attribute, value); - } - - protected String getCompareString() { - return LESS_THAN_OR_EQUALS; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +/** + * 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 { + + private static final String LESS_THAN_OR_EQUALS = "<="; + + public LessThanOrEqualsFilter(String attribute, String value) { + super(attribute, value); + } + + public LessThanOrEqualsFilter(String attribute, int value) { + super(attribute, value); + } + + 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 f3374dcc..e19ca4d3 100644 --- a/core/src/main/java/org/springframework/ldap/filter/LikeFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/LikeFilter.java @@ -1,67 +1,67 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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: - * - *
- * LikeFilter filter = new LikeFilter("cn", "foo*");
- * System.out.println(filter.ecode());
- * 
- * - * would result in: - * - *
- *  (cn=foo*)
- * 
- * - * @author Anders Henja - * @author Mattias Hellborg Arthursson - */ -public class LikeFilter extends EqualsFilter { - - public LikeFilter(String attribute, String value) { - super(attribute, value); - } - - protected String encodeValue(String value) { - // just return if blank string - if (value == null) { - return ""; - } - - String[] substrings = value.split("\\*", -2); - - if (substrings.length == 1) { - return LdapEncoder.filterEncode(substrings[0]); - } - - StringBuilder buff = new StringBuilder(); - for (int i = 0; i < substrings.length; i++) { - buff.append(LdapEncoder.filterEncode(substrings[i])); - if (i < substrings.length - 1) { - buff.append("*"); - } - } - - return buff.toString(); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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: + * + *
+ * LikeFilter filter = new LikeFilter("cn", "foo*");
+ * System.out.println(filter.ecode());
+ * 
+ * + * would result in: + * + *
+ *  (cn=foo*)
+ * 
+ * + * @author Anders Henja + * @author Mattias Hellborg Arthursson + */ +public class LikeFilter extends EqualsFilter { + + public LikeFilter(String attribute, String value) { + super(attribute, value); + } + + protected String encodeValue(String value) { + // just return if blank string + if (value == null) { + return ""; + } + + String[] substrings = value.split("\\*", -2); + + if (substrings.length == 1) { + return LdapEncoder.filterEncode(substrings[0]); + } + + StringBuilder buff = new StringBuilder(); + for (int i = 0; i < substrings.length; i++) { + buff.append(LdapEncoder.filterEncode(substrings[i])); + if (i < substrings.length - 1) { + buff.append("*"); + } + } + + 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 39845137..dadd7b6a 100644 --- a/core/src/main/java/org/springframework/ldap/filter/NotFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/NotFilter.java @@ -1,76 +1,76 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -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 { - - private final Filter filter; - - /** - * Create a filter that negates the outcome of the given filter. - * - * @param filter The filter that should be negated. - */ - public NotFilter(Filter filter) { - Assert.notNull(filter, "Filter must not be null"); - this.filter = filter; - } - - public StringBuffer encode(StringBuffer buff) { - - buff.append("(!"); - filter.encode(buff); - buff.append(')'); - - return buff; - } - - @Override - public boolean equals(Object o) { - 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; - - return true; - } - - @Override - public int hashCode() { - return filter != null ? filter.hashCode() : 0; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +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 { + + private final Filter filter; + + /** + * Create a filter that negates the outcome of the given filter. + * + * @param filter The filter that should be negated. + */ + public NotFilter(Filter filter) { + Assert.notNull(filter, "Filter must not be null"); + this.filter = filter; + } + + public StringBuffer encode(StringBuffer buff) { + + buff.append("(!"); + filter.encode(buff); + buff.append(')'); + + return buff; + } + + @Override + public boolean equals(Object o) { + 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; + + return true; + } + + @Override + public int hashCode() { + return filter != null ? filter.hashCode() : 0; + } +} 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 6993cb19..cfc23eb3 100644 --- a/core/src/main/java/org/springframework/ldap/filter/WhitespaceWildcardsFilter.java +++ b/core/src/main/java/org/springframework/ldap/filter/WhitespaceWildcardsFilter.java @@ -1,72 +1,72 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.filter; - -import org.springframework.util.StringUtils; -import org.springframework.ldap.support.LdapEncoder; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * 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) { - super(attribute, value); - } - - protected String encodeValue(String value) { - - // blank string means just ONE star - if (!StringUtils.hasText(value)) { - return "*"; - } - - // filter encode so that any stars etc. are preserved - String filterEncoded = LdapEncoder.filterEncode(value.trim()); - - // Now replace all whitespace with stars - Matcher m = starReplacePattern.matcher(filterEncoded); - - // possibly 2 longer (stars at ends) - StringBuffer buff = new StringBuffer(value.length() + 2); - - buff.append('*'); - - while (m.find()) { - m.appendReplacement(buff, "*"); - } - m.appendTail(buff); - - buff.append('*'); - - return buff.toString(); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.filter; + +import org.springframework.util.StringUtils; +import org.springframework.ldap.support.LdapEncoder; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * 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) { + super(attribute, value); + } + + protected String encodeValue(String value) { + + // blank string means just ONE star + if (!StringUtils.hasText(value)) { + return "*"; + } + + // filter encode so that any stars etc. are preserved + String filterEncoded = LdapEncoder.filterEncode(value.trim()); + + // Now replace all whitespace with stars + Matcher m = starReplacePattern.matcher(filterEncoded); + + // possibly 2 longer (stars at ends) + StringBuffer buff = new StringBuffer(value.length() + 2); + + buff.append('*'); + + while (m.find()) { + m.appendReplacement(buff, "*"); + } + m.appendTail(buff); + + buff.append('*'); + + 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 aeda41ab..f381936b 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 @@ -1,77 +1,77 @@ -package org.springframework.ldap.odm.annotations; - -import java.lang.annotation.ElementType; -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. - */ - enum Type { - /** - * A string field - returned by the JNDI LDAP provider as a {@link java.lang.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. - * - * @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. - */ - 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}. - * - * @return The LDAP syntax of this attribute. - */ - String syntax() default ""; - - /** - * 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. - * - * @return {@code true} is the attribute should not be written to ldap. - */ - boolean readonly() default false; - -} +package org.springframework.ldap.odm.annotations; + +import java.lang.annotation.ElementType; +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. + */ + enum Type { + /** + * A string field - returned by the JNDI LDAP provider as a {@link java.lang.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. + * + * @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. + */ + 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}. + * + * @return The LDAP syntax of this attribute. + */ + String syntax() default ""; + + /** + * 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. + * + * @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/Entry.java b/core/src/main/java/org/springframework/ldap/odm/annotations/Entry.java index da05808b..39ba5073 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 @@ -1,34 +1,34 @@ -package org.springframework.ldap.odm.annotations; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -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(); - - /** - * 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 ""; -} +package org.springframework.ldap.odm.annotations; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +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(); + + /** + * 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 ca7b0d46..0e21a7e0 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 @@ -1,23 +1,23 @@ -package org.springframework.ldap.odm.annotations; - -import java.lang.annotation.ElementType; -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. - *

- * 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 { -} +package org.springframework.ldap.odm.annotations; + +import java.lang.annotation.ElementType; +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. + *

+ * 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 bf7b17b1..c970cfea 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 @@ -1,19 +1,19 @@ -package org.springframework.ldap.odm.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -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. - * - * @author Paul Harvey <paul@pauls-place.me.uk> - * - * @see Entry - */ -@Target(ElementType.FIELD) -@Retention(RetentionPolicy.RUNTIME) -public @interface Transient { -} +package org.springframework.ldap.odm.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +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. + * + * @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 262f3a12..43f56985 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,9 @@ -/** - * Provides a set of annotations to describe the mapping of a Java class to an LDAP entry. - *

- * These annotations are for use with OdmManager. - * - * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ - +/** + * Provides a set of annotations to describe the mapping of a Java class to an LDAP entry. + *

+ * 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/OdmException.java b/core/src/main/java/org/springframework/ldap/odm/core/OdmException.java index cc41e029..7b972953 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 @@ -1,36 +1,36 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.core; - -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); - } - - public OdmException(String message, Throwable e) { - super(message, e); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.core; + +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); + } + + 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 d96aaa9c..43b58e30 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 @@ -1,330 +1,330 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.core.impl; - -import org.springframework.ldap.UncategorizedLdapException; -import org.springframework.ldap.odm.annotations.Attribute; -import org.springframework.ldap.odm.annotations.DnAttribute; -import org.springframework.ldap.odm.annotations.Id; -import org.springframework.ldap.odm.annotations.Transient; - -import javax.naming.Name; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.SortedSet; -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"); - - // Name of the LDAP attribute from the @Attribute annotation - private CaseIgnoreString name; - - // Syntax of the LDAP attribute from the @Attribute annotation - private String syntax; - - // Whether this attribute is binary from the @Attribute annotation - private boolean isBinary; - - // The Java field corresponding to this meta-data - 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 - // List then the valueClass will be String - private Class valueClass; - - // Is this field annotated @Id - private boolean isId; - - // Is this field multi-valued represented by a List - private boolean isCollection; - - private Class collectionClass; - - // Is this the objectClass attribute - private boolean isObjectClass; - - private boolean isTransient = false; - - private boolean isReadOnly = false; - - private String[] attributes; - - private DnAttribute dnAttribute; - - // Extract information from the @Attribute annotation: - // syntax, isBinary, isObjectClass and name. - 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; - - // Grab the @Attribute annotation - Attribute attribute = field.getAnnotation(Attribute.class); - - List attrList = new ArrayList(); - // Did we find the annotation? - if (attribute != null) { - // Pull attribute name, syntax and whether attribute is binary - // 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) { - name = new CaseIgnoreString(localAttributeName); - attrList.add(localAttributeName); - } - syntax = attribute.syntax(); - isBinary = attribute.type() == Attribute.Type.BINARY; - isReadOnly = attribute.readonly(); - } - attributes = attrList.toArray(new String[attrList.size()]); - - isObjectClass=name.equals(OBJECT_CLASS_ATTRIBUTE_CI); - - return foundAnnotation; - } - - // Extract reflection information from the field: - // valueClass, isList - private void determineFieldType(Field field) { - // Determine the class of data stored in the field - Class fieldType = field.getType(); - - isCollection = Collection.class.isAssignableFrom(fieldType); - - valueClass=null; - if (!isCollection) { - // It's not a list so assume its single valued - so just take the field type - valueClass = fieldType; - } 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); - } - Type[] actualParamArguments = paramType.getActualTypeArguments(); - if (actualParamArguments.length == 1) { - if (actualParamArguments[0] instanceof Class) { - valueClass = (Class)actualParamArguments[0]; - } else { - if (actualParamArguments[0] instanceof GenericArrayType) { - // Deal with arrays - Type type=((GenericArrayType)actualParamArguments[0]).getGenericComponentType(); - if (type instanceof Class) { - 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", - field, field.getDeclaringClass())); - } - } - - @SuppressWarnings("unchecked") - private void determineCollectionClass(Class fieldType) { - if(fieldType.isInterface()) { - if(Collection.class.equals(fieldType) || List.class.equals(fieldType)) { - collectionClass = ArrayList.class; - } else if(SortedSet.class.equals(fieldType)) { - collectionClass = TreeSet.class; - } else if(Set.class.isAssignableFrom(fieldType)) { - collectionClass = LinkedHashSet.class; - } else { - throw new MetaDataException(String.format("Collection class %s is not supported", fieldType)); - } - } else { - collectionClass = (Class) fieldType; - } - } - - @SuppressWarnings("unchecked") - public Collection newCollectionInstance() { - try { - return (Collection) collectionClass.newInstance(); - } catch (Exception e) { - throw new UncategorizedLdapException("Failed to instantiate collection class", e); - } - } - - // Extract information from the @Id annotation: - // isId - private boolean processIdAnnotation(Field field, Class fieldType) { - // Are we dealing with the Id field? - isId=field.getAnnotation(Id.class)!=null; - - 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())); - } - } - - return isId; - } - - // Extract meta-data from the given field - public AttributeMetaData(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())); - } - - Transient transientAnnotation = field.getAnnotation(Transient.class); - if(transientAnnotation != null) { - this.isTransient = true; - return; - } - - // Reflection data - determineFieldType(field); - - - // Data from the @Attribute annotation - boolean foundAttributeAnnotation=processAttributeAnnotation(field); - - // Data from the @Id annotation - 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())); - } - - // 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())); - } - } - - - public String getSyntax() { - return syntax; - } - - public boolean isBinary() { - return isBinary; - } - - public Field getField() { - return field; - } - - public CaseIgnoreString getName() { - return name; - } - - public boolean isCollection() { - return isCollection; - } - - public boolean isId() { - return isId; - } - - public boolean isReadOnly() { - return isReadOnly; - } - - public boolean isTransient() { - return isTransient; - } - - public DnAttribute getDnAttribute() { - return dnAttribute; - } - - public boolean isDnAttribute() { - return dnAttribute != null; - } - - public boolean isObjectClass() { - return isObjectClass; - } - - public Class getValueClass() { - return valueClass; - } - - public String[] getAttributes() { - return attributes; - } - - public Class getJndiClass() { - if(isBinary()) { - return byte[].class; - } else if(Name.class.isAssignableFrom(valueClass)) { - return Name.class; - } 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()); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.core.impl; + +import org.springframework.ldap.UncategorizedLdapException; +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.DnAttribute; +import org.springframework.ldap.odm.annotations.Id; +import org.springframework.ldap.odm.annotations.Transient; + +import javax.naming.Name; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.SortedSet; +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"); + + // Name of the LDAP attribute from the @Attribute annotation + private CaseIgnoreString name; + + // Syntax of the LDAP attribute from the @Attribute annotation + private String syntax; + + // Whether this attribute is binary from the @Attribute annotation + private boolean isBinary; + + // The Java field corresponding to this meta-data + 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 + // List then the valueClass will be String + private Class valueClass; + + // Is this field annotated @Id + private boolean isId; + + // Is this field multi-valued represented by a List + private boolean isCollection; + + private Class collectionClass; + + // Is this the objectClass attribute + private boolean isObjectClass; + + private boolean isTransient = false; + + private boolean isReadOnly = false; + + private String[] attributes; + + private DnAttribute dnAttribute; + + // Extract information from the @Attribute annotation: + // syntax, isBinary, isObjectClass and name. + 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; + + // Grab the @Attribute annotation + Attribute attribute = field.getAnnotation(Attribute.class); + + List attrList = new ArrayList(); + // Did we find the annotation? + if (attribute != null) { + // Pull attribute name, syntax and whether attribute is binary + // 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) { + name = new CaseIgnoreString(localAttributeName); + attrList.add(localAttributeName); + } + syntax = attribute.syntax(); + isBinary = attribute.type() == Attribute.Type.BINARY; + isReadOnly = attribute.readonly(); + } + attributes = attrList.toArray(new String[attrList.size()]); + + isObjectClass=name.equals(OBJECT_CLASS_ATTRIBUTE_CI); + + return foundAnnotation; + } + + // Extract reflection information from the field: + // valueClass, isList + private void determineFieldType(Field field) { + // Determine the class of data stored in the field + Class fieldType = field.getType(); + + isCollection = Collection.class.isAssignableFrom(fieldType); + + valueClass=null; + if (!isCollection) { + // It's not a list so assume its single valued - so just take the field type + valueClass = fieldType; + } 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); + } + Type[] actualParamArguments = paramType.getActualTypeArguments(); + if (actualParamArguments.length == 1) { + if (actualParamArguments[0] instanceof Class) { + valueClass = (Class)actualParamArguments[0]; + } else { + if (actualParamArguments[0] instanceof GenericArrayType) { + // Deal with arrays + Type type=((GenericArrayType)actualParamArguments[0]).getGenericComponentType(); + if (type instanceof Class) { + 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", + field, field.getDeclaringClass())); + } + } + + @SuppressWarnings("unchecked") + private void determineCollectionClass(Class fieldType) { + if(fieldType.isInterface()) { + if(Collection.class.equals(fieldType) || List.class.equals(fieldType)) { + collectionClass = ArrayList.class; + } else if(SortedSet.class.equals(fieldType)) { + collectionClass = TreeSet.class; + } else if(Set.class.isAssignableFrom(fieldType)) { + collectionClass = LinkedHashSet.class; + } else { + throw new MetaDataException(String.format("Collection class %s is not supported", fieldType)); + } + } else { + collectionClass = (Class) fieldType; + } + } + + @SuppressWarnings("unchecked") + public Collection newCollectionInstance() { + try { + return (Collection) collectionClass.newInstance(); + } catch (Exception e) { + throw new UncategorizedLdapException("Failed to instantiate collection class", e); + } + } + + // Extract information from the @Id annotation: + // isId + private boolean processIdAnnotation(Field field, Class fieldType) { + // Are we dealing with the Id field? + isId=field.getAnnotation(Id.class)!=null; + + 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())); + } + } + + return isId; + } + + // Extract meta-data from the given field + public AttributeMetaData(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())); + } + + Transient transientAnnotation = field.getAnnotation(Transient.class); + if(transientAnnotation != null) { + this.isTransient = true; + return; + } + + // Reflection data + determineFieldType(field); + + + // Data from the @Attribute annotation + boolean foundAttributeAnnotation=processAttributeAnnotation(field); + + // Data from the @Id annotation + 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())); + } + + // 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())); + } + } + + + public String getSyntax() { + return syntax; + } + + public boolean isBinary() { + return isBinary; + } + + public Field getField() { + return field; + } + + public CaseIgnoreString getName() { + return name; + } + + public boolean isCollection() { + return isCollection; + } + + public boolean isId() { + return isId; + } + + public boolean isReadOnly() { + return isReadOnly; + } + + public boolean isTransient() { + return isTransient; + } + + public DnAttribute getDnAttribute() { + return dnAttribute; + } + + public boolean isDnAttribute() { + return dnAttribute != null; + } + + public boolean isObjectClass() { + return isObjectClass; + } + + public Class getValueClass() { + return valueClass; + } + + public String[] getAttributes() { + return attributes; + } + + public Class getJndiClass() { + if(isBinary()) { + return byte[].class; + } else if(Name.class.isAssignableFrom(valueClass)) { + return Name.class; + } 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()); + } +} 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 29d96395..d60839fc 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 @@ -1,49 +1,49 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.core.impl; - -import org.springframework.util.Assert; - -// A case independent String wrapper. -/* package */ final class CaseIgnoreString implements Comparable { - private final String string; - private final int hashCode; - - public CaseIgnoreString(String string) { - Assert.notNull(string, "string must not be null"); - this.string = string; - hashCode = string.toUpperCase().hashCode(); - } - - public boolean equals(Object other) { - return other instanceof CaseIgnoreString && - ((CaseIgnoreString)other).string.equalsIgnoreCase(string); - } - - public int hashCode() { - return hashCode; - } - - public int compareTo(CaseIgnoreString other) { - CaseIgnoreString cis = other; - return String.CASE_INSENSITIVE_ORDER.compare(string, cis.string); - } - - public String toString() { - return string; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.core.impl; + +import org.springframework.util.Assert; + +// A case independent String wrapper. +/* package */ final class CaseIgnoreString implements Comparable { + private final String string; + private final int hashCode; + + public CaseIgnoreString(String string) { + Assert.notNull(string, "string must not be null"); + this.string = string; + hashCode = string.toUpperCase().hashCode(); + } + + public boolean equals(Object other) { + return other instanceof CaseIgnoreString && + ((CaseIgnoreString)other).string.equalsIgnoreCase(string); + } + + public int hashCode() { + return hashCode; + } + + public int compareTo(CaseIgnoreString other) { + CaseIgnoreString cis = other; + return String.CASE_INSENSITIVE_ORDER.compare(string, cis.string); + } + + public String toString() { + return string; + } +} 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 be8d027a..bf828617 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 @@ -1,36 +1,36 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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. - * - * @author Paul Harvey <paul.at.pauls-place.me.uk> - * - */ -@SuppressWarnings("serial") -public class InvalidEntryException extends OdmException { - public InvalidEntryException(String message) { - super(message); - } - - public InvalidEntryException(String message, Throwable reason) { - super(message, reason); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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. + * + * @author Paul Harvey <paul.at.pauls-place.me.uk> + * + */ +@SuppressWarnings("serial") +public class InvalidEntryException extends OdmException { + public InvalidEntryException(String message) { + super(message); + } + + 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 b1fd9809..2e12a680 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 @@ -1,36 +1,36 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.core.impl; - -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); - } - - public MetaDataException(String message, Throwable reason) { - super(message, reason); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.core.impl; + +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); + } + + public MetaDataException(String message, Throwable reason) { + super(message, reason); + } +} 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 2da0f48e..3e37d7a7 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 @@ -1,37 +1,37 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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. - * - * @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); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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. + * + * @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 d6c9acc3..58d83451 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,9 @@ -/** - * 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. - * - * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ +/** + * 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. + * + * @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 9022cbce..80856fbc 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 - * annotated with {@link org.springframework.ldap.odm.annotations}. - * - * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ - +/** + * Provides an OdmManager interface for interaction with an LDAP directory. + *

+ * 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 454f9bca..c17d9979 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 @@ -1,35 +1,35 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.typeconversion; - -import org.springframework.ldap.NamingException; - -/** - * 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); - } - - public ConverterException(final String message, final Throwable e) { - super(message, e); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.typeconversion; + +import org.springframework.ldap.NamingException; + +/** + * 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); + } + + 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 91652c06..d04fb9eb 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 @@ -1,47 +1,47 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.typeconversion; - -/** - * A simple interface to be implemented to provide type conversion functionality. - * - * @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. - * - * @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. - */ - 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. - * - * @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); -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.typeconversion; + +/** + * A simple interface to be implemented to provide type conversion functionality. + * + * @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. + * + * @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. + */ + 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. + * + * @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/Converter.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/Converter.java index 488ee811..9b28bfd6 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 @@ -1,35 +1,35 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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. - * @return The converted class or null if the conversion was not possible. - * @throws Exception Any exception may be throw by a Converter on error. - */ - T convert(Object source, Class toClass) throws Exception; -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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. + * @return The converted class or null if the conversion was not possible. + * @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/ConverterManagerImpl.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/ConverterManagerImpl.java index 722eed70..4f103282 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 @@ -1,177 +1,177 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.typeconversion.impl; - -import org.springframework.ldap.odm.typeconversion.ConverterException; -import org.springframework.ldap.odm.typeconversion.ConverterManager; - -import java.util.HashMap; -import java.util.Map; - -/** - * 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. - *
- * - * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ -public final class ConverterManagerImpl implements ConverterManager { - /** - * Separator used to form keys into the converters Map. - */ - private static final String KEY_SEP = ":"; - - /** - * Map of keys created via makeConverterKey to Converter instances. - */ - private final Map converters = new HashMap(); - - /** - * 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. - * @return key - */ - private String makeConverterKey(Class fromClass, String syntax, Class toClass) { - StringBuilder key = new StringBuilder(); - if (syntax==null) { - syntax=""; - } - key.append(fromClass.getName()).append(KEY_SEP).append(syntax).append(KEY_SEP).append(toClass.getName()); - return key.toString(); - } - - /** - * Create an empty ConverterManagerImpl - */ - public ConverterManagerImpl() { - } - - /** - * 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>(); - static { - primitiveTypeMap.put(Byte.TYPE, Byte.class); - primitiveTypeMap.put(Short.TYPE, Short.class); - primitiveTypeMap.put(Integer.TYPE, Integer.class); - primitiveTypeMap.put(Long.TYPE, Long.class); - primitiveTypeMap.put(Float.TYPE, Float.class); - primitiveTypeMap.put(Double.TYPE, Double.class); - primitiveTypeMap.put(Boolean.TYPE, Boolean.class); - 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) - */ - public boolean canConvert(Class fromClass, String syntax, Class toClass) { - Class fixedToClass = toClass; - if (toClass.isPrimitive()) { - fixedToClass = primitiveTypeMap.get(toClass); - } - Class fixedFromClass = fromClass; - 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); - } - - - /* - * (non-Javadoc) - * @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) { - Object result = null; - - // What are we converting form - Class fromClass = source.getClass(); - - // Deal with primitives - Class targetClass = toClass; - if (toClass.isPrimitive()) { - targetClass = primitiveTypeMap.get(toClass); - } - - // Try to convert with any syntax we have been given - Converter syntaxConverter = converters.get(makeConverterKey(fromClass, syntax, targetClass)); - if (syntaxConverter != null) { - try { - result = syntaxConverter.convert(source, targetClass); - } catch (Exception e) { - // Ignore as we may still be able to convert successfully - } - } - - // Do we actually need to do any conversion? - if (result == null && targetClass.isAssignableFrom(fromClass)) { - result = source; - } - - // If we were given a syntax and we failed to convert drop back to any mapping - // that will work from class -> to class - if (result == null && syntax != null) { - Converter nullSyntaxConverter = converters.get(makeConverterKey(fromClass, null, targetClass)); - if (nullSyntaxConverter != null) { - try { - result = nullSyntaxConverter.convert(source, targetClass); - } 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)); - } - - // 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 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. - */ - public void addConverter(Class fromClass, String syntax, Class toClass, Converter converter) { - converters.put(makeConverterKey(fromClass, syntax, toClass), converter); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.typeconversion.impl; + +import org.springframework.ldap.odm.typeconversion.ConverterException; +import org.springframework.ldap.odm.typeconversion.ConverterManager; + +import java.util.HashMap; +import java.util.Map; + +/** + * 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. + *
+ * + * @author Paul Harvey <paul.at.pauls-place.me.uk> + */ +public final class ConverterManagerImpl implements ConverterManager { + /** + * Separator used to form keys into the converters Map. + */ + private static final String KEY_SEP = ":"; + + /** + * Map of keys created via makeConverterKey to Converter instances. + */ + private final Map converters = new HashMap(); + + /** + * 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. + * @return key + */ + private String makeConverterKey(Class fromClass, String syntax, Class toClass) { + StringBuilder key = new StringBuilder(); + if (syntax==null) { + syntax=""; + } + key.append(fromClass.getName()).append(KEY_SEP).append(syntax).append(KEY_SEP).append(toClass.getName()); + return key.toString(); + } + + /** + * Create an empty ConverterManagerImpl + */ + public ConverterManagerImpl() { + } + + /** + * 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>(); + static { + primitiveTypeMap.put(Byte.TYPE, Byte.class); + primitiveTypeMap.put(Short.TYPE, Short.class); + primitiveTypeMap.put(Integer.TYPE, Integer.class); + primitiveTypeMap.put(Long.TYPE, Long.class); + primitiveTypeMap.put(Float.TYPE, Float.class); + primitiveTypeMap.put(Double.TYPE, Double.class); + primitiveTypeMap.put(Boolean.TYPE, Boolean.class); + 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) + */ + public boolean canConvert(Class fromClass, String syntax, Class toClass) { + Class fixedToClass = toClass; + if (toClass.isPrimitive()) { + fixedToClass = primitiveTypeMap.get(toClass); + } + Class fixedFromClass = fromClass; + 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); + } + + + /* + * (non-Javadoc) + * @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) { + Object result = null; + + // What are we converting form + Class fromClass = source.getClass(); + + // Deal with primitives + Class targetClass = toClass; + if (toClass.isPrimitive()) { + targetClass = primitiveTypeMap.get(toClass); + } + + // Try to convert with any syntax we have been given + Converter syntaxConverter = converters.get(makeConverterKey(fromClass, syntax, targetClass)); + if (syntaxConverter != null) { + try { + result = syntaxConverter.convert(source, targetClass); + } catch (Exception e) { + // Ignore as we may still be able to convert successfully + } + } + + // Do we actually need to do any conversion? + if (result == null && targetClass.isAssignableFrom(fromClass)) { + result = source; + } + + // If we were given a syntax and we failed to convert drop back to any mapping + // that will work from class -> to class + if (result == null && syntax != null) { + Converter nullSyntaxConverter = converters.get(makeConverterKey(fromClass, null, targetClass)); + if (nullSyntaxConverter != null) { + try { + result = nullSyntaxConverter.convert(source, targetClass); + } 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)); + } + + // 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 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. + */ + 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/converters/FromStringConverter.java b/core/src/main/java/org/springframework/ldap/odm/typeconversion/impl/converters/FromStringConverter.java index 049aa4df..f8c9ff75 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 @@ -1,40 +1,40 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.typeconversion.impl.converters; - -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 - * 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) - */ - public T convert(Object source, Class toClass) throws Exception { - Constructor constructor = toClass.getConstructor(java.lang.String.class); - return constructor.newInstance(source); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.typeconversion.impl.converters; + +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 + * 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) + */ + 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 4358629d..b212abc4 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 @@ -1,37 +1,37 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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. - *

- * 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) - */ - public T convert(Object source, Class toClass) { - return toClass.cast(source.toString()); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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. + *

+ * 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) + */ + 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 795ce9f3..f4b8a24b 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,7 +1,7 @@ -/** - * Provides some basic implementations of the {@link org.springframework.ldap.odm.typeconversion.impl.Converter} interface. - * - * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ - +/** + * Provides some basic implementations of the {@link org.springframework.ldap.odm.typeconversion.impl.Converter} interface. + * + * @author Paul Harvey <paul.at.pauls-place.me.uk> + */ + package org.springframework.ldap.odm.typeconversion.impl.converters; \ No newline at end of file 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 98c794d0..76d9ef63 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. - * - * @author Paul Harvey <paul.at.pauls-place.me.uk> - */ - -package org.springframework.ldap.odm.typeconversion.impl; - +/** + * 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 6351ba3a..164db597 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 @@ -1,10 +1,10 @@ -/** - * 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; - +/** + * 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/support/LdapEncoder.java b/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java index 8c0a4af5..22df75c6 100644 --- a/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java +++ b/core/src/main/java/org/springframework/ldap/support/LdapEncoder.java @@ -1,306 +1,306 @@ -/* - * Copyright 2005-2021 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.support; - -import java.util.Base64; - -import org.springframework.ldap.BadLdapGrammarException; -import org.springframework.util.Assert; - -/** - * Helper class to encode and decode ldap names and values. - * - * @author Adam Skogman - * @author Mattias Hellborg Arthursson - * @author Thomas Darimont - */ -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]; - - private static final int RFC2849_MAX_BASE64_CHARS_PER_LINE = 76; - - static { - - // Name encoding table ------------------------------------- - - // all below 0x20 (control chars) - for (char c = 0; c < ' '; c++) { - NAME_ESCAPE_TABLE[c] = "\\" + toTwoCharHex(c); - } - - NAME_ESCAPE_TABLE['#'] = "\\#"; - NAME_ESCAPE_TABLE[','] = "\\,"; - NAME_ESCAPE_TABLE[';'] = "\\;"; - NAME_ESCAPE_TABLE['='] = "\\="; - NAME_ESCAPE_TABLE['+'] = "\\+"; - NAME_ESCAPE_TABLE['<'] = "\\<"; - NAME_ESCAPE_TABLE['>'] = "\\>"; - NAME_ESCAPE_TABLE['\"'] = "\\\""; - NAME_ESCAPE_TABLE['\\'] = "\\\\"; - - // Filter encoding table ------------------------------------- - - // fill with char itself - for (char c = 0; c < FILTER_ESCAPE_TABLE.length; c++) { - FILTER_ESCAPE_TABLE[c] = String.valueOf(c); - } - - // escapes (RFC2254) - FILTER_ESCAPE_TABLE['*'] = "\\2a"; - FILTER_ESCAPE_TABLE['('] = "\\28"; - FILTER_ESCAPE_TABLE[')'] = "\\29"; - FILTER_ESCAPE_TABLE['\\'] = "\\5c"; - FILTER_ESCAPE_TABLE[0] = "\\00"; - - } - - /** - * All static methods - not to be instantiated. - */ - private LdapEncoder() { - } - - protected static String toTwoCharHex(char c) { - - String raw = Integer.toHexString(c).toUpperCase(); - - if (raw.length() > 1) { - return raw; - } else { - return "0" + raw; - } - } - - /** - * Escape a value for use in a filter. - * - * @param value - * the value to escape. - * @return a properly escaped representation of the supplied value. - */ - public static String filterEncode(String value) { - - if (value == null) - return null; - - // make buffer roomy - StringBuilder encodedValue = new StringBuilder(value.length() * 2); - - int length = value.length(); - - for (int i = 0; i < length; i++) { - - char c = value.charAt(i); - - if (c < FILTER_ESCAPE_TABLE.length) { - encodedValue.append(FILTER_ESCAPE_TABLE[c]); - } else { - // default: add the char - encodedValue.append(c); - } - } - - return encodedValue.toString(); - } - - /** - * 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. - * @return The escaped value. - */ - public static String nameEncode(String value) { - - if (value == null) - return null; - - // make buffer roomy - StringBuilder encodedValue = new StringBuilder(value.length() * 2); - - int length = value.length(); - int last = length - 1; - - for (int i = 0; i < length; i++) { - - char c = value.charAt(i); - - // space first or last - if (c == ' ' && (i == 0 || i == last)) { - encodedValue.append("\\ "); - continue; - } - - if (c < NAME_ESCAPE_TABLE.length) { - // check in table for escapes - String esc = NAME_ESCAPE_TABLE[c]; - - if (esc != null) { - encodedValue.append(esc); - continue; - } - } - - // default: add the char - encodedValue.append(c); - } - - return encodedValue.toString(); - - } - - /** - * Decodes a value. Converts escaped chars to ordinary chars. - * - * @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 { - - if (value == null) - return null; - - // make buffer same size - StringBuilder decoded = new StringBuilder(value.length()); - - int i = 0; - while (i < value.length()) { - char currentChar = value.charAt(i); - if (currentChar == '\\') { - if (value.length() <= i + 1) { - // Ending with a single backslash is not allowed - 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 == '\"' - || nextChar == ' ') { - // Normal backslash escape - decoded.append(nextChar); - i += 2; - } else { - if (value.length() <= i + 2) { - throw new BadLdapGrammarException( - "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)); - i += 3; - } - } - } - } else { - // This character wasn't escaped - just append it - decoded.append(currentChar); - i++; - } - } - - return decoded.toString(); - - } - - /** - * 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. - * @throws IllegalArgumentException if val is null. - */ - public static String printBase64Binary(byte[] val) { - - Assert.notNull(val, "val must not be null!"); - - String encoded = encode(val); - - int length = encoded.length(); - StringBuilder sb = new StringBuilder(length + length / RFC2849_MAX_BASE64_CHARS_PER_LINE); - - for (int i = 0, len = length; i < len; i++) { - sb.append(encoded.charAt(i)); - - if ((i + 1) % RFC2849_MAX_BASE64_CHARS_PER_LINE == 0) { - sb.append('\n'); - sb.append(' '); - } - } - - return sb.toString(); - } - - /** - * 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. - */ - public static byte[] parseBase64Binary(String val) { - - Assert.notNull(val, "val must not be null!"); - - int length = val.length(); - StringBuilder sb = new StringBuilder(length); - for (int i = 0, len = length; i < len; i++) { - - char c = val.charAt(i); - - if(c == '\n'){ - if(i + 1 < len && val.charAt(i + 1) == ' ') { - i++; - } - continue; - } - - sb.append(c); - } - - return decode(sb.toString()); - } - - private static String encode(byte[] decoded) { - return Base64.getEncoder().encodeToString(decoded); - } - - private static byte[] decode(String encoded) { - return Base64.getDecoder().decode(encoded); - } -} +/* + * Copyright 2005-2021 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.support; + +import java.util.Base64; + +import org.springframework.ldap.BadLdapGrammarException; +import org.springframework.util.Assert; + +/** + * Helper class to encode and decode ldap names and values. + * + * @author Adam Skogman + * @author Mattias Hellborg Arthursson + * @author Thomas Darimont + */ +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]; + + private static final int RFC2849_MAX_BASE64_CHARS_PER_LINE = 76; + + static { + + // Name encoding table ------------------------------------- + + // all below 0x20 (control chars) + for (char c = 0; c < ' '; c++) { + NAME_ESCAPE_TABLE[c] = "\\" + toTwoCharHex(c); + } + + NAME_ESCAPE_TABLE['#'] = "\\#"; + NAME_ESCAPE_TABLE[','] = "\\,"; + NAME_ESCAPE_TABLE[';'] = "\\;"; + NAME_ESCAPE_TABLE['='] = "\\="; + NAME_ESCAPE_TABLE['+'] = "\\+"; + NAME_ESCAPE_TABLE['<'] = "\\<"; + NAME_ESCAPE_TABLE['>'] = "\\>"; + NAME_ESCAPE_TABLE['\"'] = "\\\""; + NAME_ESCAPE_TABLE['\\'] = "\\\\"; + + // Filter encoding table ------------------------------------- + + // fill with char itself + for (char c = 0; c < FILTER_ESCAPE_TABLE.length; c++) { + FILTER_ESCAPE_TABLE[c] = String.valueOf(c); + } + + // escapes (RFC2254) + FILTER_ESCAPE_TABLE['*'] = "\\2a"; + FILTER_ESCAPE_TABLE['('] = "\\28"; + FILTER_ESCAPE_TABLE[')'] = "\\29"; + FILTER_ESCAPE_TABLE['\\'] = "\\5c"; + FILTER_ESCAPE_TABLE[0] = "\\00"; + + } + + /** + * All static methods - not to be instantiated. + */ + private LdapEncoder() { + } + + protected static String toTwoCharHex(char c) { + + String raw = Integer.toHexString(c).toUpperCase(); + + if (raw.length() > 1) { + return raw; + } else { + return "0" + raw; + } + } + + /** + * Escape a value for use in a filter. + * + * @param value + * the value to escape. + * @return a properly escaped representation of the supplied value. + */ + public static String filterEncode(String value) { + + if (value == null) + return null; + + // make buffer roomy + StringBuilder encodedValue = new StringBuilder(value.length() * 2); + + int length = value.length(); + + for (int i = 0; i < length; i++) { + + char c = value.charAt(i); + + if (c < FILTER_ESCAPE_TABLE.length) { + encodedValue.append(FILTER_ESCAPE_TABLE[c]); + } else { + // default: add the char + encodedValue.append(c); + } + } + + return encodedValue.toString(); + } + + /** + * 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. + * @return The escaped value. + */ + public static String nameEncode(String value) { + + if (value == null) + return null; + + // make buffer roomy + StringBuilder encodedValue = new StringBuilder(value.length() * 2); + + int length = value.length(); + int last = length - 1; + + for (int i = 0; i < length; i++) { + + char c = value.charAt(i); + + // space first or last + if (c == ' ' && (i == 0 || i == last)) { + encodedValue.append("\\ "); + continue; + } + + if (c < NAME_ESCAPE_TABLE.length) { + // check in table for escapes + String esc = NAME_ESCAPE_TABLE[c]; + + if (esc != null) { + encodedValue.append(esc); + continue; + } + } + + // default: add the char + encodedValue.append(c); + } + + return encodedValue.toString(); + + } + + /** + * Decodes a value. Converts escaped chars to ordinary chars. + * + * @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 { + + if (value == null) + return null; + + // make buffer same size + StringBuilder decoded = new StringBuilder(value.length()); + + int i = 0; + while (i < value.length()) { + char currentChar = value.charAt(i); + if (currentChar == '\\') { + if (value.length() <= i + 1) { + // Ending with a single backslash is not allowed + 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 == '\"' + || nextChar == ' ') { + // Normal backslash escape + decoded.append(nextChar); + i += 2; + } else { + if (value.length() <= i + 2) { + throw new BadLdapGrammarException( + "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)); + i += 3; + } + } + } + } else { + // This character wasn't escaped - just append it + decoded.append(currentChar); + i++; + } + } + + return decoded.toString(); + + } + + /** + * 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. + * @throws IllegalArgumentException if val is null. + */ + public static String printBase64Binary(byte[] val) { + + Assert.notNull(val, "val must not be null!"); + + String encoded = encode(val); + + int length = encoded.length(); + StringBuilder sb = new StringBuilder(length + length / RFC2849_MAX_BASE64_CHARS_PER_LINE); + + for (int i = 0, len = length; i < len; i++) { + sb.append(encoded.charAt(i)); + + if ((i + 1) % RFC2849_MAX_BASE64_CHARS_PER_LINE == 0) { + sb.append('\n'); + sb.append(' '); + } + } + + return sb.toString(); + } + + /** + * 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. + */ + public static byte[] parseBase64Binary(String val) { + + Assert.notNull(val, "val must not be null!"); + + int length = val.length(); + StringBuilder sb = new StringBuilder(length); + for (int i = 0, len = length; i < len; i++) { + + char c = val.charAt(i); + + if(c == '\n'){ + if(i + 1 < len && val.charAt(i + 1) == ' ') { + i++; + } + continue; + } + + sb.append(c); + } + + return decode(sb.toString()); + } + + private static String encode(byte[] decoded) { + return Base64.getEncoder().encodeToString(decoded); + } + + private static byte[] decode(String encoded) { + return Base64.getDecoder().decode(encoded); + } +} 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 10b9f113..05dc2e63 100644 --- a/core/src/main/java/org/springframework/ldap/support/ListComparator.java +++ b/core/src/main/java/org/springframework/ldap/support/ListComparator.java @@ -1,67 +1,67 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.support; - -import java.io.Serializable; -import java.util.Comparator; -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. - */ - public int compare(Object o1, Object o2) { - List list1 = (List) o1; - List list2 = (List) o2; - - for (int i = 0; i < list1.size(); i++) { - if (list2.size() > i) { - Comparable component1 = (Comparable) list1.get(i); - Comparable component2 = (Comparable) list2.get(i); - int componentsCompared = component1.compareTo(component2); - if (componentsCompared != 0) { - return componentsCompared; - } - } - else { - // First instance has more components, so that instance is - // greater. - return 1; - } - } - - // All components so far are equal - if the other instance has - // more components it is greater otherwise they are equal. - if (list2.size() > list1.size()) { - return -1; - } - else { - return 0; - } - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.support; + +import java.io.Serializable; +import java.util.Comparator; +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. + */ + public int compare(Object o1, Object o2) { + List list1 = (List) o1; + List list2 = (List) o2; + + for (int i = 0; i < list1.size(); i++) { + if (list2.size() > i) { + Comparable component1 = (Comparable) list1.get(i); + Comparable component2 = (Comparable) list2.get(i); + int componentsCompared = component1.compareTo(component2); + if (componentsCompared != 0) { + return componentsCompared; + } + } + else { + // First instance has more components, so that instance is + // greater. + return 1; + } + } + + // All components so far are equal - if the other instance has + // more components it is greater otherwise they are equal. + if (list2.size() > list1.size()) { + return -1; + } + else { + return 0; + } + } +} 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 29e4e261..4a93a498 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 @@ -1,79 +1,79 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import javax.naming.Name; -import javax.naming.directory.Attributes; - -import org.springframework.ldap.core.LdapOperations; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; - -/** - * 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 { - - private LdapOperations ldapOperations; - - /** - * Constructor. - * - * @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[]) - */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { - if (args == null || args.length != 3) { - 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) { - attributes = (Attributes) args[2]; - } - - return new BindOperationExecutor(ldapOperations, dn, object, attributes); - } - - /** - * Get the LdapOperations. For testing purposes.s - * - * @return the LdapOperations. - */ - LdapOperations getLdapOperations() { - return ldapOperations; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import javax.naming.Name; +import javax.naming.directory.Attributes; + +import org.springframework.ldap.core.LdapOperations; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; +import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; + +/** + * 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 { + + private LdapOperations ldapOperations; + + /** + * Constructor. + * + * @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[]) + */ + public CompensatingTransactionOperationExecutor recordOperation( + Object[] args) { + if (args == null || args.length != 3) { + 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) { + attributes = (Attributes) args[2]; + } + + return new BindOperationExecutor(ldapOperations, dn, object, attributes); + } + + /** + * 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/LdapTransactionUtils.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/LdapTransactionUtils.java index bf143598..5231e02e 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 @@ -1,100 +1,100 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.springframework.ldap.support.LdapUtils; -import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; - -import javax.naming.Name; - -/** - * Utility methods for working with LDAP transactions. - * - * @author Mattias Hellborg Arthursson - * @since 1.2 - */ -public final class LdapTransactionUtils { - - public static final String REBIND_METHOD_NAME = "rebind"; - - public static final String BIND_METHOD_NAME = "bind"; - - public static final String RENAME_METHOD_NAME = "rename"; - - public static final String UNBIND_METHOD_NAME = "unbind"; - - public static final String MODIFY_ATTRIBUTES_METHOD_NAME = "modifyAttributes"; - - /** - * Not to be instantiated. - */ - private 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. - */ - public static Name getFirstArgumentAsName(Object[] args) { - Assert.notEmpty(args); - - Object firstArg = args[0]; - return getArgumentAsName(firstArg); - } - - /** - * 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. - */ - public static Name getArgumentAsName(Object arg) { - if (arg instanceof String) { - return LdapUtils.newLdapName((String) arg); - } else if (arg instanceof Name) { - return (Name) arg; - } 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. - * @return true if this is a supported transaction operation, - * false otherwise. - */ - public static boolean isSupportedWriteTransactionOperation(String methodName) { - return (ObjectUtils.nullSafeEquals(methodName, BIND_METHOD_NAME) - || ObjectUtils.nullSafeEquals(methodName, REBIND_METHOD_NAME) - || ObjectUtils.nullSafeEquals(methodName, RENAME_METHOD_NAME) - || ObjectUtils.nullSafeEquals(methodName, MODIFY_ATTRIBUTES_METHOD_NAME) - || ObjectUtils.nullSafeEquals(methodName, UNBIND_METHOD_NAME)); - - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.springframework.ldap.support.LdapUtils; +import org.springframework.util.Assert; +import org.springframework.util.ObjectUtils; + +import javax.naming.Name; + +/** + * Utility methods for working with LDAP transactions. + * + * @author Mattias Hellborg Arthursson + * @since 1.2 + */ +public final class LdapTransactionUtils { + + public static final String REBIND_METHOD_NAME = "rebind"; + + public static final String BIND_METHOD_NAME = "bind"; + + public static final String RENAME_METHOD_NAME = "rename"; + + public static final String UNBIND_METHOD_NAME = "unbind"; + + public static final String MODIFY_ATTRIBUTES_METHOD_NAME = "modifyAttributes"; + + /** + * Not to be instantiated. + */ + private 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. + */ + public static Name getFirstArgumentAsName(Object[] args) { + Assert.notEmpty(args); + + Object firstArg = args[0]; + return getArgumentAsName(firstArg); + } + + /** + * 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. + */ + public static Name getArgumentAsName(Object arg) { + if (arg instanceof String) { + return LdapUtils.newLdapName((String) arg); + } else if (arg instanceof Name) { + return (Name) arg; + } 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. + * @return true if this is a supported transaction operation, + * false otherwise. + */ + public static boolean isSupportedWriteTransactionOperation(String methodName) { + return (ObjectUtils.nullSafeEquals(methodName, BIND_METHOD_NAME) + || ObjectUtils.nullSafeEquals(methodName, REBIND_METHOD_NAME) + || ObjectUtils.nullSafeEquals(methodName, RENAME_METHOD_NAME) + || ObjectUtils.nullSafeEquals(methodName, MODIFY_ATTRIBUTES_METHOD_NAME) + || ObjectUtils.nullSafeEquals(methodName, UNBIND_METHOD_NAME)); + + } +} 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 141fe190..e15e70b3 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 @@ -1,168 +1,168 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.transaction.compensating; - -import org.springframework.ldap.core.AttributesMapper; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.core.support.DefaultIncrementalAttributesMapper; -import org.springframework.ldap.core.IncrementalAttributesMapper; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; -import org.springframework.util.Assert; - -import javax.naming.Name; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.BasicAttribute; -import javax.naming.directory.DirContext; -import javax.naming.directory.ModificationItem; -import java.util.HashSet; -import java.util.Set; - -/** - * 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 { - - private LdapOperations ldapOperations; - - public ModifyAttributesOperationRecorder(LdapOperations ldapOperations) { - this.ldapOperations = ldapOperations; - } - - /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) - */ - 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"); - } - - ModificationItem[] incomingModifications = (ModificationItem[]) args[1]; - - Set set = new HashSet(); - for (ModificationItem incomingModification : incomingModifications) { - set.add(incomingModification.getAttribute().getID()); - } - - // Get the current values of all referred Attributes. - 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 - // by one query. - IncrementalAttributesMapper attributesMapper = getAttributesMapper(attributeNameArray); - while (attributesMapper.hasMore()) { - ldapOperations.lookup(dn, attributesMapper.getAttributesForLookup(), attributesMapper); - } - - Attributes currentAttributes = attributesMapper.getCollectedAttributes(); - - // Get a compensating ModificationItem for each of the incoming - // modification. - ModificationItem[] rollbackItems = new ModificationItem[incomingModifications.length]; - for (int i = 0; i < incomingModifications.length; i++) { - rollbackItems[i] = getCompensatingModificationItem( - currentAttributes, incomingModifications[i]); - } - - 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. - */ - IncrementalAttributesMapper getAttributesMapper(String[] attributeNames) { - return new DefaultIncrementalAttributesMapper(attributeNames); - } - - /** - * 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. - */ - protected ModificationItem getCompensatingModificationItem( - Attributes originalAttributes, ModificationItem modificationItem) { - Attribute modificationAttribute = modificationItem.getAttribute(); - 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 { - // The rollback modification will be to re-add the removed - // attribute values. - return new ModificationItem(DirContext.ADD_ATTRIBUTE, - (Attribute) modificationAttribute.clone()); - } - } else if (modificationItem.getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { - if (originalAttribute != null) { - 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 { - // 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 { - // 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()); - } - } - } - - LdapOperations getLdapOperations() { - return ldapOperations; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.transaction.compensating; + +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.core.support.DefaultIncrementalAttributesMapper; +import org.springframework.ldap.core.IncrementalAttributesMapper; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; +import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; +import org.springframework.util.Assert; + +import javax.naming.Name; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttribute; +import javax.naming.directory.DirContext; +import javax.naming.directory.ModificationItem; +import java.util.HashSet; +import java.util.Set; + +/** + * 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 { + + private LdapOperations ldapOperations; + + public ModifyAttributesOperationRecorder(LdapOperations ldapOperations) { + this.ldapOperations = ldapOperations; + } + + /* + * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + */ + 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"); + } + + ModificationItem[] incomingModifications = (ModificationItem[]) args[1]; + + Set set = new HashSet(); + for (ModificationItem incomingModification : incomingModifications) { + set.add(incomingModification.getAttribute().getID()); + } + + // Get the current values of all referred Attributes. + 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 + // by one query. + IncrementalAttributesMapper attributesMapper = getAttributesMapper(attributeNameArray); + while (attributesMapper.hasMore()) { + ldapOperations.lookup(dn, attributesMapper.getAttributesForLookup(), attributesMapper); + } + + Attributes currentAttributes = attributesMapper.getCollectedAttributes(); + + // Get a compensating ModificationItem for each of the incoming + // modification. + ModificationItem[] rollbackItems = new ModificationItem[incomingModifications.length]; + for (int i = 0; i < incomingModifications.length; i++) { + rollbackItems[i] = getCompensatingModificationItem( + currentAttributes, incomingModifications[i]); + } + + 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. + */ + IncrementalAttributesMapper getAttributesMapper(String[] attributeNames) { + return new DefaultIncrementalAttributesMapper(attributeNames); + } + + /** + * 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. + */ + protected ModificationItem getCompensatingModificationItem( + Attributes originalAttributes, ModificationItem modificationItem) { + Attribute modificationAttribute = modificationItem.getAttribute(); + 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 { + // The rollback modification will be to re-add the removed + // attribute values. + return new ModificationItem(DirContext.ADD_ATTRIBUTE, + (Attribute) modificationAttribute.clone()); + } + } else if (modificationItem.getModificationOp() == DirContext.REPLACE_ATTRIBUTE) { + if (originalAttribute != null) { + 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 { + // 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 { + // 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()); + } + } + } + + LdapOperations getLdapOperations() { + return ldapOperations; + } +} 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 43ec46b3..b98fefe8 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 @@ -1,43 +1,43 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; -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. - * - * @author Mattias Hellborg Arthursson - * @since 1.2 - */ -public class NullOperationRecorder implements - CompensatingTransactionOperationRecorder { - - /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) - */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { - return new NullOperationExecutor(); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; +import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; +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. + * + * @author Mattias Hellborg Arthursson + * @since 1.2 + */ +public class NullOperationRecorder implements + CompensatingTransactionOperationRecorder { + + /* + * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + */ + public CompensatingTransactionOperationExecutor recordOperation( + Object[] args) { + return new NullOperationExecutor(); + } +} 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 bd9c18c7..48b38589 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 @@ -1,93 +1,93 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import javax.naming.Name; -import javax.naming.directory.Attributes; - -import org.springframework.ldap.core.LdapOperations; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; - -/** - * 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 { - - private LdapOperations ldapOperations; - - private TempEntryRenamingStrategy renamingStrategy; - - /** - * 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. - */ - public RebindOperationRecorder(LdapOperations ldapOperations, - TempEntryRenamingStrategy renamingStrategy) { - this.ldapOperations = ldapOperations; - this.renamingStrategy = renamingStrategy; - } - - /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) - */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { - if (args == null || args.length != 3) { - 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) { - attributes = (Attributes) args[2]; - } - - Name temporaryName = renamingStrategy.getTemporaryName(dn); - - return new RebindOperationExecutor(ldapOperations, dn, temporaryName, - object, attributes); - } - - /** - * Get the LdapOperations. For testing purposes. - * - * @return the LdapOperations. - */ - LdapOperations getLdapOperations() { - return ldapOperations; - } - - public TempEntryRenamingStrategy getRenamingStrategy() { - return renamingStrategy; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import javax.naming.Name; +import javax.naming.directory.Attributes; + +import org.springframework.ldap.core.LdapOperations; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; +import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; + +/** + * 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 { + + private LdapOperations ldapOperations; + + private TempEntryRenamingStrategy renamingStrategy; + + /** + * 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. + */ + public RebindOperationRecorder(LdapOperations ldapOperations, + TempEntryRenamingStrategy renamingStrategy) { + this.ldapOperations = ldapOperations; + this.renamingStrategy = renamingStrategy; + } + + /* + * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + */ + public CompensatingTransactionOperationExecutor recordOperation( + Object[] args) { + if (args == null || args.length != 3) { + 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) { + attributes = (Attributes) args[2]; + } + + Name temporaryName = renamingStrategy.getTemporaryName(dn); + + return new RebindOperationExecutor(ldapOperations, dn, temporaryName, + object, attributes); + } + + /** + * Get the LdapOperations. For testing purposes. + * + * @return the LdapOperations. + */ + LdapOperations getLdapOperations() { + return ldapOperations; + } + + public TempEntryRenamingStrategy getRenamingStrategy() { + return renamingStrategy; + } +} 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 d5beac2a..c8f328bf 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 @@ -1,38 +1,38 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import javax.naming.Name; - -/** - * Interface for different strategies to rename temporary entries for unbind and - * rebind operations. - * - * @author Mattias Hellborg Arthursson - * @since 1.2 - */ -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. - */ - Name getTemporaryName(Name originalName); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import javax.naming.Name; + +/** + * Interface for different strategies to rename temporary entries for unbind and + * rebind operations. + * + * @author Mattias Hellborg Arthursson + * @since 1.2 + */ +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. + */ + Name getTemporaryName(Name originalName); +} 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 3f8d60c3..5529b7f8 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 @@ -1,74 +1,74 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import javax.naming.Name; - -import org.springframework.ldap.core.LdapOperations; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; - -/** - * {@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 { - - private LdapOperations ldapOperations; - - private TempEntryRenamingStrategy renamingStrategy; - - /** - * 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. - */ - public UnbindOperationRecorder(LdapOperations ldapOperations, - TempEntryRenamingStrategy renamingStrategy) { - this.ldapOperations = ldapOperations; - this.renamingStrategy = renamingStrategy; - } - - /* - * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) - */ - public CompensatingTransactionOperationExecutor recordOperation( - Object[] args) { - Name dn = LdapTransactionUtils.getFirstArgumentAsName(args); - Name temporaryDn = renamingStrategy.getTemporaryName(dn); - - return new UnbindOperationExecutor(ldapOperations, dn, temporaryDn); - } - - LdapOperations getLdapOperations() { - return ldapOperations; - } - - public TempEntryRenamingStrategy getRenamingStrategy() { - return renamingStrategy; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import javax.naming.Name; + +import org.springframework.ldap.core.LdapOperations; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; +import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; + +/** + * {@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 { + + private LdapOperations ldapOperations; + + private TempEntryRenamingStrategy renamingStrategy; + + /** + * 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. + */ + public UnbindOperationRecorder(LdapOperations ldapOperations, + TempEntryRenamingStrategy renamingStrategy) { + this.ldapOperations = ldapOperations; + this.renamingStrategy = renamingStrategy; + } + + /* + * @see org.springframework.ldap.support.transaction.CompensatingTransactionOperationRecorder#recordOperation(java.lang.Object[]) + */ + public CompensatingTransactionOperationExecutor recordOperation( + Object[] args) { + Name dn = LdapTransactionUtils.getFirstArgumentAsName(args); + Name temporaryDn = renamingStrategy.getTemporaryName(dn); + + return new UnbindOperationExecutor(ldapOperations, dn, temporaryDn); + } + + LdapOperations getLdapOperations() { + return ldapOperations; + } + + 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 006513eb..d88a07d3 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 @@ -1,212 +1,212 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.transaction.compensating.manager; - -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; -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 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. - */ -public class ContextSourceAndDataSourceTransactionManager extends - DataSourceTransactionManager { - - private static final long serialVersionUID = 6832868697460384648L; - - private ContextSourceTransactionManagerDelegate ldapManagerDelegate = new ContextSourceTransactionManagerDelegate(); - - public ContextSourceAndDataSourceTransactionManager() { - super(); - // Override the default behaviour. - setNestedTransactionAllowed(false); - } - - /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#isExistingTransaction(java.lang.Object) - */ - protected boolean isExistingTransaction(Object transaction) { - // We don't support nested transactions here - return false; - } - - /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doGetTransaction() - */ - protected Object doGetTransaction() { - Object dataSourceTransactionObject = super.doGetTransaction(); - Object contextSourceTransactionObject = ldapManagerDelegate - .doGetTransaction(); - - return new ContextSourceAndDataSourceTransactionObject( - contextSourceTransactionObject, dataSourceTransactionObject); - } - - /* - * @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); - try { - 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; - } - } - - /* - * @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()); - } - - /* - * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doCommit(org.springframework.transaction.support.DefaultTransactionStatus) - */ - protected void doCommit(DefaultTransactionStatus status) { - - ContextSourceAndDataSourceTransactionObject actualTransactionObject = (ContextSourceAndDataSourceTransactionObject) status - .getTransaction(); - - try { - 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."); - } - } - 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) - */ - 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())); - } - - public ContextSource getContextSource() { - return ldapManagerDelegate.getContextSource(); - } - - public void setContextSource(ContextSource contextSource) { - ldapManagerDelegate.setContextSource(contextSource); - } - - 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) { - this.ldapTransactionObject = ldapTransactionObject; - this.dataSourceTransactionObject = dataSourceTransactionObject; - } - - public Object getDataSourceTransactionObject() { - return dataSourceTransactionObject; - } - - public Object getLdapTransactionObject() { - return ldapTransactionObject; - } - } - - /* - * @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"); - } - - /* - * @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"); - } - - public void afterPropertiesSet() { - super.afterPropertiesSet(); - ldapManagerDelegate.checkRenamingStrategy(); - } +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.transaction.compensating.manager; + +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; +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 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. + */ +public class ContextSourceAndDataSourceTransactionManager extends + DataSourceTransactionManager { + + private static final long serialVersionUID = 6832868697460384648L; + + private ContextSourceTransactionManagerDelegate ldapManagerDelegate = new ContextSourceTransactionManagerDelegate(); + + public ContextSourceAndDataSourceTransactionManager() { + super(); + // Override the default behaviour. + setNestedTransactionAllowed(false); + } + + /* + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#isExistingTransaction(java.lang.Object) + */ + protected boolean isExistingTransaction(Object transaction) { + // We don't support nested transactions here + return false; + } + + /* + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doGetTransaction() + */ + protected Object doGetTransaction() { + Object dataSourceTransactionObject = super.doGetTransaction(); + Object contextSourceTransactionObject = ldapManagerDelegate + .doGetTransaction(); + + return new ContextSourceAndDataSourceTransactionObject( + contextSourceTransactionObject, dataSourceTransactionObject); + } + + /* + * @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); + try { + 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; + } + } + + /* + * @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()); + } + + /* + * @see org.springframework.jdbc.datasource.DataSourceTransactionManager#doCommit(org.springframework.transaction.support.DefaultTransactionStatus) + */ + protected void doCommit(DefaultTransactionStatus status) { + + ContextSourceAndDataSourceTransactionObject actualTransactionObject = (ContextSourceAndDataSourceTransactionObject) status + .getTransaction(); + + try { + 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."); + } + } + 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) + */ + 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())); + } + + public ContextSource getContextSource() { + return ldapManagerDelegate.getContextSource(); + } + + public void setContextSource(ContextSource contextSource) { + ldapManagerDelegate.setContextSource(contextSource); + } + + 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) { + this.ldapTransactionObject = ldapTransactionObject; + this.dataSourceTransactionObject = dataSourceTransactionObject; + } + + public Object getDataSourceTransactionObject() { + return dataSourceTransactionObject; + } + + public Object getLdapTransactionObject() { + return ldapTransactionObject; + } + } + + /* + * @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"); + } + + /* + * @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"); + } + + 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/ContextSourceTransactionManager.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/ContextSourceTransactionManager.java index 0730d92e..000843ef 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 @@ -1,196 +1,196 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.transaction.compensating.manager; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; -import org.springframework.ldap.transaction.compensating.UnbindOperationExecutor; -import org.springframework.ldap.transaction.compensating.support.DefaultTempEntryRenamingStrategy; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionException; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; -import org.springframework.transaction.compensating.support.CompensatingTransactionObject; -import org.springframework.transaction.compensating.support.DefaultCompensatingTransactionOperationManager; -import org.springframework.transaction.support.AbstractPlatformTransactionManager; -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. - *

- * 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.
  • - *
- *

- * 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. - *

- * 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 - * {@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. - *

- * - * @author Mattias Hellborg Arthursson - * - * @see ContextSourceAndDataSourceTransactionManager - * @see ContextSourceTransactionManagerDelegate - * @see DefaultCompensatingTransactionOperationManager - * @see TempEntryRenamingStrategy - * @see TransactionAwareContextSourceProxy - * @since 1.2 - */ -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) - */ - protected void doBegin(Object transaction, TransactionDefinition definition) { - delegate.doBegin(transaction, definition); - } - - /* - * @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) - */ - protected void doCommit(DefaultTransactionStatus status) { - delegate.doCommit(status); - } - - /* - * @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) - */ - protected void doRollback(DefaultTransactionStatus status) { - delegate.doRollback(status); - } - - /** - * Get the ContextSource. - * - * @return the contextSource. - * @see ContextSourceTransactionManagerDelegate#getContextSource() - */ - public ContextSource getContextSource() { - return delegate.getContextSource(); - } - - /** - * Set the ContextSource. - * - * @param contextSource - * the ContextSource. - * @see ContextSourceTransactionManagerDelegate#setContextSource(ContextSource) - */ - public void setContextSource(ContextSource contextSource) { - delegate.setContextSource(contextSource); - } - - /** - * Set the {@link TempEntryRenamingStrategy}. - * - * @param renamingStrategy - * the Renaming Strategy. - * @see ContextSourceTransactionManagerDelegate#setRenamingStrategy(TempEntryRenamingStrategy) - */ - public void setRenamingStrategy(TempEntryRenamingStrategy renamingStrategy) { - delegate.setRenamingStrategy(renamingStrategy); - } - - public void afterPropertiesSet() throws Exception { - delegate.checkRenamingStrategy(); - } - - @Override - protected boolean isExistingTransaction(Object transaction) - throws TransactionException { - CompensatingTransactionObject txObject = (CompensatingTransactionObject) transaction; - return (txObject.getHolder() != null); - } +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.transaction.compensating.manager; + +import org.springframework.beans.factory.InitializingBean; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; +import org.springframework.ldap.transaction.compensating.UnbindOperationExecutor; +import org.springframework.ldap.transaction.compensating.support.DefaultTempEntryRenamingStrategy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionException; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; +import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; +import org.springframework.transaction.compensating.support.CompensatingTransactionObject; +import org.springframework.transaction.compensating.support.DefaultCompensatingTransactionOperationManager; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +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. + *

+ * 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.
  • + *
+ *

+ * 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. + *

+ * 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 + * {@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. + *

+ * + * @author Mattias Hellborg Arthursson + * + * @see ContextSourceAndDataSourceTransactionManager + * @see ContextSourceTransactionManagerDelegate + * @see DefaultCompensatingTransactionOperationManager + * @see TempEntryRenamingStrategy + * @see TransactionAwareContextSourceProxy + * @since 1.2 + */ +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) + */ + protected void doBegin(Object transaction, TransactionDefinition definition) { + delegate.doBegin(transaction, definition); + } + + /* + * @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) + */ + protected void doCommit(DefaultTransactionStatus status) { + delegate.doCommit(status); + } + + /* + * @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) + */ + protected void doRollback(DefaultTransactionStatus status) { + delegate.doRollback(status); + } + + /** + * Get the ContextSource. + * + * @return the contextSource. + * @see ContextSourceTransactionManagerDelegate#getContextSource() + */ + public ContextSource getContextSource() { + return delegate.getContextSource(); + } + + /** + * Set the ContextSource. + * + * @param contextSource + * the ContextSource. + * @see ContextSourceTransactionManagerDelegate#setContextSource(ContextSource) + */ + public void setContextSource(ContextSource contextSource) { + delegate.setContextSource(contextSource); + } + + /** + * Set the {@link TempEntryRenamingStrategy}. + * + * @param renamingStrategy + * the Renaming Strategy. + * @see ContextSourceTransactionManagerDelegate#setRenamingStrategy(TempEntryRenamingStrategy) + */ + public void setRenamingStrategy(TempEntryRenamingStrategy renamingStrategy) { + delegate.setRenamingStrategy(renamingStrategy); + } + + public void afterPropertiesSet() throws Exception { + delegate.checkRenamingStrategy(); + } + + @Override + 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/DirContextHolder.java b/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/DirContextHolder.java index 9a8bc826..fa1cfb2e 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 @@ -1,73 +1,73 @@ -/* - * Copyright 2002-2007 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.manager; - -import javax.naming.directory.DirContext; - -import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; -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. - * - * @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. - */ - 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. - */ - public void setCtx(DirContext ctx) { - this.ctx = ctx; - } - - /** - * Return the DirContext associated with the current transaction. - */ - public DirContext getCtx() { - return ctx; - } - - /* - * @see org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport#getTransactedResource() - */ - protected Object getTransactedResource() { - return ctx; - } -} +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.manager; + +import javax.naming.directory.DirContext; + +import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; +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. + * + * @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. + */ + 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. + */ + public void setCtx(DirContext ctx) { + this.ctx = ctx; + } + + /** + * Return the DirContext associated with the current transaction. + */ + public DirContext getCtx() { + return ctx; + } + + /* + * @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 755b5106..645aaa99 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 @@ -1,100 +1,100 @@ -/* - * Copyright 2002-2007 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.manager; - -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.core.DirContextProxy; -import org.springframework.ldap.core.support.DelegatingBaseLdapPathContextSourceSupport; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -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}. - * - * @author Mattias Hellborg Arthursson - * @since 1.2 - */ -public class TransactionAwareContextSourceProxy - extends DelegatingBaseLdapPathContextSourceSupport - implements ContextSource { - - private ContextSource target; - - /** - * Constructor. - * - * @param target - * the target ContextSource. - */ - public TransactionAwareContextSourceProxy(ContextSource target) { - this.target = target; - } - - @Override - public ContextSource getTarget() { - return target; - } - - @Override - public DirContext getReadOnlyContext() { - 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)); - - } - - @Override - public DirContext getReadWriteContext() { - DirContextHolder contextHolder = (DirContextHolder) TransactionSynchronizationManager - .getResource(target); - DirContext ctx = null; - - if (contextHolder != null) { - ctx = contextHolder.getCtx(); - } - - if (ctx == null) { - ctx = target.getReadWriteContext(); - if (contextHolder != null) { - contextHolder.setCtx(ctx); - } - } - return getTransactionAwareDirContextProxy(ctx, target); - } - - @Override - public DirContext getContext(String principal, String credentials) { - return target.getContext(principal, credentials); - } -} +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.manager; + +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextProxy; +import org.springframework.ldap.core.support.DelegatingBaseLdapPathContextSourceSupport; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +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}. + * + * @author Mattias Hellborg Arthursson + * @since 1.2 + */ +public class TransactionAwareContextSourceProxy + extends DelegatingBaseLdapPathContextSourceSupport + implements ContextSource { + + private ContextSource target; + + /** + * Constructor. + * + * @param target + * the target ContextSource. + */ + public TransactionAwareContextSourceProxy(ContextSource target) { + this.target = target; + } + + @Override + public ContextSource getTarget() { + return target; + } + + @Override + public DirContext getReadOnlyContext() { + 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)); + + } + + @Override + public DirContext getReadWriteContext() { + DirContextHolder contextHolder = (DirContextHolder) TransactionSynchronizationManager + .getResource(target); + DirContext ctx = null; + + if (contextHolder != null) { + ctx = contextHolder.getCtx(); + } + + if (ctx == null) { + ctx = target.getReadWriteContext(); + if (contextHolder != null) { + contextHolder.setCtx(ctx); + } + } + return getTransactionAwareDirContextProxy(ctx, target); + } + + @Override + public DirContext getContext(String principal, String credentials) { + return target.getContext(principal, credentials); + } +} 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 9589760a..87f49137 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 @@ -1,96 +1,96 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.support; - -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; - -import javax.naming.InvalidNameException; -import javax.naming.Name; -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: - * - *

- * 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. - * - * @author Mattias Hellborg Arthursson - * @since 1.2 - */ -public class DefaultTempEntryRenamingStrategy implements - TempEntryRenamingStrategy { - - /** - * The default temp entry suffix, "_temp". - */ - public static final String DEFAULT_TEMP_SUFFIX = "_temp"; - - private String tempSuffix = DEFAULT_TEMP_SUFFIX; - - /* - * @see org.springframework.ldap.support.transaction.TempEntryRenamingStrategy#getTemporaryName(javax.naming.Name) - */ - public Name getTemporaryName(Name originalName) { - LdapName temporaryName = LdapUtils.newLdapName(originalName); - - // 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) { - throw new org.springframework.ldap.InvalidNameException(e); - } - - return temporaryName; - } - - /** - * Get the suffix that will be used for renaming temporary entries. - * - * @return the suffix. - */ - public String getTempSuffix() { - return tempSuffix; - } - - /** - * Set the suffix to use for renaming temporary entries. Default value is - * {@link #DEFAULT_TEMP_SUFFIX}. - * - * @param tempSuffix - * the suffix. - */ - public void setTempSuffix(String tempSuffix) { - this.tempSuffix = tempSuffix; - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.support; + +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; + +import javax.naming.InvalidNameException; +import javax.naming.Name; +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: + * + *

+ * 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. + * + * @author Mattias Hellborg Arthursson + * @since 1.2 + */ +public class DefaultTempEntryRenamingStrategy implements + TempEntryRenamingStrategy { + + /** + * The default temp entry suffix, "_temp". + */ + public static final String DEFAULT_TEMP_SUFFIX = "_temp"; + + private String tempSuffix = DEFAULT_TEMP_SUFFIX; + + /* + * @see org.springframework.ldap.support.transaction.TempEntryRenamingStrategy#getTemporaryName(javax.naming.Name) + */ + public Name getTemporaryName(Name originalName) { + LdapName temporaryName = LdapUtils.newLdapName(originalName); + + // 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) { + throw new org.springframework.ldap.InvalidNameException(e); + } + + return temporaryName; + } + + /** + * Get the suffix that will be used for renaming temporary entries. + * + * @return the suffix. + */ + public String getTempSuffix() { + return tempSuffix; + } + + /** + * Set the suffix to use for renaming temporary entries. Default value is + * {@link #DEFAULT_TEMP_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 6dea982e..271050a5 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 @@ -1,91 +1,91 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.transaction.compensating.support; - -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; - -import javax.naming.InvalidNameException; -import javax.naming.Name; -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. - *

- * 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 { - - private Name subtreeNode; - - private static final AtomicInteger NEXT_SEQUENCE_NO = new AtomicInteger(1); - - public DifferentSubtreeTempEntryRenamingStrategy(Name subtreeNode) { - this.subtreeNode = subtreeNode; - } - - public DifferentSubtreeTempEntryRenamingStrategy(String subtreeNode) { - this(LdapUtils.newLdapName(subtreeNode)); - } - - public Name getSubtreeNode() { - return subtreeNode; - } - - public void setSubtreeNode(Name subtreeNode) { - this.subtreeNode = subtreeNode; - } - - int getNextSequenceNo() { - return NEXT_SEQUENCE_NO.get(); - } - - /* - * @see org.springframework.ldap.support.transaction.TempEntryRenamingStrategy#getTemporaryName(javax.naming.Name) - */ - public Name getTemporaryName(Name originalName) { - int thisSequenceNo = NEXT_SEQUENCE_NO.getAndIncrement(); - - LdapName tempName = LdapUtils.newLdapName(originalName); - try { - String leafNode = tempName.get(tempName.size() - 1) + thisSequenceNo; - LdapName newName = LdapUtils.newLdapName(subtreeNode); - newName.add(leafNode); - - return newName; - } catch (InvalidNameException e) { - throw new org.springframework.ldap.InvalidNameException(e); - } - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.transaction.compensating.support; + +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; + +import javax.naming.InvalidNameException; +import javax.naming.Name; +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. + *

+ * 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 { + + private Name subtreeNode; + + private static final AtomicInteger NEXT_SEQUENCE_NO = new AtomicInteger(1); + + public DifferentSubtreeTempEntryRenamingStrategy(Name subtreeNode) { + this.subtreeNode = subtreeNode; + } + + public DifferentSubtreeTempEntryRenamingStrategy(String subtreeNode) { + this(LdapUtils.newLdapName(subtreeNode)); + } + + public Name getSubtreeNode() { + return subtreeNode; + } + + public void setSubtreeNode(Name subtreeNode) { + this.subtreeNode = subtreeNode; + } + + int getNextSequenceNo() { + return NEXT_SEQUENCE_NO.get(); + } + + /* + * @see org.springframework.ldap.support.transaction.TempEntryRenamingStrategy#getTemporaryName(javax.naming.Name) + */ + public Name getTemporaryName(Name originalName) { + int thisSequenceNo = NEXT_SEQUENCE_NO.getAndIncrement(); + + LdapName tempName = LdapUtils.newLdapName(originalName); + try { + String leafNode = tempName.get(tempName.size() - 1) + thisSequenceNo; + LdapName newName = LdapUtils.newLdapName(subtreeNode); + newName.add(leafNode); + + return newName; + } 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 94ffbb50..eea6542a 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationExecutor.java +++ b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationExecutor.java @@ -1,62 +1,62 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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. - *

- * 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. - */ - 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. - */ - 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. - */ - void performOperation(); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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. + *

+ * 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. + */ + 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. + */ + 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. + */ + 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 b622c128..f7f0406b 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationFactory.java +++ b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationFactory.java @@ -1,44 +1,44 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.transaction.compensating; - -import org.springframework.transaction.compensating.support.DefaultCompensatingTransactionOperationManager; - -/** - * 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. - * - * @return a new {@link CompensatingTransactionOperationRecorder} instance. - */ - CompensatingTransactionOperationRecorder createRecordingOperation( - Object resource, String method); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.transaction.compensating; + +import org.springframework.transaction.compensating.support.DefaultCompensatingTransactionOperationManager; + +/** + * 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. + * + * @return a new {@link CompensatingTransactionOperationRecorder} instance. + */ + 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 9c11e149..eee9d931 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationManager.java +++ b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationManager.java @@ -1,55 +1,55 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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. - * - * @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. - */ - 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. - */ - void commit(); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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. + * + * @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. + */ + 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. + */ + 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 30f47d26..b3c1fb5c 100644 --- a/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationRecorder.java +++ b/core/src/main/java/org/springframework/transaction/compensating/CompensatingTransactionOperationRecorder.java @@ -1,41 +1,41 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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. - * - * @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. - */ - CompensatingTransactionOperationExecutor recordOperation( - Object[] args); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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. + * + * @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. + */ + CompensatingTransactionOperationExecutor recordOperation( + Object[] args); +} 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 e62235d8..3bfb4dc5 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 @@ -1,80 +1,80 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.transaction.compensating.support; - -import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; -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 { - - private CompensatingTransactionOperationManager transactionOperationManager; - - /** - * Constructor. - * - * @param manager - * The {@link CompensatingTransactionOperationManager} to use for - * creating Compensating operations. - */ - public CompensatingTransactionHolderSupport( - CompensatingTransactionOperationManager manager) { - this.transactionOperationManager = manager; - } - - /** - * Get the actual transacted resource. - * - * @return the transaction's target resource - */ - protected abstract Object getTransactedResource(); - - /* - * @see org.springframework.transaction.support.ResourceHolderSupport#clear() - */ - public void clear() { - super.clear(); - transactionOperationManager = null; - } - - /** - * Get the CompensatingTransactionOperationManager to handle the data for - * the current transaction. - * - * @return the CompensatingTransactionOperationManager. - */ - public CompensatingTransactionOperationManager getTransactionOperationManager() { - return transactionOperationManager; - } - - /** - * Set the CompensatingTransactionOperationManager. For testing purposes - * only. - * - * @param transactionOperationManager - * the CompensatingTransactionOperationManager to use. - */ - public void setTransactionOperationManager( - CompensatingTransactionOperationManager transactionOperationManager) { - this.transactionOperationManager = transactionOperationManager; - } +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.transaction.compensating.support; + +import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; +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 { + + private CompensatingTransactionOperationManager transactionOperationManager; + + /** + * Constructor. + * + * @param manager + * The {@link CompensatingTransactionOperationManager} to use for + * creating Compensating operations. + */ + public CompensatingTransactionHolderSupport( + CompensatingTransactionOperationManager manager) { + this.transactionOperationManager = manager; + } + + /** + * Get the actual transacted resource. + * + * @return the transaction's target resource + */ + protected abstract Object getTransactedResource(); + + /* + * @see org.springframework.transaction.support.ResourceHolderSupport#clear() + */ + public void clear() { + super.clear(); + transactionOperationManager = null; + } + + /** + * Get the CompensatingTransactionOperationManager to handle the data for + * the current transaction. + * + * @return the CompensatingTransactionOperationManager. + */ + public CompensatingTransactionOperationManager getTransactionOperationManager() { + return transactionOperationManager; + } + + /** + * Set the CompensatingTransactionOperationManager. For testing purposes + * only. + * + * @param transactionOperationManager + * the CompensatingTransactionOperationManager to use. + */ + 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 dc609ae2..94bdb067 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 @@ -1,62 +1,62 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.transaction.compensating.support; - -/** - * 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. - */ - public CompensatingTransactionObject( - CompensatingTransactionHolderSupport holder) { - this.holder = holder; - } - - /** - * Get the DirContextHolder. - * - * @return the DirContextHolder. - */ - public CompensatingTransactionHolderSupport getHolder() { - return holder; - } - - /** - * Set 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; - } +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.transaction.compensating.support; + +/** + * 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. + */ + public CompensatingTransactionObject( + CompensatingTransactionHolderSupport holder) { + this.holder = holder; + } + + /** + * Get the DirContextHolder. + * + * @return the DirContextHolder. + */ + public CompensatingTransactionHolderSupport getHolder() { + return holder; + } + + /** + * Set 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 cb065452..812df555 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 @@ -1,76 +1,76 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.transaction.compensating.support; - -import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -/** - * Common methods for use with compensating transactions. - * - * @author Mattias Hellborg Arthursson - * @since 1.2 - */ -public final class CompensatingTransactionUtils { - - /** - * Not to be instantiated. - */ - private 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. - */ - 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 { - // Perform the target operation - try { - method.invoke(target, args); - } catch (InvocationTargetException e) { - throw e.getTargetException(); - } - } - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.transaction.compensating.support; + +import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * Common methods for use with compensating transactions. + * + * @author Mattias Hellborg Arthursson + * @since 1.2 + */ +public final class CompensatingTransactionUtils { + + /** + * Not to be instantiated. + */ + private 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. + */ + 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 { + // Perform the target operation + try { + method.invoke(target, args); + } catch (InvocationTargetException e) { + throw e.getTargetException(); + } + } + } + +} 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 5c75f666..c3b7d59c 100644 --- a/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java +++ b/core/src/test/java/org/springframework/ldap/authentication/DefaultValuesAuthenticationSourceDecoratorTest.java @@ -1,115 +1,115 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.authentication; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.AuthenticationSource; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class DefaultValuesAuthenticationSourceDecoratorTest { - - private static final String DEFAULT_PASSWORD = "defaultPassword"; - - private static final String DEFAULT_USER = "cn=defaultUser"; - - private DefaultValuesAuthenticationSourceDecorator tested; - - private AuthenticationSource authenticationSourceMock; - - @Before - public void setUp() throws Exception { - authenticationSourceMock = mock(AuthenticationSource.class); - tested = new DefaultValuesAuthenticationSourceDecorator(); - tested.setDefaultUser(DEFAULT_USER); - tested.setDefaultPassword(DEFAULT_PASSWORD); - tested.setTarget(authenticationSourceMock); - } - - @Test - public void testGetPrincipal_TargetHasPrincipal() { - when(authenticationSourceMock.getPrincipal()).thenReturn("cn=someUser"); - String principal = tested.getPrincipal(); - - assertThat(principal).isEqualTo("cn=someUser"); - } - - @Test - public void testGetPrincipal_TargetHasNoPrincipal() { - when(authenticationSourceMock.getPrincipal()).thenReturn(""); - - String principal = tested.getPrincipal(); - - assertThat(principal).isEqualTo(DEFAULT_USER); - } - - @Test - public void testGetCredentials_TargetHasPrincipal() { - when(authenticationSourceMock.getPrincipal()).thenReturn("cn=someUser"); - when(authenticationSourceMock.getCredentials()).thenReturn("somepassword"); - - String credentials = tested.getCredentials(); - - assertThat(credentials).isEqualTo("somepassword"); - } - - @Test - public void testGetCredentials_TargetHasNoPrincipal() { - when(authenticationSourceMock.getPrincipal()).thenReturn(""); - when(authenticationSourceMock.getCredentials()).thenReturn("somepassword"); - - String credentials = tested.getCredentials(); - - assertThat(credentials).isEqualTo(DEFAULT_PASSWORD); - } - - @Test - public void testAfterPropertiesSet_noTarget() throws Exception { - tested.setTarget(null); - try { - tested.afterPropertiesSet(); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testAfterPropertiesSet_noDefaultUser() throws Exception { - tested.setDefaultUser(null); - try { - tested.afterPropertiesSet(); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testAfterPropertiesSet_noDefaultPassword() throws Exception { - tested.setDefaultPassword(null); - try { - tested.afterPropertiesSet(); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.authentication; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.AuthenticationSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class DefaultValuesAuthenticationSourceDecoratorTest { + + private static final String DEFAULT_PASSWORD = "defaultPassword"; + + private static final String DEFAULT_USER = "cn=defaultUser"; + + private DefaultValuesAuthenticationSourceDecorator tested; + + private AuthenticationSource authenticationSourceMock; + + @Before + public void setUp() throws Exception { + authenticationSourceMock = mock(AuthenticationSource.class); + tested = new DefaultValuesAuthenticationSourceDecorator(); + tested.setDefaultUser(DEFAULT_USER); + tested.setDefaultPassword(DEFAULT_PASSWORD); + tested.setTarget(authenticationSourceMock); + } + + @Test + public void testGetPrincipal_TargetHasPrincipal() { + when(authenticationSourceMock.getPrincipal()).thenReturn("cn=someUser"); + String principal = tested.getPrincipal(); + + assertThat(principal).isEqualTo("cn=someUser"); + } + + @Test + public void testGetPrincipal_TargetHasNoPrincipal() { + when(authenticationSourceMock.getPrincipal()).thenReturn(""); + + String principal = tested.getPrincipal(); + + assertThat(principal).isEqualTo(DEFAULT_USER); + } + + @Test + public void testGetCredentials_TargetHasPrincipal() { + when(authenticationSourceMock.getPrincipal()).thenReturn("cn=someUser"); + when(authenticationSourceMock.getCredentials()).thenReturn("somepassword"); + + String credentials = tested.getCredentials(); + + assertThat(credentials).isEqualTo("somepassword"); + } + + @Test + public void testGetCredentials_TargetHasNoPrincipal() { + when(authenticationSourceMock.getPrincipal()).thenReturn(""); + when(authenticationSourceMock.getCredentials()).thenReturn("somepassword"); + + String credentials = tested.getCredentials(); + + assertThat(credentials).isEqualTo(DEFAULT_PASSWORD); + } + + @Test + public void testAfterPropertiesSet_noTarget() throws Exception { + tested.setTarget(null); + try { + tested.afterPropertiesSet(); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testAfterPropertiesSet_noDefaultUser() throws Exception { + tested.setDefaultUser(null); + try { + tested.afterPropertiesSet(); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testAfterPropertiesSet_noDefaultPassword() throws Exception { + tested.setDefaultPassword(null); + try { + tested.afterPropertiesSet(); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + } +} 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 83a2242f..3e1388bd 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultTest.java @@ -1,54 +1,54 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.control; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; - -import javax.naming.ldap.PagedResultsControl; -import java.util.LinkedList; -import java.util.List; - -/** - * 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(); - expectedList.add("dummy"); - 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)) { - - }; - - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.control; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import javax.naming.ldap.PagedResultsControl; +import java.util.LinkedList; +import java.util.List; + +/** + * 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(); + expectedList.add("dummy"); + 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)) { + + }; + + 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 5027c322..eef8c545 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultsCookieTest.java @@ -1,42 +1,42 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.control; - -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) { - - }; - - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.control; + +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) { + + }; + + 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 210cada4..9b31bb0e 100644 --- a/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/PagedResultsDirContextProcessorTest.java @@ -1,180 +1,180 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.control; - -import com.sun.jndi.ldap.Ber; -import com.sun.jndi.ldap.BerDecoder; -import com.sun.jndi.ldap.BerEncoder; -import com.sun.jndi.ldap.ctl.DirSyncResponseControl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import javax.naming.ldap.Control; -import javax.naming.ldap.LdapContext; -import javax.naming.ldap.PagedResultsControl; -import javax.naming.ldap.PagedResultsResponseControl; -import java.io.IOException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class PagedResultsDirContextProcessorTest { - - private LdapContext ldapContextMock; - - private PagedResultsDirContextProcessor tested; - - @Before - public void setUp() throws Exception { - - tested = new PagedResultsDirContextProcessor(20); - - // Create ldapContext mock - ldapContextMock = mock(LdapContext.class); - } - - @After - public void tearDown() throws Exception { - - tested = null; - ldapContextMock = null; - } - - @Test - public void testCreateRequestControl() throws Exception { - 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); - - PagedResultsControl control = (PagedResultsControl) tested - .createRequestControl(); - assertThat(control).isNotNull(); - } - - @Test - public void testPostProcess() throws Exception { - int resultSize = 50; - byte pageSize = 8; - - byte[] value = new byte[1]; - value[0] = pageSize; - byte[] cookie = encodeValue(resultSize, value); - 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(tested.getPageSize()).isEqualTo(20); - assertThat(tested.getResultSize()).isEqualTo(50); - } - - @Test - public void testPostProcess_InvalidResponseControl() throws Exception { - int resultSize = 50; - byte pageSize = 8; - - byte[] value = new byte[1]; - value[0] = pageSize; - byte[] cookie = encodeDirSyncValue(resultSize, value); - - // Using another response control to verify that it is ignored - DirSyncResponseControl control = new DirSyncResponseControl( - "dummy", true, cookie); - - - when(ldapContextMock.getResponseControls()).thenReturn(new Control[]{control}); - tested.postProcess(ldapContextMock); - - assertThat(tested.getCookie()).isNull(); - assertThat(tested.getPageSize()).isEqualTo(20); - assertThat(tested.getResultSize()).isEqualTo(0); - } - - @Test - public void testPostProcess_NoResponseControls() throws Exception { - when(ldapContextMock.getResponseControls()).thenReturn(null); - - tested.postProcess(ldapContextMock); - - assertThat(tested.getCookie()).isNull(); - assertThat(tested.getPageSize()).isEqualTo(20); - assertThat(tested.getResultSize()).isEqualTo(0); - } - - @Test - public void testBerDecoding() throws Exception { - byte[] value = new byte[1]; - value[0] = 8; - int pageSize = 20; - byte[] cookie = encodeValue(pageSize, value); - - BerDecoder ber = new BerDecoder(cookie, 0, cookie.length); - - ber.parseSeq(null); - int actualPageSize = ber.parseInt(); - byte[] actualValue = ber.parseOctetString(Ber.ASN_OCTET_STR, null); - - assertThat(actualPageSize).as("pageSize,").isEqualTo(20); - assertThat(actualValue.length).as("value length").isEqualTo(value.length); - for (int i = 0; i < value.length; i++) { - assertThat(actualValue[i]).as("value (index " + i + "),").isEqualTo(value[i]); - } - } - - private byte[] encodeValue(int pageSize, byte[] cookie) - throws IOException { - - // build the ASN.1 encoding - BerEncoder ber = new BerEncoder(10 + cookie.length); - - ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); - ber.encodeInt(pageSize); - ber.encodeOctetString(cookie, Ber.ASN_OCTET_STR); - ber.endSeq(); - - return ber.getTrimmedBuf(); - } - - /** - * Encode a value suitable for the DirSyncResponseControl used in a test. - */ - private byte[] encodeDirSyncValue(int pageSize, byte[] cookie) - throws IOException { - - // build the ASN.1 encoding - BerEncoder ber = new BerEncoder(10 + cookie.length); - - ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); - ber.encodeInt(1); // flag - ber.encodeInt(pageSize); // maxReturnLength - ber.encodeOctetString(cookie, Ber.ASN_OCTET_STR); - ber.endSeq(); - - return ber.getTrimmedBuf(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.control; + +import com.sun.jndi.ldap.Ber; +import com.sun.jndi.ldap.BerDecoder; +import com.sun.jndi.ldap.BerEncoder; +import com.sun.jndi.ldap.ctl.DirSyncResponseControl; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.naming.ldap.Control; +import javax.naming.ldap.LdapContext; +import javax.naming.ldap.PagedResultsControl; +import javax.naming.ldap.PagedResultsResponseControl; +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class PagedResultsDirContextProcessorTest { + + private LdapContext ldapContextMock; + + private PagedResultsDirContextProcessor tested; + + @Before + public void setUp() throws Exception { + + tested = new PagedResultsDirContextProcessor(20); + + // Create ldapContext mock + ldapContextMock = mock(LdapContext.class); + } + + @After + public void tearDown() throws Exception { + + tested = null; + ldapContextMock = null; + } + + @Test + public void testCreateRequestControl() throws Exception { + 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); + + PagedResultsControl control = (PagedResultsControl) tested + .createRequestControl(); + assertThat(control).isNotNull(); + } + + @Test + public void testPostProcess() throws Exception { + int resultSize = 50; + byte pageSize = 8; + + byte[] value = new byte[1]; + value[0] = pageSize; + byte[] cookie = encodeValue(resultSize, value); + 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(tested.getPageSize()).isEqualTo(20); + assertThat(tested.getResultSize()).isEqualTo(50); + } + + @Test + public void testPostProcess_InvalidResponseControl() throws Exception { + int resultSize = 50; + byte pageSize = 8; + + byte[] value = new byte[1]; + value[0] = pageSize; + byte[] cookie = encodeDirSyncValue(resultSize, value); + + // Using another response control to verify that it is ignored + DirSyncResponseControl control = new DirSyncResponseControl( + "dummy", true, cookie); + + + when(ldapContextMock.getResponseControls()).thenReturn(new Control[]{control}); + tested.postProcess(ldapContextMock); + + assertThat(tested.getCookie()).isNull(); + assertThat(tested.getPageSize()).isEqualTo(20); + assertThat(tested.getResultSize()).isEqualTo(0); + } + + @Test + public void testPostProcess_NoResponseControls() throws Exception { + when(ldapContextMock.getResponseControls()).thenReturn(null); + + tested.postProcess(ldapContextMock); + + assertThat(tested.getCookie()).isNull(); + assertThat(tested.getPageSize()).isEqualTo(20); + assertThat(tested.getResultSize()).isEqualTo(0); + } + + @Test + public void testBerDecoding() throws Exception { + byte[] value = new byte[1]; + value[0] = 8; + int pageSize = 20; + byte[] cookie = encodeValue(pageSize, value); + + BerDecoder ber = new BerDecoder(cookie, 0, cookie.length); + + ber.parseSeq(null); + int actualPageSize = ber.parseInt(); + byte[] actualValue = ber.parseOctetString(Ber.ASN_OCTET_STR, null); + + assertThat(actualPageSize).as("pageSize,").isEqualTo(20); + assertThat(actualValue.length).as("value length").isEqualTo(value.length); + for (int i = 0; i < value.length; i++) { + assertThat(actualValue[i]).as("value (index " + i + "),").isEqualTo(value[i]); + } + } + + private byte[] encodeValue(int pageSize, byte[] cookie) + throws IOException { + + // build the ASN.1 encoding + BerEncoder ber = new BerEncoder(10 + cookie.length); + + ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); + ber.encodeInt(pageSize); + ber.encodeOctetString(cookie, Ber.ASN_OCTET_STR); + ber.endSeq(); + + return ber.getTrimmedBuf(); + } + + /** + * Encode a value suitable for the DirSyncResponseControl used in a test. + */ + private byte[] encodeDirSyncValue(int pageSize, byte[] cookie) + throws IOException { + + // build the ASN.1 encoding + BerEncoder ber = new BerEncoder(10 + cookie.length); + + ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); + ber.encodeInt(1); // flag + ber.encodeInt(pageSize); // maxReturnLength + ber.encodeOctetString(cookie, Ber.ASN_OCTET_STR); + ber.endSeq(); + + 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 7b524752..b35faab9 100644 --- a/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/RequestControlDirContextProcessorTest.java @@ -1,130 +1,130 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.control; - -import javax.naming.ldap.SortControl; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.ldap.Control; -import javax.naming.ldap.LdapContext; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class RequestControlDirContextProcessorTest { - - private AbstractRequestControlDirContextProcessor tested; - - private Control requestControlMock; - - private Control requestControl2Mock; - - private LdapContext ldapContextMock; - - private DirContext dirContextMock; - - @Before - public void setUp() throws Exception { - // Create requestControl mock - requestControlMock = mock(Control.class); - - // Create requestControl2 mock - requestControl2Mock = mock(Control.class); - - // Create ldapContext mock - ldapContextMock = mock(LdapContext.class); - - // Create dirContext mock - dirContextMock = mock(DirContext.class); - - tested = new AbstractRequestControlDirContextProcessor() { - - public Control createRequestControl() { - return requestControlMock; - } - - public void postProcess(DirContext ctx) throws NamingException { - } - - }; - } - - @After - public void tearDown() throws Exception { - requestControlMock = null; - requestControl2Mock = null; - ldapContextMock = null; - dirContextMock = null; - - } - - @Test - public void testPreProcessWithExistingControlOfDifferentClassShouldAdd() throws Exception { - SortControl existingControl = new SortControl(new String[] { "cn" }, true); - when(ldapContextMock.getRequestControls()).thenReturn(new Control[]{existingControl}); - - tested.preProcess(ldapContextMock); - - verify(ldapContextMock).setRequestControls(new Control[] { existingControl, requestControlMock }); - } - - @Test - public void testPreProcessWithExistingControlOfSameClassShouldReplace() throws Exception { - when(ldapContextMock.getRequestControls()).thenReturn(new Control[]{requestControl2Mock}); - - tested.preProcess(ldapContextMock); - - verify(ldapContextMock).setRequestControls(new Control[] { requestControlMock }); - } - - @Test - public void testPreProcessWithExistingControlOfSameClassAndPropertyFalseShouldAdd() throws Exception { - when(ldapContextMock.getRequestControls()).thenReturn(new Control[] { requestControl2Mock }); - - tested.setReplaceSameControlEnabled(false); - tested.preProcess(ldapContextMock); - - verify(ldapContextMock).setRequestControls(new Control[]{requestControl2Mock, requestControlMock}); - } - - @Test - public void testPreProcessWithNoExistingControlsShouldAdd() throws NamingException { - when(ldapContextMock.getRequestControls()).thenReturn(new Control[0]); - - tested.preProcess(ldapContextMock); - - verify(ldapContextMock).setRequestControls(new Control[]{requestControlMock}); - } - - @Test - public void testPreProcessWithNullControlsShouldAdd() throws NamingException { - when(ldapContextMock.getRequestControls()).thenReturn(null); - - tested.preProcess(ldapContextMock); - - verify(ldapContextMock).setRequestControls(new Control[] { requestControlMock }); - } - - @Test(expected = IllegalArgumentException.class) - public void testPreProcessWhenNotLdapContextShouldFail() throws Exception { - tested.preProcess(dirContextMock); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.control; + +import javax.naming.ldap.SortControl; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.ldap.Control; +import javax.naming.ldap.LdapContext; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class RequestControlDirContextProcessorTest { + + private AbstractRequestControlDirContextProcessor tested; + + private Control requestControlMock; + + private Control requestControl2Mock; + + private LdapContext ldapContextMock; + + private DirContext dirContextMock; + + @Before + public void setUp() throws Exception { + // Create requestControl mock + requestControlMock = mock(Control.class); + + // Create requestControl2 mock + requestControl2Mock = mock(Control.class); + + // Create ldapContext mock + ldapContextMock = mock(LdapContext.class); + + // Create dirContext mock + dirContextMock = mock(DirContext.class); + + tested = new AbstractRequestControlDirContextProcessor() { + + public Control createRequestControl() { + return requestControlMock; + } + + public void postProcess(DirContext ctx) throws NamingException { + } + + }; + } + + @After + public void tearDown() throws Exception { + requestControlMock = null; + requestControl2Mock = null; + ldapContextMock = null; + dirContextMock = null; + + } + + @Test + public void testPreProcessWithExistingControlOfDifferentClassShouldAdd() throws Exception { + SortControl existingControl = new SortControl(new String[] { "cn" }, true); + when(ldapContextMock.getRequestControls()).thenReturn(new Control[]{existingControl}); + + tested.preProcess(ldapContextMock); + + verify(ldapContextMock).setRequestControls(new Control[] { existingControl, requestControlMock }); + } + + @Test + public void testPreProcessWithExistingControlOfSameClassShouldReplace() throws Exception { + when(ldapContextMock.getRequestControls()).thenReturn(new Control[]{requestControl2Mock}); + + tested.preProcess(ldapContextMock); + + verify(ldapContextMock).setRequestControls(new Control[] { requestControlMock }); + } + + @Test + public void testPreProcessWithExistingControlOfSameClassAndPropertyFalseShouldAdd() throws Exception { + when(ldapContextMock.getRequestControls()).thenReturn(new Control[] { requestControl2Mock }); + + tested.setReplaceSameControlEnabled(false); + tested.preProcess(ldapContextMock); + + verify(ldapContextMock).setRequestControls(new Control[]{requestControl2Mock, requestControlMock}); + } + + @Test + public void testPreProcessWithNoExistingControlsShouldAdd() throws NamingException { + when(ldapContextMock.getRequestControls()).thenReturn(new Control[0]); + + tested.preProcess(ldapContextMock); + + verify(ldapContextMock).setRequestControls(new Control[]{requestControlMock}); + } + + @Test + public void testPreProcessWithNullControlsShouldAdd() throws NamingException { + when(ldapContextMock.getRequestControls()).thenReturn(null); + + tested.preProcess(ldapContextMock); + + verify(ldapContextMock).setRequestControls(new Control[] { requestControlMock }); + } + + @Test(expected = IllegalArgumentException.class) + 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 ac4ff8a8..a88ad8c9 100644 --- a/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java +++ b/core/src/test/java/org/springframework/ldap/control/SortControlDirContextProcessorTest.java @@ -1,156 +1,156 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.control; - -import com.sun.jndi.ldap.Ber; -import com.sun.jndi.ldap.BerDecoder; -import com.sun.jndi.ldap.BerEncoder; -import com.sun.jndi.ldap.ctl.DirSyncResponseControl; -import org.junit.Before; -import org.junit.Test; - -import javax.naming.ldap.Control; -import javax.naming.ldap.LdapContext; -import javax.naming.ldap.SortControl; -import javax.naming.ldap.SortResponseControl; -import java.io.IOException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * Unit tests for the SortControlDirContextProcessor class. - * - * @author Ulrik Sandberg - */ -public class SortControlDirContextProcessorTest { - - private LdapContext ldapContextMock; - - private SortControlDirContextProcessor tested; - - @Before - public void setUp() throws Exception { - tested = new SortControlDirContextProcessor("key"); - - // Create ldapContext mock - ldapContextMock = mock(LdapContext.class); - } - - @Test - public void testCreateRequestControl() throws Exception { - SortControl result = (SortControl) tested.createRequestControl(); - assertThat(result).isNotNull(); - assertThat(result.getID()).isEqualTo("1.2.840.113556.1.4.473"); - assertThat(result.getEncodedValue().length).isEqualTo(9); - } - - @Test - public void testPostProcess() throws Exception { - byte sortResult = 0; // success - - byte[] value = encodeValue(sortResult); - SortResponseControl control = new SortResponseControl( - "dummy", true, value); - - when(ldapContextMock.getResponseControls()).thenReturn( new Control[]{control}); - - tested.postProcess(ldapContextMock); - - assertThat(tested.isSorted()).isEqualTo(true); - assertThat(tested.getResultCode()).isEqualTo(0); - } - - @Test - public void testPostProcess_NonSuccess() throws Exception { - byte sortResult = 1; - - byte[] value = encodeValue(sortResult); - SortResponseControl control = new SortResponseControl( - "dummy", true, value); - - when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); - - tested.postProcess(ldapContextMock); - - assertThat(tested.isSorted()).isEqualTo(false); - assertThat(tested.getResultCode()).isEqualTo(1); - } - - @Test - public void testPostProcess_InvalidResponseControl() throws Exception { - int resultSize = 50; - byte pageSize = 8; - - byte[] value = new byte[1]; - value[0] = pageSize; - byte[] cookie = encodeDirSyncValue(resultSize, value); - - // Using another response control to verify that it is ignored - DirSyncResponseControl control = new DirSyncResponseControl("dummy", - true, cookie); - - when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); - - tested.postProcess(ldapContextMock); - - assertThat(tested.isSorted()).isEqualTo(false); - } - - @Test - public void testBerDecoding() throws Exception { - int sortResult = 53; // unwilling to perform - byte[] encoded = encodeValue(sortResult); - - BerDecoder ber = new BerDecoder(encoded, 0, encoded.length); - - ber.parseSeq(null); - int actualSortResult = ber.parseEnumeration(); - - assertThat(actualSortResult).as("sortResult,").isEqualTo(53); - } - - private byte[] encodeValue(int sortResult) throws IOException { - - // build the ASN.1 encoding - BerEncoder ber = new BerEncoder(10); - - ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); - ber.encodeInt(sortResult, Ber.ASN_ENUMERATED); - ber.endSeq(); - - return ber.getTrimmedBuf(); - } - - /** - * Encode a value suitable for the DirSyncResponseControl used in a test. - */ - private byte[] encodeDirSyncValue(int pageSize, byte[] cookie) - throws IOException { - - // build the ASN.1 encoding - BerEncoder ber = new BerEncoder(10 + cookie.length); - - ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); - ber.encodeInt(1); // flag - ber.encodeInt(pageSize); // maxReturnLength - ber.encodeOctetString(cookie, Ber.ASN_OCTET_STR); - ber.endSeq(); - - return ber.getTrimmedBuf(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.control; + +import com.sun.jndi.ldap.Ber; +import com.sun.jndi.ldap.BerDecoder; +import com.sun.jndi.ldap.BerEncoder; +import com.sun.jndi.ldap.ctl.DirSyncResponseControl; +import org.junit.Before; +import org.junit.Test; + +import javax.naming.ldap.Control; +import javax.naming.ldap.LdapContext; +import javax.naming.ldap.SortControl; +import javax.naming.ldap.SortResponseControl; +import java.io.IOException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Unit tests for the SortControlDirContextProcessor class. + * + * @author Ulrik Sandberg + */ +public class SortControlDirContextProcessorTest { + + private LdapContext ldapContextMock; + + private SortControlDirContextProcessor tested; + + @Before + public void setUp() throws Exception { + tested = new SortControlDirContextProcessor("key"); + + // Create ldapContext mock + ldapContextMock = mock(LdapContext.class); + } + + @Test + public void testCreateRequestControl() throws Exception { + SortControl result = (SortControl) tested.createRequestControl(); + assertThat(result).isNotNull(); + assertThat(result.getID()).isEqualTo("1.2.840.113556.1.4.473"); + assertThat(result.getEncodedValue().length).isEqualTo(9); + } + + @Test + public void testPostProcess() throws Exception { + byte sortResult = 0; // success + + byte[] value = encodeValue(sortResult); + SortResponseControl control = new SortResponseControl( + "dummy", true, value); + + when(ldapContextMock.getResponseControls()).thenReturn( new Control[]{control}); + + tested.postProcess(ldapContextMock); + + assertThat(tested.isSorted()).isEqualTo(true); + assertThat(tested.getResultCode()).isEqualTo(0); + } + + @Test + public void testPostProcess_NonSuccess() throws Exception { + byte sortResult = 1; + + byte[] value = encodeValue(sortResult); + SortResponseControl control = new SortResponseControl( + "dummy", true, value); + + when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); + + tested.postProcess(ldapContextMock); + + assertThat(tested.isSorted()).isEqualTo(false); + assertThat(tested.getResultCode()).isEqualTo(1); + } + + @Test + public void testPostProcess_InvalidResponseControl() throws Exception { + int resultSize = 50; + byte pageSize = 8; + + byte[] value = new byte[1]; + value[0] = pageSize; + byte[] cookie = encodeDirSyncValue(resultSize, value); + + // Using another response control to verify that it is ignored + DirSyncResponseControl control = new DirSyncResponseControl("dummy", + true, cookie); + + when(ldapContextMock.getResponseControls()).thenReturn(new Control[] { control }); + + tested.postProcess(ldapContextMock); + + assertThat(tested.isSorted()).isEqualTo(false); + } + + @Test + public void testBerDecoding() throws Exception { + int sortResult = 53; // unwilling to perform + byte[] encoded = encodeValue(sortResult); + + BerDecoder ber = new BerDecoder(encoded, 0, encoded.length); + + ber.parseSeq(null); + int actualSortResult = ber.parseEnumeration(); + + assertThat(actualSortResult).as("sortResult,").isEqualTo(53); + } + + private byte[] encodeValue(int sortResult) throws IOException { + + // build the ASN.1 encoding + BerEncoder ber = new BerEncoder(10); + + ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); + ber.encodeInt(sortResult, Ber.ASN_ENUMERATED); + ber.endSeq(); + + return ber.getTrimmedBuf(); + } + + /** + * Encode a value suitable for the DirSyncResponseControl used in a test. + */ + private byte[] encodeDirSyncValue(int pageSize, byte[] cookie) + throws IOException { + + // build the ASN.1 encoding + BerEncoder ber = new BerEncoder(10 + cookie.length); + + ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR); + ber.encodeInt(1); // flag + ber.encodeInt(pageSize); // maxReturnLength + ber.encodeOctetString(cookie, Ber.ASN_OCTET_STR); + ber.endSeq(); + + return ber.getTrimmedBuf(); + } +} diff --git a/core/src/test/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandlerTest.java b/core/src/test/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandlerTest.java index 1d745c23..da423d0f 100644 --- a/core/src/test/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandlerTest.java +++ b/core/src/test/java/org/springframework/ldap/core/CollectingNameClassPairCallbackHandlerTest.java @@ -1,57 +1,57 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.junit.Before; -import org.junit.Test; - -import javax.naming.NameClassPair; -import javax.naming.NamingException; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertSame; - -public class CollectingNameClassPairCallbackHandlerTest { - - private CollectingNameClassPairCallbackHandler tested; - - private Object expectedResult; - - private NameClassPair expectedNameClassPair; - - @Before - public void setUp() throws Exception { - expectedResult = new Object(); - expectedNameClassPair = new NameClassPair(null, null); - tested = new CollectingNameClassPairCallbackHandler() { - public Object getObjectFromNameClassPair(NameClassPair nameClassPair) { - assertThat(nameClassPair).isSameAs(expectedNameClassPair); - return expectedResult; - } - }; - } - - @Test - public void testHandleNameClassPair() throws NamingException { - tested.handleNameClassPair(expectedNameClassPair); - List result = tested.getList(); - assertThat(result).hasSize(1); - assertThat(result.get(0)).isSameAs(expectedResult); - } - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.junit.Before; +import org.junit.Test; + +import javax.naming.NameClassPair; +import javax.naming.NamingException; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertSame; + +public class CollectingNameClassPairCallbackHandlerTest { + + private CollectingNameClassPairCallbackHandler tested; + + private Object expectedResult; + + private NameClassPair expectedNameClassPair; + + @Before + public void setUp() throws Exception { + expectedResult = new Object(); + expectedNameClassPair = new NameClassPair(null, null); + tested = new CollectingNameClassPairCallbackHandler() { + public Object getObjectFromNameClassPair(NameClassPair nameClassPair) { + assertThat(nameClassPair).isSameAs(expectedNameClassPair); + return expectedResult; + } + }; + } + + @Test + public void testHandleNameClassPair() throws NamingException { + tested.handleNameClassPair(expectedNameClassPair); + List result = tested.getList(); + assertThat(result).hasSize(1); + assertThat(result.get(0)).isSameAs(expectedResult); + } + +} 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 4e7a56bd..615fe5d7 100644 --- a/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DirContextAdapterBugTest.java @@ -1,96 +1,96 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core; - -import org.junit.Test; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.Name; -import javax.naming.directory.Attributes; -import javax.naming.directory.BasicAttributes; - -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 { - - @Test - public void testResetAttributeValuesNotReportedAsModifications() { - BasicAttributes attrs = new BasicAttributes("myattr", "a"); - attrs.get("myattr").add("b"); - attrs.get("myattr").add("c"); - UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName()); - - ctx.setAttributeValues("myattr", new String[] { "a", "b" }); - ctx.setAttributeValues("myattr", new String[] { "a", "b", "c" }); - - assertThat(ctx.getModificationItems().length).isEqualTo(0); - } - - @Test - public void testResetAttributeValuesSameLengthNotReportedAsModifications() { - BasicAttributes attrs = new BasicAttributes("myattr", "a"); - attrs.get("myattr").add("b"); - attrs.get("myattr").add("c"); - UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName()); - - ctx.setAttributeValues("myattr", new String[] { "a", "b", "d" }); - ctx.setAttributeValues("myattr", new String[] { "a", "b", "c" }); - - assertThat(ctx.getModificationItems().length).isEqualTo(0); - } - - /** - * 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 - public void testResetNullAttributeValuesReportedAsModifications() { - BasicAttributes attrs = new BasicAttributes("myattr", null); - UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName()); - - ctx.setAttributeValues("myattr", new String[] { "a" }); - ctx.setAttributeValues("myattr", null); - - assertThat(ctx.getModificationItems().length).isEqualTo(1); - } - - @Test - public void testResetNullAttributeValueNotReportedAsModification() throws Exception { - BasicAttributes attrs = new BasicAttributes("myattr", "b"); - UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName()); - - ctx.setAttributeValue("myattr", "a"); - ctx.setAttributeValue("myattr", "b"); - - assertThat(ctx.getModificationItems().length).isEqualTo(0); - } - - private static class UpdateAdapter extends DirContextAdapter { - public UpdateAdapter(Attributes attrs, Name dn) { - super(attrs, dn); - setUpdateMode(true); - } - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core; + +import org.junit.Test; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.Name; +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttributes; + +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 { + + @Test + public void testResetAttributeValuesNotReportedAsModifications() { + BasicAttributes attrs = new BasicAttributes("myattr", "a"); + attrs.get("myattr").add("b"); + attrs.get("myattr").add("c"); + UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName()); + + ctx.setAttributeValues("myattr", new String[] { "a", "b" }); + ctx.setAttributeValues("myattr", new String[] { "a", "b", "c" }); + + assertThat(ctx.getModificationItems().length).isEqualTo(0); + } + + @Test + public void testResetAttributeValuesSameLengthNotReportedAsModifications() { + BasicAttributes attrs = new BasicAttributes("myattr", "a"); + attrs.get("myattr").add("b"); + attrs.get("myattr").add("c"); + UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName()); + + ctx.setAttributeValues("myattr", new String[] { "a", "b", "d" }); + ctx.setAttributeValues("myattr", new String[] { "a", "b", "c" }); + + assertThat(ctx.getModificationItems().length).isEqualTo(0); + } + + /** + * 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 + public void testResetNullAttributeValuesReportedAsModifications() { + BasicAttributes attrs = new BasicAttributes("myattr", null); + UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName()); + + ctx.setAttributeValues("myattr", new String[] { "a" }); + ctx.setAttributeValues("myattr", null); + + assertThat(ctx.getModificationItems().length).isEqualTo(1); + } + + @Test + public void testResetNullAttributeValueNotReportedAsModification() throws Exception { + BasicAttributes attrs = new BasicAttributes("myattr", "b"); + UpdateAdapter ctx = new UpdateAdapter(attrs, LdapUtils.emptyLdapName()); + + ctx.setAttributeValue("myattr", "a"); + ctx.setAttributeValue("myattr", "b"); + + assertThat(ctx.getModificationItems().length).isEqualTo(0); + } + + 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/DistinguishedNameEditorTest.java b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java index e335c9ad..65091173 100644 --- a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameEditorTest.java @@ -1,76 +1,76 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core; - -import org.junit.Before; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - -/** - * Unit tests for {@link DistinguishedNameEditor}. - * - * @author Mattias Hellborg Arthursson - */ -public class DistinguishedNameEditorTest { - - private DistinguishedNameEditor tested; - - @Before - public void setUp() throws Exception { - tested = new DistinguishedNameEditor(); - } - - @Test - public void testSetAsText() throws Exception { - String expectedDn = "dc=jayway, dc=se"; - - tested.setAsText(expectedDn); - DistinguishedName result = (DistinguishedName) tested.getValue(); - assertThat(result).isEqualTo(new DistinguishedName(expectedDn)); - - try { - result.getNames().add(new LdapRdn("cn", "john doe")); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testSetAsTextNullValue() throws Exception { - tested.setAsText(null); - Object result = tested.getValue(); - assertThat(result).isNull(); - } - - @Test - public void testGetAsText() throws Exception { - String expectedDn = "dc=jayway,dc=se"; - tested.setValue(new DistinguishedName(expectedDn)); - String text = tested.getAsText(); - assertThat(text).isEqualTo(expectedDn); - } - - @Test - public void testGetAsTextNullValue() throws Exception { - tested.setValue(null); - String text = tested.getAsText(); - assertThat(text).isNull(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core; + +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +/** + * Unit tests for {@link DistinguishedNameEditor}. + * + * @author Mattias Hellborg Arthursson + */ +public class DistinguishedNameEditorTest { + + private DistinguishedNameEditor tested; + + @Before + public void setUp() throws Exception { + tested = new DistinguishedNameEditor(); + } + + @Test + public void testSetAsText() throws Exception { + String expectedDn = "dc=jayway, dc=se"; + + tested.setAsText(expectedDn); + DistinguishedName result = (DistinguishedName) tested.getValue(); + assertThat(result).isEqualTo(new DistinguishedName(expectedDn)); + + try { + result.getNames().add(new LdapRdn("cn", "john doe")); + fail("UnsupportedOperationException expected"); + } + catch (UnsupportedOperationException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testSetAsTextNullValue() throws Exception { + tested.setAsText(null); + Object result = tested.getValue(); + assertThat(result).isNull(); + } + + @Test + public void testGetAsText() throws Exception { + String expectedDn = "dc=jayway,dc=se"; + tested.setValue(new DistinguishedName(expectedDn)); + String text = tested.getAsText(); + assertThat(text).isEqualTo(expectedDn); + } + + @Test + public void testGetAsTextNullValue() throws Exception { + tested.setValue(null); + 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 c4c229d7..39b758dc 100644 --- a/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java +++ b/core/src/test/java/org/springframework/ldap/core/DistinguishedNameTest.java @@ -1,710 +1,710 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; -import org.springframework.ldap.BadLdapGrammarException; - -import javax.naming.CompositeName; -import javax.naming.InvalidNameException; -import javax.naming.Name; -import java.util.Enumeration; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - -/** - * Unit tests for the {@link DistinguishedName} class. - * - * @author Adam Skogman - * @author Mattias Hellborg Arthursson - */ -public class DistinguishedNameTest { - - @Test - public void testDistinguishedName_CompositeWithSlash() throws Exception { - Name testPath = new CompositeName("cn=foo\\/bar"); - DistinguishedName path = new DistinguishedName(testPath); - assertThat(path.toString()).isEqualTo("cn=foo/bar"); - } - - @Test - public void testDistinguishedName_CompositeWithSlashAsString() throws Exception { - Name testPath = new CompositeName("cn=foo\\/bar"); - DistinguishedName path = new DistinguishedName(testPath.toString()); - assertThat(path.toString()).isEqualTo("cn=foo/bar"); - } - - @Test - public void testDistinguishedName_Ldap237_NotDestroyedByCompositeName() throws InvalidNameException { - DistinguishedName path = new DistinguishedName("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com"); - assertThat(path.toString()).isEqualTo("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com"); - } - - /** - * CompositeName screws up distinguished names when there are double qoutes, as described in Ldap237. - * - * @throws InvalidNameException - */ - @Test - public void testDistinguishedName_Ldap237_DestroyedByCompositeName() throws InvalidNameException { - DistinguishedName path = new DistinguishedName("ou=Roger \\\\\"Bunny\\\\\" Rabbit,dc=somecompany,dc=com"); - assertThat(path.toString()).isEqualTo("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com"); - } - - @Test - public void testEmptyPathImmutable() throws Exception { - DistinguishedName emptyPath = DistinguishedName.EMPTY_PATH; - try { - emptyPath.add("cn=John Doe"); - fail("UnsupportedOperationException expected"); - } - catch (UnsupportedOperationException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testDistinguishedName() { - - String testPath = "cn=foo\\,bar,OU=FOO\\,bar , OU=foo\\;bar;OU=foo\\;bar" - + " ; ou=foo\\,,ou=foo\\,;ou=foo\\;;ou=foo\\,;ou=bar\\,"; - System.out.println(testPath); - - DistinguishedName path = new DistinguishedName(testPath); - - assertThat(path.getLdapRdn(8).getComponent().getKey()).isEqualTo("cn"); - assertThat(path.getLdapRdn(8).getComponent().getValue()).isEqualTo("foo,bar"); - assertThat(path.getLdapRdn(7).getComponent().getKey()).isEqualTo("ou"); - assertThat(path.getLdapRdn(7).getComponent().getValue()).isEqualTo("FOO,bar"); - assertThat(path.getLdapRdn(6).getComponent().getKey()).isEqualTo("ou"); - assertThat(path.getLdapRdn(6).getComponent().getValue()).isEqualTo("foo;bar"); - assertThat(path.getLdapRdn(5).getComponent().getKey()).isEqualTo("ou"); - assertThat(path.getLdapRdn(5).getComponent().getValue()).isEqualTo("foo;bar"); - assertThat(path.getLdapRdn(4).getComponent().getKey()).isEqualTo("ou"); - assertThat(path.getLdapRdn(4).getComponent().getValue()).isEqualTo("foo,"); - assertThat(path.getLdapRdn(3).getComponent().getKey()).isEqualTo("ou"); - assertThat(path.getLdapRdn(3).getComponent().getValue()).isEqualTo("foo,"); - assertThat(path.getLdapRdn(2).getComponent().getKey()).isEqualTo("ou"); - assertThat(path.getLdapRdn(2).getComponent().getValue()).isEqualTo("foo;"); - assertThat(path.getLdapRdn(1).getComponent().getKey()).isEqualTo("ou"); - assertThat(path.getLdapRdn(1).getComponent().getValue()).isEqualTo("foo,"); - assertThat(path.getLdapRdn(0).getComponent().getKey()).isEqualTo("ou"); - assertThat(path.getLdapRdn(0).getComponent().getValue()).isEqualTo("bar,"); - } - - @Test - public void testRemove() throws InvalidNameException { - - String testPath = "cn=john.doe, OU=Users,OU=Some Company,OU=G,OU=I,OU=M"; - DistinguishedName path = new DistinguishedName(testPath); - - path.remove(1); - path.remove(3); - - assertThat(path.toString()).isEqualTo("cn=john.doe,ou=Some Company,ou=G,ou=M"); - } - - /** - * Tests parsing and toString. - */ - @Test - public void testContains() { - - DistinguishedName migpath = new DistinguishedName("OU=G,OU=I,OU=M"); - DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,OU=G,OU=I,OU=M"); - DistinguishedName path2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=i,OU=M, ou=foo"); - DistinguishedName path3 = new DistinguishedName("ou=G,OU=i,OU=M, ou=foo"); - DistinguishedName path4 = new DistinguishedName("ou=G,OU=i,ou=m"); - - DistinguishedName pathE1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=L,OU=M, ou=foo"); - DistinguishedName pathE2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE"); - - assertThat(path1.contains(migpath)).isTrue(); - assertThat(path2.contains(migpath)).isTrue(); - assertThat(path3.contains(migpath)).isTrue(); - assertThat(path4.contains(migpath)).isTrue(); - - assertThat(pathE1.contains(migpath)).isFalse(); - assertThat(pathE2.contains(migpath)).isFalse(); - } - - @Test - public void testAppend() { - DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); - DistinguishedName path2 = new DistinguishedName("OU=baz"); - - path1.append(path2); - - assertThat(path1.toString()).isEqualTo("ou=baz,ou=foo,ou=bar"); - } - - @Test - public void testPrepend() { - DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); - DistinguishedName path2 = new DistinguishedName("cn=fie, OU=baz"); - - path1.prepend(path2); - - assertThat(path1.toString()).isEqualTo("ou=foo,ou=bar,cn=fie,ou=baz"); - } - - @Test - public void testEquals() throws Exception { - - // original object - final Object originalObject = new DistinguishedName("cn=john.doe, OU=Users,OU=Some company,C=SE"); - - // another object that has the same values as the original (case is - // ignored) - final Object identicalObject = new DistinguishedName("cn=john.doe, OU=Users,OU=SOME COMPANY,C=SE"); - - // another object with different values - final Object differentObject = new DistinguishedName("cn=john.doe, OU=Users,OU=Some other company,C=SE"); - - // 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); - } - - @Test - public void testClone() { - - DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=Some company,C=SE"); - - DistinguishedName path2 = (DistinguishedName) path1.clone(); - - assertThat(path2).as("Should be equal").isEqualTo(path1); - - path2.removeFirst(); - assertThat(path1.equals(path2)).isFalse(); - - } - - @Test - public void testEndsWith_true() { - DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - DistinguishedName ending1 = new DistinguishedName("uid=mtah.test"); - - DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - DistinguishedName ending2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU"); - - assertThat(path1.endsWith(ending1)).isTrue(); - assertThat(path2.endsWith(ending2)).isTrue(); - } - - @Test - public void testEndsWith_false() { - DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - DistinguishedName ending1 = new DistinguishedName("ou=people"); - - DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - DistinguishedName ending2 = new DistinguishedName("ou=EU, o=example.com"); - - assertThat(path1.endsWith(ending1)).isFalse(); - assertThat(path2.endsWith(ending2)).isFalse(); - } - - @Test - public void testGetAll() throws Exception { - DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - - Enumeration elements = path.getAll(); - - String element = (String) elements.nextElement(); - assertThat(element).isEqualTo("o=example.com"); - - element = (String) elements.nextElement(); - assertThat(element).isEqualTo("ou=EU"); - - element = (String) elements.nextElement(); - assertThat(element).isEqualTo("ou=people"); - - element = (String) elements.nextElement(); - assertThat(element).isEqualTo("uid=mtah.test"); - } - - @Test - public void testGet() throws Exception { - DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - - String string = path.get(1); - - assertThat(string).isEqualTo("ou=EU"); - } - - @Test - public void testSize() { - DistinguishedName path1 = new DistinguishedName(); - assertThat(path1.size()).isEqualTo(0); - - DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - assertThat(path2.size()).isEqualTo(4); - } - - @Test - public void testGetPrefix() { - DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - - Name prefix = path.getPrefix(0); - assertThat(prefix.size()).isEqualTo(0); - - prefix = path.getPrefix(1); - assertThat(prefix.size()).isEqualTo(1); - assertThat(prefix.get(0)).isEqualTo("o=example.com"); - - prefix = path.getPrefix(2); - assertThat(prefix.size()).isEqualTo(2); - assertThat(prefix.get(0)).isEqualTo("o=example.com"); - assertThat(prefix.get(1)).isEqualTo("ou=EU"); - } - - @Test - public void testGetSuffix() { - DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - - Name suffix = path.getSuffix(0); - assertThat(suffix.size()).isEqualTo(4); - - suffix = path.getSuffix(2); - assertThat(suffix.size()).isEqualTo(2); - assertThat(suffix.get(0)).isEqualTo("ou=people"); - - suffix = path.getSuffix(4); - assertThat(suffix.size()).isEqualTo(0); - - try { - path.getSuffix(5); - fail("ArrayIndexOutOfBoundsException expected"); - } - catch (ArrayIndexOutOfBoundsException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testStartsWith_true() { - DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - DistinguishedName start1 = new DistinguishedName("o=example.com"); - - DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - DistinguishedName start2 = new DistinguishedName("ou=people, ou=EU, o=example.com"); - - assertThat(path1.startsWith(start1)).isTrue(); - assertThat(path2.startsWith(start2)).isTrue(); - } - - @Test - public void testStartsWith_false() { - DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - DistinguishedName start1 = new DistinguishedName("ou=people"); - - DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - DistinguishedName start2 = new DistinguishedName("uid=mtah.test, ou=EU, ou=people"); - - assertThat(path1.startsWith(start1)).isFalse(); - assertThat(path2.startsWith(start2)).isFalse(); - } - - @Test - public void testStartsWith_Longer() { - DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - - DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com, o=a.com"); - - assertThat(path1.startsWith(path2)).isFalse(); - } - - @Test - public void testStartsWith_EmptyPath() { - DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); - - DistinguishedName path2 = new DistinguishedName(); - - assertThat(path1.startsWith(path2)).isFalse(); - } - - @Test - public void testIsEmpty_True() { - DistinguishedName path = new DistinguishedName(); - assertThat(path.isEmpty()).isTrue(); - } - - @Test - public void testIsEmpty_False() { - DistinguishedName path = new DistinguishedName("o=example.com"); - assertThat(path.isEmpty()).isFalse(); - } - - @Test - public void testAddAll() throws Exception { - DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); - DistinguishedName path2 = new DistinguishedName("OU=baz"); - - path1.addAll(path2); - - assertThat(path1.toString()).isEqualTo("ou=baz,ou=foo,ou=bar"); - } - - @Test - public void testAddAll_Index() throws InvalidNameException { - DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); - DistinguishedName path2 = new DistinguishedName("OU=baz"); - - path1.addAll(1, path2); - - assertThat(path1.toString()).isEqualTo("ou=foo,ou=baz,ou=bar"); - } - - @Test - public void testAdd() throws InvalidNameException { - DistinguishedName path1 = new DistinguishedName("ou=foo, ou=bar"); - path1.add("ou=baz"); - - assertThat(path1.toString()).isEqualTo("ou=baz,ou=foo,ou=bar"); - } - - @Test - public void testAdd_Index() throws InvalidNameException { - DistinguishedName path1 = new DistinguishedName("ou=foo, ou=bar"); - path1.add(1, "ou=baz"); - - assertThat(path1.toString()).isEqualTo("ou=foo,ou=baz,ou=bar"); - } - - @Test - public void testToUrl() { - DistinguishedName path = new DistinguishedName("dc=jayway, dc=se"); - String url = path.toUrl(); - - assertThat(url).isEqualTo("dc=jayway,dc=se"); - } - - @Test - public void testMultiValueRdn() throws Exception { - DistinguishedName path = new DistinguishedName("firstName=Rod+lastName=Johnson,ou=UK,dc=interface21,dc=com"); - assertThat(path.size()).isEqualTo(4); - assertThat(path.get(3)).isEqualTo("firstname=Rod+lastname=Johnson"); - } - - @Test - public void testCompareTo_Equals() throws Exception { - DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - - int result = name1.compareTo(name2); - assertThat(result).isEqualTo(0); - } - - @Test - public void testCompareTo_Less() throws Exception { - DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=DK"); - DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - - int result = name1.compareTo(name2); - assertThat(result < 0).isTrue(); - } - - @Test - public void testCompareTo_Less_MoreSignificant() throws Exception { - DistinguishedName name1 = new DistinguishedName("an=john doe, ou=Some company, c=DK"); - DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - - int result = name1.compareTo(name2); - assertThat(result < 0).isTrue(); - } - - @Test - public void testCompareTo_Greater() throws Exception { - DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=DK"); - - int result = name1.compareTo(name2); - assertThat(result > 0).isTrue(); - } - - @Test - public void testCompareTo_Longer() throws Exception { - DistinguishedName name1 = new DistinguishedName("leaf=someleaf, cn=john doe, ou=Some company, c=SE"); - DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - - int result = name1.compareTo(name2); - assertThat(result > 0).isTrue(); - } - - @Test - public void testCompareTo_Shorter() throws Exception { - DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - DistinguishedName name2 = new DistinguishedName("leaf=someleaf, cn=john doe, ou=Some company, c=SE"); - - int result = name1.compareTo(name2); - assertThat(result < 0).isTrue(); - } - - @Test - public void testGetLdapRdnForKey() throws Exception { - DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - LdapRdn ldapRdn = dn.getLdapRdn("ou"); - assertThat(ldapRdn).isEqualTo(new LdapRdn("ou=Some company")); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetLdapRdnForKeyNoMatchingKeyThrowsException() throws Exception { - DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - dn.getLdapRdn("nosuchkey"); - } - - @Test - public void testGetValue() throws Exception { - DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - String value = dn.getValue("ou"); - assertThat(value).isEqualTo("Some company"); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetValueNoMatchingKeyThrowsException() throws Exception { - DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); - dn.getValue("nosuchkey"); - } - - @Test - public void test_longDN() throws InvalidNameException { - DistinguishedName name = new DistinguishedName(""); - assertThat(name).isNotNull(); - } - - /** - * Test case to verify correct parsing for issue on forums. - */ - @Test - public void testParseAtSign() { - DistinguishedName name = new DistinguishedName("cn=testname@example.com"); - assertThat(name).isNotNull(); - } - - /** - * Test case to verify correct parsing for issue on forums. - */ - @Test - public void testParseAtSign2() { - DistinguishedName name = new DistinguishedName("cn=te\\+stname@example.com"); - assertThat(name).isNotNull(); - } - - /** - * Test case to verify correct parsing for issue on forums. - */ - @Test(expected = BadLdapGrammarException.class) - public void testParseInvalidPlus() { - new DistinguishedName("cn=te+stname@example.com"); - } - - /** - * Test case to verify correct parsing for issue on forums. - */ - @Test - public void testParseValidQuotation() { - DistinguishedName name = new DistinguishedName("cn=jo\"hn doe"); - assertThat(name).isNotNull(); - } - - @Test - public void testAppendChained() { - DistinguishedName tested = new DistinguishedName("dc=mycompany,dc=com"); - tested.append("ou", "company1").append("cn", "john doe"); - - assertThat(tested.toString()).isEqualTo("cn=john doe,ou=company1,dc=mycompany,dc=com"); - } - - @Test(expected = UnsupportedOperationException.class) - public void testUnmodifiableDistinguishedNameFailsToAddRdn() throws Exception { - DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); - result.add(new LdapRdn("somekey", "somevalue")); - } - - @Test(expected = UnsupportedOperationException.class) - public void testUnmodifiableDistinguishedNameFailsToModifyRdn() throws Exception { - DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); - LdapRdn ldapRdn = result.getLdapRdn(0); - - ldapRdn.addComponent(new LdapRdnComponent("somekey", "somevalue")); - } - - @Test(expected = UnsupportedOperationException.class) - public void testUnmodifiableDistinguishedNameFailsToModifyRdnComponentKey() throws Exception { - DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); - LdapRdnComponent component = result.getLdapRdn(0).getComponent(); - - component.setKey("somekey"); - } - - @Test(expected = UnsupportedOperationException.class) - public void testUnmodifiableDistinguishedNameFailsToModifyRdnComponentValue() throws Exception { - DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); - LdapRdnComponent component = result.getLdapRdn(0).getComponent(); - - component.setValue("somevalue"); - } - - @Test - public void testUnmodifiableDistinguishedNameEqualsIdenticalMutableOne() throws Exception { - DistinguishedName immutable = DistinguishedName.immutableDistinguishedName("cn=john doe"); - DistinguishedName mutable = new DistinguishedName("cn=john doe"); - assertThat(immutable.equals(mutable)).isTrue(); - } - - /** - * Test for LDAP-97. - */ - @Test - public void testDistinguishedNameWithCRParsesProperly() { - DistinguishedName name = new DistinguishedName("cn=foo \r bar"); - assertThat(name).isNotNull(); - } - - /** - * Test for https://forum.spring.io/showthread.php?t=86640. - */ - @Test - public void testDistinguishedNameWithDotParsesProperly() { - DistinguishedName name = new DistinguishedName("cn=first.last,OU=DevTest Users,DC=xyz,DC=com"); - assertThat(name.toCompactString()).isEqualTo("cn=first.last,ou=DevTest Users,dc=xyz,dc=com"); - DistinguishedName dn = new DistinguishedName(); - dn.parse("cn=first.last,OU=DevTest Users,DC=xyz,DC=com"); - assertThat(dn.getValue("cn")).isEqualTo("first.last"); - assertThat(dn.getValue("ou")).isEqualTo("DevTest Users"); - assertThat(dn.getLdapRdn(1).getValue()).isEqualTo("xyz"); - assertThat(dn.getLdapRdn(0).getValue()).isEqualTo("com"); - } - - @Test - public void testToStringCompact() { - try { - DistinguishedName name = new DistinguishedName("cn=john doe, ou=company"); - // First check the default - assertThat(name.toString()).isEqualTo("cn=john doe,ou=company"); - System.setProperty(DistinguishedName.SPACED_DN_FORMAT_PROPERTY, "true"); - assertThat(name.toString()).isEqualTo("cn=john doe, ou=company"); - } - finally { - // Always restore the system setting - System.setProperty(DistinguishedName.SPACED_DN_FORMAT_PROPERTY, ""); - } - } - - @Test - public void testKeyCaseFoldNoneShouldEqualOriginalCasedKeys() throws Exception { - 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"); - - System.setProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY, DistinguishedName.KEY_CASE_FOLD_NONE); - name = new DistinguishedName(dnString); - System.out.println(dnString + " folded as \"" + DistinguishedName.KEY_CASE_FOLD_NONE + "\": " + name); - assertThat(name.toString()).isEqualTo(dnString); - } - finally { - // Always restore the system setting - System.clearProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); - } - } - - @Test - public void testKeyCaseFoldUpperShouldEqualUpperCasedKeys() throws Exception { - 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"); - - 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); - assertThat(name.toString()).isEqualTo("OU=foo,OU=bar,OU=baz,OU=bim"); - } - finally { - // Always restore the system setting - System.clearProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); - } - } - - @Test - public void testKeyCaseFoldLowerShouldEqualLowerCasedKeys() throws Exception { - 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"); - - 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); - assertThat(name.toString()).isEqualTo("ou=foo,ou=bar,ou=baz,ou=bim"); - } - finally { - // Always restore the system setting - System.clearProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); - } - } - - @Test - public void testKeyCaseFoldNonsenseShoulddefaultToLowerCasedKeysAndLogWarning() throws Exception { - 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"); - - System.setProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY, "whatever"); - name = new DistinguishedName(dnString); - System.out.println(dnString + " folded as \"whatever\": " + name); - assertThat(name.toString()).isEqualTo("ou=foo,ou=bar,ou=baz,ou=bim"); - } - finally { - // Always restore the system setting - System.clearProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); - } - } - - @Test - public void testHashSignLdap229() { - 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")); - } - - @Test - public void testSpaceSignLdap229() { - assertThat(new DistinguishedName("cn=Foo\\ Bar")).isEqualTo( - new DistinguishedName("cn=Foo Bar")); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; +import org.springframework.ldap.BadLdapGrammarException; + +import javax.naming.CompositeName; +import javax.naming.InvalidNameException; +import javax.naming.Name; +import java.util.Enumeration; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +/** + * Unit tests for the {@link DistinguishedName} class. + * + * @author Adam Skogman + * @author Mattias Hellborg Arthursson + */ +public class DistinguishedNameTest { + + @Test + public void testDistinguishedName_CompositeWithSlash() throws Exception { + Name testPath = new CompositeName("cn=foo\\/bar"); + DistinguishedName path = new DistinguishedName(testPath); + assertThat(path.toString()).isEqualTo("cn=foo/bar"); + } + + @Test + public void testDistinguishedName_CompositeWithSlashAsString() throws Exception { + Name testPath = new CompositeName("cn=foo\\/bar"); + DistinguishedName path = new DistinguishedName(testPath.toString()); + assertThat(path.toString()).isEqualTo("cn=foo/bar"); + } + + @Test + public void testDistinguishedName_Ldap237_NotDestroyedByCompositeName() throws InvalidNameException { + DistinguishedName path = new DistinguishedName("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com"); + assertThat(path.toString()).isEqualTo("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com"); + } + + /** + * CompositeName screws up distinguished names when there are double qoutes, as described in Ldap237. + * + * @throws InvalidNameException + */ + @Test + public void testDistinguishedName_Ldap237_DestroyedByCompositeName() throws InvalidNameException { + DistinguishedName path = new DistinguishedName("ou=Roger \\\\\"Bunny\\\\\" Rabbit,dc=somecompany,dc=com"); + assertThat(path.toString()).isEqualTo("ou=Roger \\\"Bunny\\\" Rabbit,dc=somecompany,dc=com"); + } + + @Test + public void testEmptyPathImmutable() throws Exception { + DistinguishedName emptyPath = DistinguishedName.EMPTY_PATH; + try { + emptyPath.add("cn=John Doe"); + fail("UnsupportedOperationException expected"); + } + catch (UnsupportedOperationException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testDistinguishedName() { + + String testPath = "cn=foo\\,bar,OU=FOO\\,bar , OU=foo\\;bar;OU=foo\\;bar" + + " ; ou=foo\\,,ou=foo\\,;ou=foo\\;;ou=foo\\,;ou=bar\\,"; + System.out.println(testPath); + + DistinguishedName path = new DistinguishedName(testPath); + + assertThat(path.getLdapRdn(8).getComponent().getKey()).isEqualTo("cn"); + assertThat(path.getLdapRdn(8).getComponent().getValue()).isEqualTo("foo,bar"); + assertThat(path.getLdapRdn(7).getComponent().getKey()).isEqualTo("ou"); + assertThat(path.getLdapRdn(7).getComponent().getValue()).isEqualTo("FOO,bar"); + assertThat(path.getLdapRdn(6).getComponent().getKey()).isEqualTo("ou"); + assertThat(path.getLdapRdn(6).getComponent().getValue()).isEqualTo("foo;bar"); + assertThat(path.getLdapRdn(5).getComponent().getKey()).isEqualTo("ou"); + assertThat(path.getLdapRdn(5).getComponent().getValue()).isEqualTo("foo;bar"); + assertThat(path.getLdapRdn(4).getComponent().getKey()).isEqualTo("ou"); + assertThat(path.getLdapRdn(4).getComponent().getValue()).isEqualTo("foo,"); + assertThat(path.getLdapRdn(3).getComponent().getKey()).isEqualTo("ou"); + assertThat(path.getLdapRdn(3).getComponent().getValue()).isEqualTo("foo,"); + assertThat(path.getLdapRdn(2).getComponent().getKey()).isEqualTo("ou"); + assertThat(path.getLdapRdn(2).getComponent().getValue()).isEqualTo("foo;"); + assertThat(path.getLdapRdn(1).getComponent().getKey()).isEqualTo("ou"); + assertThat(path.getLdapRdn(1).getComponent().getValue()).isEqualTo("foo,"); + assertThat(path.getLdapRdn(0).getComponent().getKey()).isEqualTo("ou"); + assertThat(path.getLdapRdn(0).getComponent().getValue()).isEqualTo("bar,"); + } + + @Test + public void testRemove() throws InvalidNameException { + + String testPath = "cn=john.doe, OU=Users,OU=Some Company,OU=G,OU=I,OU=M"; + DistinguishedName path = new DistinguishedName(testPath); + + path.remove(1); + path.remove(3); + + assertThat(path.toString()).isEqualTo("cn=john.doe,ou=Some Company,ou=G,ou=M"); + } + + /** + * Tests parsing and toString. + */ + @Test + public void testContains() { + + DistinguishedName migpath = new DistinguishedName("OU=G,OU=I,OU=M"); + DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,OU=G,OU=I,OU=M"); + DistinguishedName path2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=i,OU=M, ou=foo"); + DistinguishedName path3 = new DistinguishedName("ou=G,OU=i,OU=M, ou=foo"); + DistinguishedName path4 = new DistinguishedName("ou=G,OU=i,ou=m"); + + DistinguishedName pathE1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=L,OU=M, ou=foo"); + DistinguishedName pathE2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE"); + + assertThat(path1.contains(migpath)).isTrue(); + assertThat(path2.contains(migpath)).isTrue(); + assertThat(path3.contains(migpath)).isTrue(); + assertThat(path4.contains(migpath)).isTrue(); + + assertThat(pathE1.contains(migpath)).isFalse(); + assertThat(pathE2.contains(migpath)).isFalse(); + } + + @Test + public void testAppend() { + DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); + DistinguishedName path2 = new DistinguishedName("OU=baz"); + + path1.append(path2); + + assertThat(path1.toString()).isEqualTo("ou=baz,ou=foo,ou=bar"); + } + + @Test + public void testPrepend() { + DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); + DistinguishedName path2 = new DistinguishedName("cn=fie, OU=baz"); + + path1.prepend(path2); + + assertThat(path1.toString()).isEqualTo("ou=foo,ou=bar,cn=fie,ou=baz"); + } + + @Test + public void testEquals() throws Exception { + + // original object + final Object originalObject = new DistinguishedName("cn=john.doe, OU=Users,OU=Some company,C=SE"); + + // another object that has the same values as the original (case is + // ignored) + final Object identicalObject = new DistinguishedName("cn=john.doe, OU=Users,OU=SOME COMPANY,C=SE"); + + // another object with different values + final Object differentObject = new DistinguishedName("cn=john.doe, OU=Users,OU=Some other company,C=SE"); + + // 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); + } + + @Test + public void testClone() { + + DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=Some company,C=SE"); + + DistinguishedName path2 = (DistinguishedName) path1.clone(); + + assertThat(path2).as("Should be equal").isEqualTo(path1); + + path2.removeFirst(); + assertThat(path1.equals(path2)).isFalse(); + + } + + @Test + public void testEndsWith_true() { + DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + DistinguishedName ending1 = new DistinguishedName("uid=mtah.test"); + + DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + DistinguishedName ending2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU"); + + assertThat(path1.endsWith(ending1)).isTrue(); + assertThat(path2.endsWith(ending2)).isTrue(); + } + + @Test + public void testEndsWith_false() { + DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + DistinguishedName ending1 = new DistinguishedName("ou=people"); + + DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + DistinguishedName ending2 = new DistinguishedName("ou=EU, o=example.com"); + + assertThat(path1.endsWith(ending1)).isFalse(); + assertThat(path2.endsWith(ending2)).isFalse(); + } + + @Test + public void testGetAll() throws Exception { + DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + + Enumeration elements = path.getAll(); + + String element = (String) elements.nextElement(); + assertThat(element).isEqualTo("o=example.com"); + + element = (String) elements.nextElement(); + assertThat(element).isEqualTo("ou=EU"); + + element = (String) elements.nextElement(); + assertThat(element).isEqualTo("ou=people"); + + element = (String) elements.nextElement(); + assertThat(element).isEqualTo("uid=mtah.test"); + } + + @Test + public void testGet() throws Exception { + DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + + String string = path.get(1); + + assertThat(string).isEqualTo("ou=EU"); + } + + @Test + public void testSize() { + DistinguishedName path1 = new DistinguishedName(); + assertThat(path1.size()).isEqualTo(0); + + DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + assertThat(path2.size()).isEqualTo(4); + } + + @Test + public void testGetPrefix() { + DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + + Name prefix = path.getPrefix(0); + assertThat(prefix.size()).isEqualTo(0); + + prefix = path.getPrefix(1); + assertThat(prefix.size()).isEqualTo(1); + assertThat(prefix.get(0)).isEqualTo("o=example.com"); + + prefix = path.getPrefix(2); + assertThat(prefix.size()).isEqualTo(2); + assertThat(prefix.get(0)).isEqualTo("o=example.com"); + assertThat(prefix.get(1)).isEqualTo("ou=EU"); + } + + @Test + public void testGetSuffix() { + DistinguishedName path = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + + Name suffix = path.getSuffix(0); + assertThat(suffix.size()).isEqualTo(4); + + suffix = path.getSuffix(2); + assertThat(suffix.size()).isEqualTo(2); + assertThat(suffix.get(0)).isEqualTo("ou=people"); + + suffix = path.getSuffix(4); + assertThat(suffix.size()).isEqualTo(0); + + try { + path.getSuffix(5); + fail("ArrayIndexOutOfBoundsException expected"); + } + catch (ArrayIndexOutOfBoundsException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testStartsWith_true() { + DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + DistinguishedName start1 = new DistinguishedName("o=example.com"); + + DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + DistinguishedName start2 = new DistinguishedName("ou=people, ou=EU, o=example.com"); + + assertThat(path1.startsWith(start1)).isTrue(); + assertThat(path2.startsWith(start2)).isTrue(); + } + + @Test + public void testStartsWith_false() { + DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + DistinguishedName start1 = new DistinguishedName("ou=people"); + + DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + DistinguishedName start2 = new DistinguishedName("uid=mtah.test, ou=EU, ou=people"); + + assertThat(path1.startsWith(start1)).isFalse(); + assertThat(path2.startsWith(start2)).isFalse(); + } + + @Test + public void testStartsWith_Longer() { + DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + + DistinguishedName path2 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com, o=a.com"); + + assertThat(path1.startsWith(path2)).isFalse(); + } + + @Test + public void testStartsWith_EmptyPath() { + DistinguishedName path1 = new DistinguishedName("uid=mtah.test, ou=people, ou=EU, o=example.com"); + + DistinguishedName path2 = new DistinguishedName(); + + assertThat(path1.startsWith(path2)).isFalse(); + } + + @Test + public void testIsEmpty_True() { + DistinguishedName path = new DistinguishedName(); + assertThat(path.isEmpty()).isTrue(); + } + + @Test + public void testIsEmpty_False() { + DistinguishedName path = new DistinguishedName("o=example.com"); + assertThat(path.isEmpty()).isFalse(); + } + + @Test + public void testAddAll() throws Exception { + DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); + DistinguishedName path2 = new DistinguishedName("OU=baz"); + + path1.addAll(path2); + + assertThat(path1.toString()).isEqualTo("ou=baz,ou=foo,ou=bar"); + } + + @Test + public void testAddAll_Index() throws InvalidNameException { + DistinguishedName path1 = new DistinguishedName("ou=foo, OU=bar"); + DistinguishedName path2 = new DistinguishedName("OU=baz"); + + path1.addAll(1, path2); + + assertThat(path1.toString()).isEqualTo("ou=foo,ou=baz,ou=bar"); + } + + @Test + public void testAdd() throws InvalidNameException { + DistinguishedName path1 = new DistinguishedName("ou=foo, ou=bar"); + path1.add("ou=baz"); + + assertThat(path1.toString()).isEqualTo("ou=baz,ou=foo,ou=bar"); + } + + @Test + public void testAdd_Index() throws InvalidNameException { + DistinguishedName path1 = new DistinguishedName("ou=foo, ou=bar"); + path1.add(1, "ou=baz"); + + assertThat(path1.toString()).isEqualTo("ou=foo,ou=baz,ou=bar"); + } + + @Test + public void testToUrl() { + DistinguishedName path = new DistinguishedName("dc=jayway, dc=se"); + String url = path.toUrl(); + + assertThat(url).isEqualTo("dc=jayway,dc=se"); + } + + @Test + public void testMultiValueRdn() throws Exception { + DistinguishedName path = new DistinguishedName("firstName=Rod+lastName=Johnson,ou=UK,dc=interface21,dc=com"); + assertThat(path.size()).isEqualTo(4); + assertThat(path.get(3)).isEqualTo("firstname=Rod+lastname=Johnson"); + } + + @Test + public void testCompareTo_Equals() throws Exception { + DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + + int result = name1.compareTo(name2); + assertThat(result).isEqualTo(0); + } + + @Test + public void testCompareTo_Less() throws Exception { + DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=DK"); + DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + + int result = name1.compareTo(name2); + assertThat(result < 0).isTrue(); + } + + @Test + public void testCompareTo_Less_MoreSignificant() throws Exception { + DistinguishedName name1 = new DistinguishedName("an=john doe, ou=Some company, c=DK"); + DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + + int result = name1.compareTo(name2); + assertThat(result < 0).isTrue(); + } + + @Test + public void testCompareTo_Greater() throws Exception { + DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=DK"); + + int result = name1.compareTo(name2); + assertThat(result > 0).isTrue(); + } + + @Test + public void testCompareTo_Longer() throws Exception { + DistinguishedName name1 = new DistinguishedName("leaf=someleaf, cn=john doe, ou=Some company, c=SE"); + DistinguishedName name2 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + + int result = name1.compareTo(name2); + assertThat(result > 0).isTrue(); + } + + @Test + public void testCompareTo_Shorter() throws Exception { + DistinguishedName name1 = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + DistinguishedName name2 = new DistinguishedName("leaf=someleaf, cn=john doe, ou=Some company, c=SE"); + + int result = name1.compareTo(name2); + assertThat(result < 0).isTrue(); + } + + @Test + public void testGetLdapRdnForKey() throws Exception { + DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + LdapRdn ldapRdn = dn.getLdapRdn("ou"); + assertThat(ldapRdn).isEqualTo(new LdapRdn("ou=Some company")); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetLdapRdnForKeyNoMatchingKeyThrowsException() throws Exception { + DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + dn.getLdapRdn("nosuchkey"); + } + + @Test + public void testGetValue() throws Exception { + DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + String value = dn.getValue("ou"); + assertThat(value).isEqualTo("Some company"); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetValueNoMatchingKeyThrowsException() throws Exception { + DistinguishedName dn = new DistinguishedName("cn=john doe, ou=Some company, c=SE"); + dn.getValue("nosuchkey"); + } + + @Test + public void test_longDN() throws InvalidNameException { + DistinguishedName name = new DistinguishedName(""); + assertThat(name).isNotNull(); + } + + /** + * Test case to verify correct parsing for issue on forums. + */ + @Test + public void testParseAtSign() { + DistinguishedName name = new DistinguishedName("cn=testname@example.com"); + assertThat(name).isNotNull(); + } + + /** + * Test case to verify correct parsing for issue on forums. + */ + @Test + public void testParseAtSign2() { + DistinguishedName name = new DistinguishedName("cn=te\\+stname@example.com"); + assertThat(name).isNotNull(); + } + + /** + * Test case to verify correct parsing for issue on forums. + */ + @Test(expected = BadLdapGrammarException.class) + public void testParseInvalidPlus() { + new DistinguishedName("cn=te+stname@example.com"); + } + + /** + * Test case to verify correct parsing for issue on forums. + */ + @Test + public void testParseValidQuotation() { + DistinguishedName name = new DistinguishedName("cn=jo\"hn doe"); + assertThat(name).isNotNull(); + } + + @Test + public void testAppendChained() { + DistinguishedName tested = new DistinguishedName("dc=mycompany,dc=com"); + tested.append("ou", "company1").append("cn", "john doe"); + + assertThat(tested.toString()).isEqualTo("cn=john doe,ou=company1,dc=mycompany,dc=com"); + } + + @Test(expected = UnsupportedOperationException.class) + public void testUnmodifiableDistinguishedNameFailsToAddRdn() throws Exception { + DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); + result.add(new LdapRdn("somekey", "somevalue")); + } + + @Test(expected = UnsupportedOperationException.class) + public void testUnmodifiableDistinguishedNameFailsToModifyRdn() throws Exception { + DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); + LdapRdn ldapRdn = result.getLdapRdn(0); + + ldapRdn.addComponent(new LdapRdnComponent("somekey", "somevalue")); + } + + @Test(expected = UnsupportedOperationException.class) + public void testUnmodifiableDistinguishedNameFailsToModifyRdnComponentKey() throws Exception { + DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); + LdapRdnComponent component = result.getLdapRdn(0).getComponent(); + + component.setKey("somekey"); + } + + @Test(expected = UnsupportedOperationException.class) + public void testUnmodifiableDistinguishedNameFailsToModifyRdnComponentValue() throws Exception { + DistinguishedName result = DistinguishedName.immutableDistinguishedName("cn=john doe"); + LdapRdnComponent component = result.getLdapRdn(0).getComponent(); + + component.setValue("somevalue"); + } + + @Test + public void testUnmodifiableDistinguishedNameEqualsIdenticalMutableOne() throws Exception { + DistinguishedName immutable = DistinguishedName.immutableDistinguishedName("cn=john doe"); + DistinguishedName mutable = new DistinguishedName("cn=john doe"); + assertThat(immutable.equals(mutable)).isTrue(); + } + + /** + * Test for LDAP-97. + */ + @Test + public void testDistinguishedNameWithCRParsesProperly() { + DistinguishedName name = new DistinguishedName("cn=foo \r bar"); + assertThat(name).isNotNull(); + } + + /** + * Test for https://forum.spring.io/showthread.php?t=86640. + */ + @Test + public void testDistinguishedNameWithDotParsesProperly() { + DistinguishedName name = new DistinguishedName("cn=first.last,OU=DevTest Users,DC=xyz,DC=com"); + assertThat(name.toCompactString()).isEqualTo("cn=first.last,ou=DevTest Users,dc=xyz,dc=com"); + DistinguishedName dn = new DistinguishedName(); + dn.parse("cn=first.last,OU=DevTest Users,DC=xyz,DC=com"); + assertThat(dn.getValue("cn")).isEqualTo("first.last"); + assertThat(dn.getValue("ou")).isEqualTo("DevTest Users"); + assertThat(dn.getLdapRdn(1).getValue()).isEqualTo("xyz"); + assertThat(dn.getLdapRdn(0).getValue()).isEqualTo("com"); + } + + @Test + public void testToStringCompact() { + try { + DistinguishedName name = new DistinguishedName("cn=john doe, ou=company"); + // First check the default + assertThat(name.toString()).isEqualTo("cn=john doe,ou=company"); + System.setProperty(DistinguishedName.SPACED_DN_FORMAT_PROPERTY, "true"); + assertThat(name.toString()).isEqualTo("cn=john doe, ou=company"); + } + finally { + // Always restore the system setting + System.setProperty(DistinguishedName.SPACED_DN_FORMAT_PROPERTY, ""); + } + } + + @Test + public void testKeyCaseFoldNoneShouldEqualOriginalCasedKeys() throws Exception { + 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"); + + System.setProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY, DistinguishedName.KEY_CASE_FOLD_NONE); + name = new DistinguishedName(dnString); + System.out.println(dnString + " folded as \"" + DistinguishedName.KEY_CASE_FOLD_NONE + "\": " + name); + assertThat(name.toString()).isEqualTo(dnString); + } + finally { + // Always restore the system setting + System.clearProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); + } + } + + @Test + public void testKeyCaseFoldUpperShouldEqualUpperCasedKeys() throws Exception { + 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"); + + 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); + assertThat(name.toString()).isEqualTo("OU=foo,OU=bar,OU=baz,OU=bim"); + } + finally { + // Always restore the system setting + System.clearProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); + } + } + + @Test + public void testKeyCaseFoldLowerShouldEqualLowerCasedKeys() throws Exception { + 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"); + + 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); + assertThat(name.toString()).isEqualTo("ou=foo,ou=bar,ou=baz,ou=bim"); + } + finally { + // Always restore the system setting + System.clearProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); + } + } + + @Test + public void testKeyCaseFoldNonsenseShoulddefaultToLowerCasedKeysAndLogWarning() throws Exception { + 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"); + + System.setProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY, "whatever"); + name = new DistinguishedName(dnString); + System.out.println(dnString + " folded as \"whatever\": " + name); + assertThat(name.toString()).isEqualTo("ou=foo,ou=bar,ou=baz,ou=bim"); + } + finally { + // Always restore the system setting + System.clearProperty(DistinguishedName.KEY_CASE_FOLD_PROPERTY); + } + } + + @Test + public void testHashSignLdap229() { + 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")); + } + + @Test + public void testSpaceSignLdap229() { + 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 23cd41ef..1f63db04 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapRdnComponentTest.java @@ -1,70 +1,70 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for LdapRdnComponent. - * - * @author Mattias Hellborg Arthursson - */ -public class LdapRdnComponentTest { - - @Test - public void testCompareTo_Less() { - LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); - LdapRdnComponent component2 = new LdapRdnComponent("sn", "doe"); - int result = component1.compareTo(component2); - assertThat(result < 0).isTrue(); - } - - @Test - public void testCompareTo_Greater() { - LdapRdnComponent component1 = new LdapRdnComponent("sn", "doe"); - LdapRdnComponent component2 = new LdapRdnComponent("cn", "john doe"); - int result = component1.compareTo(component2); - assertThat(result > 0).isTrue(); - } - - @Test - public void testCompareTo_Equal() { - LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); - LdapRdnComponent component2 = new LdapRdnComponent("cn", "john doe"); - int result = component1.compareTo(component2); - assertThat(result).isEqualTo(0); - } - - @Test - public void testCompareTo_DifferentCase_LDAP259() { - LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); - LdapRdnComponent component2 = new LdapRdnComponent("CN", "John Doe"); - - assertThat(component2).as("Should be equal").isEqualTo(component1); - assertThat(component1.compareTo(component2) == 0).as("0 should be returned by compareTo").isTrue(); - } - - @Test - public void verifyThatHashCodeDisregardsCase_LDAP259() { - LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); - LdapRdnComponent component2 = new LdapRdnComponent("CN", "John Doe"); - - assertThat(component2.hashCode()).as("Should be equal").isEqualTo(component1.hashCode()); - } - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for LdapRdnComponent. + * + * @author Mattias Hellborg Arthursson + */ +public class LdapRdnComponentTest { + + @Test + public void testCompareTo_Less() { + LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); + LdapRdnComponent component2 = new LdapRdnComponent("sn", "doe"); + int result = component1.compareTo(component2); + assertThat(result < 0).isTrue(); + } + + @Test + public void testCompareTo_Greater() { + LdapRdnComponent component1 = new LdapRdnComponent("sn", "doe"); + LdapRdnComponent component2 = new LdapRdnComponent("cn", "john doe"); + int result = component1.compareTo(component2); + assertThat(result > 0).isTrue(); + } + + @Test + public void testCompareTo_Equal() { + LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); + LdapRdnComponent component2 = new LdapRdnComponent("cn", "john doe"); + int result = component1.compareTo(component2); + assertThat(result).isEqualTo(0); + } + + @Test + public void testCompareTo_DifferentCase_LDAP259() { + LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); + LdapRdnComponent component2 = new LdapRdnComponent("CN", "John Doe"); + + assertThat(component2).as("Should be equal").isEqualTo(component1); + assertThat(component1.compareTo(component2) == 0).as("0 should be returned by compareTo").isTrue(); + } + + @Test + public void verifyThatHashCodeDisregardsCase_LDAP259() { + LdapRdnComponent component1 = new LdapRdnComponent("cn", "john doe"); + LdapRdnComponent component2 = new LdapRdnComponent("CN", "John Doe"); + + assertThat(component2.hashCode()).as("Should be equal").isEqualTo(component1.hashCode()); + } + +} 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 13706a3c..04cf93fc 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapRdnTest.java @@ -1,259 +1,259 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; -import org.springframework.ldap.BadLdapGrammarException; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit test for the LdapRdn class. - * - * @author Adam Skogman - */ -public class LdapRdnTest { - - @Test - public void testLdapRdn_parse_simple() { - - LdapRdn rdn = new LdapRdn("foo=bar"); - - assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); - assertThat(rdn.getComponent().getValue()).isEqualTo("bar"); - assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar"); - assertThat(rdn.getKey()).isEqualTo("foo"); - assertThat(rdn.getValue()).isEqualTo("bar"); - } - - @Test - public void testLdapRdn_parse_spaces() { - - LdapRdn rdn = new LdapRdn(" foo = bar "); - - assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); - assertThat(rdn.getComponent().getValue()).isEqualTo("bar"); - assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar"); - } - - @Test - public void testLdapRdn_parse_escape() { - - LdapRdn rdn = new LdapRdn("foo=bar\\=fum"); - - assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); - assertThat(rdn.getComponent().getValue()).isEqualTo("bar=fum"); - assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar\\=fum"); - } - - @Test - public void testLdapRdn_parse_hexEscape() { - - LdapRdn rdn = new LdapRdn("foo=bar\\0dfum"); - - assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); - assertThat(rdn.getComponent().getValue()).isEqualTo("bar\rfum"); - assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar\\0Dfum"); - } - - @Test(expected = BadLdapGrammarException.class) - public void testLdapRdn_parse_trailingBackslash() { - new LdapRdn("foo=bar\\"); - } - - @Test - public void testLdapRdn_parse_spaces_escape() { - LdapRdn rdn = new LdapRdn(" foo = \\ bar\\20 \\ "); - - assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); - assertThat(rdn.getComponent().getValue()).isEqualTo(" bar "); - assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=\\ bar \\ "); - } - - @Test(expected = BadLdapGrammarException.class) - public void testLdapRdn_parse_tooMuchTrim() { - new LdapRdn("foo=bar\\"); - } - - @Test - public void testLdapRdn_parse_slash() { - LdapRdn rdn = new LdapRdn("ou=Clerical / Secretarial Staff"); - - assertThat(rdn.getComponent().getKey()).isEqualTo("ou"); - assertThat(rdn.getComponent().getValue()).isEqualTo("Clerical / Secretarial Staff"); - assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("ou=Clerical / Secretarial Staff"); - } - - @Test(expected = BadLdapGrammarException.class) - public void testLdapRdn_parse_quoteInKey() { - new LdapRdn("\"umanroleid=2583"); - } - - @Test - public void testLdapRdn_KeyValue_simple() { - LdapRdn rdn = new LdapRdn("foo", "bar"); - - assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); - assertThat(rdn.getComponent().getValue()).isEqualTo("bar"); - assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar"); - } - - @Test - public void testLdapRdn_KeyValue_valueNeedsEscape() { - LdapRdn rdn = new LdapRdn("foo", "bar\\"); - - assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); - assertThat(rdn.getComponent().getValue()).isEqualTo("bar\\"); - assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar\\\\"); - } - - @Test - public void testEncodeUrl() { - LdapRdn rdn = new LdapRdn("o = example.com "); - assertThat(rdn.encodeUrl()).isEqualTo("o=example.com"); - } - - @Test - public void testEncodeUrl_SpacesInValue() { - LdapRdn rdn = new LdapRdn("o = my organization "); - assertThat(rdn.encodeUrl()).isEqualTo("o=my%20organization"); - } - - @Test - public void testLdapRdn_Parse_MultipleComponents() { - LdapRdn rdn = new LdapRdn("cn=John Doe+sn=Doe"); - assertThat(rdn.getComponent(0).encodeLdap()).isEqualTo("cn=John Doe"); - assertThat(rdn.getComponent(1).encodeLdap()).isEqualTo("sn=Doe"); - assertThat(rdn.getLdapEncoded()).isEqualTo("cn=John Doe+sn=Doe"); - assertThat(rdn.getKey()).isEqualTo("cn"); - assertThat(rdn.getValue()).isEqualTo("John Doe"); - assertThat(rdn.getValue("cn")).isEqualTo("John Doe"); - assertThat(rdn.getValue("sn")).isEqualTo("Doe"); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetValueNoKeyWithCorrectValue() { - LdapRdn tested = new LdapRdn("cn=john doe"); - tested.getValue("sn"); - } - - @Test(expected = IllegalArgumentException.class) - public void testGetValueNoComponents() { - LdapRdn tested = new LdapRdn(); - tested.getValue("sn"); - } - - @Test - public void testEquals() throws Exception { - // original object - final Object originalObject = new LdapRdn("cn", "john.doe"); - - // another object that has the same values as the original - final Object identicalObject = new LdapRdn("cn", "john.doe"); - - // another object with different values - final Object differentObject = new LdapRdn("cn", "john.svensson"); - - // 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); - } - - @Test - public void testCompareTo_Equals() throws Exception { - LdapRdn rdn1 = new LdapRdn("cn=john doe"); - LdapRdn rdn2 = new LdapRdn("cn=john doe"); - - int result = rdn1.compareTo(rdn2); - assertThat(result).isEqualTo(0); - } - - @Test - public void verifyThatEqualsDisregardsOrder_Ldap260() throws Exception { - LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); - LdapRdn rdn2 = new LdapRdn("sn=doe+cn=john doe"); - - assertThat(rdn2).as("Should be equal").isEqualTo(rdn1); - } - - @Test - public void verifyThatHashcodeDisregardsOrder_Ldap260() throws Exception { - LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); - LdapRdn rdn2 = new LdapRdn("sn=doe+cn=john doe"); - - assertThat(rdn2.hashCode()).as("Should be equal").isEqualTo(rdn1.hashCode()); - } - - @Test - public void testCompareTo_EqualsComplex() throws Exception { - LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); - LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe"); - - int result = rdn1.compareTo(rdn2); - assertThat(result).isEqualTo(0); - } - - @Test - public void testCompareTo_LessWithMissingKey() { - LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); - LdapRdn rdn2 = new LdapRdn("cn=john doe+tn=doe"); - - int result = rdn1.compareTo(rdn2); - assertThat(result < 0).isTrue(); - } - - @Test - public void testCompareTo_LessWithExistingKey() { - LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doa"); - LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe"); - - int result = rdn1.compareTo(rdn2); - assertThat(result < 0).isTrue(); - } - - @Test - public void testCompareTo_Greater() { - LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); - LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doa"); - - int result = rdn1.compareTo(rdn2); - assertThat(result > 0).isTrue(); - } - - @Test - public void testCompareTo_Shorter() { - LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); - LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe+description=tjo"); - - int result = rdn1.compareTo(rdn2); - assertThat(result < 0).isTrue(); - } - - @Test - public void testCompareTo_Longer() { - LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe+description=tjo"); - LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe"); - - int result = rdn1.compareTo(rdn2); - assertThat(result > 0).isTrue(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; +import org.springframework.ldap.BadLdapGrammarException; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit test for the LdapRdn class. + * + * @author Adam Skogman + */ +public class LdapRdnTest { + + @Test + public void testLdapRdn_parse_simple() { + + LdapRdn rdn = new LdapRdn("foo=bar"); + + assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); + assertThat(rdn.getComponent().getValue()).isEqualTo("bar"); + assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar"); + assertThat(rdn.getKey()).isEqualTo("foo"); + assertThat(rdn.getValue()).isEqualTo("bar"); + } + + @Test + public void testLdapRdn_parse_spaces() { + + LdapRdn rdn = new LdapRdn(" foo = bar "); + + assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); + assertThat(rdn.getComponent().getValue()).isEqualTo("bar"); + assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar"); + } + + @Test + public void testLdapRdn_parse_escape() { + + LdapRdn rdn = new LdapRdn("foo=bar\\=fum"); + + assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); + assertThat(rdn.getComponent().getValue()).isEqualTo("bar=fum"); + assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar\\=fum"); + } + + @Test + public void testLdapRdn_parse_hexEscape() { + + LdapRdn rdn = new LdapRdn("foo=bar\\0dfum"); + + assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); + assertThat(rdn.getComponent().getValue()).isEqualTo("bar\rfum"); + assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar\\0Dfum"); + } + + @Test(expected = BadLdapGrammarException.class) + public void testLdapRdn_parse_trailingBackslash() { + new LdapRdn("foo=bar\\"); + } + + @Test + public void testLdapRdn_parse_spaces_escape() { + LdapRdn rdn = new LdapRdn(" foo = \\ bar\\20 \\ "); + + assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); + assertThat(rdn.getComponent().getValue()).isEqualTo(" bar "); + assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=\\ bar \\ "); + } + + @Test(expected = BadLdapGrammarException.class) + public void testLdapRdn_parse_tooMuchTrim() { + new LdapRdn("foo=bar\\"); + } + + @Test + public void testLdapRdn_parse_slash() { + LdapRdn rdn = new LdapRdn("ou=Clerical / Secretarial Staff"); + + assertThat(rdn.getComponent().getKey()).isEqualTo("ou"); + assertThat(rdn.getComponent().getValue()).isEqualTo("Clerical / Secretarial Staff"); + assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("ou=Clerical / Secretarial Staff"); + } + + @Test(expected = BadLdapGrammarException.class) + public void testLdapRdn_parse_quoteInKey() { + new LdapRdn("\"umanroleid=2583"); + } + + @Test + public void testLdapRdn_KeyValue_simple() { + LdapRdn rdn = new LdapRdn("foo", "bar"); + + assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); + assertThat(rdn.getComponent().getValue()).isEqualTo("bar"); + assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar"); + } + + @Test + public void testLdapRdn_KeyValue_valueNeedsEscape() { + LdapRdn rdn = new LdapRdn("foo", "bar\\"); + + assertThat(rdn.getComponent().getKey()).isEqualTo("foo"); + assertThat(rdn.getComponent().getValue()).isEqualTo("bar\\"); + assertThat(rdn.getComponent().getLdapEncoded()).isEqualTo("foo=bar\\\\"); + } + + @Test + public void testEncodeUrl() { + LdapRdn rdn = new LdapRdn("o = example.com "); + assertThat(rdn.encodeUrl()).isEqualTo("o=example.com"); + } + + @Test + public void testEncodeUrl_SpacesInValue() { + LdapRdn rdn = new LdapRdn("o = my organization "); + assertThat(rdn.encodeUrl()).isEqualTo("o=my%20organization"); + } + + @Test + public void testLdapRdn_Parse_MultipleComponents() { + LdapRdn rdn = new LdapRdn("cn=John Doe+sn=Doe"); + assertThat(rdn.getComponent(0).encodeLdap()).isEqualTo("cn=John Doe"); + assertThat(rdn.getComponent(1).encodeLdap()).isEqualTo("sn=Doe"); + assertThat(rdn.getLdapEncoded()).isEqualTo("cn=John Doe+sn=Doe"); + assertThat(rdn.getKey()).isEqualTo("cn"); + assertThat(rdn.getValue()).isEqualTo("John Doe"); + assertThat(rdn.getValue("cn")).isEqualTo("John Doe"); + assertThat(rdn.getValue("sn")).isEqualTo("Doe"); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetValueNoKeyWithCorrectValue() { + LdapRdn tested = new LdapRdn("cn=john doe"); + tested.getValue("sn"); + } + + @Test(expected = IllegalArgumentException.class) + public void testGetValueNoComponents() { + LdapRdn tested = new LdapRdn(); + tested.getValue("sn"); + } + + @Test + public void testEquals() throws Exception { + // original object + final Object originalObject = new LdapRdn("cn", "john.doe"); + + // another object that has the same values as the original + final Object identicalObject = new LdapRdn("cn", "john.doe"); + + // another object with different values + final Object differentObject = new LdapRdn("cn", "john.svensson"); + + // 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); + } + + @Test + public void testCompareTo_Equals() throws Exception { + LdapRdn rdn1 = new LdapRdn("cn=john doe"); + LdapRdn rdn2 = new LdapRdn("cn=john doe"); + + int result = rdn1.compareTo(rdn2); + assertThat(result).isEqualTo(0); + } + + @Test + public void verifyThatEqualsDisregardsOrder_Ldap260() throws Exception { + LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); + LdapRdn rdn2 = new LdapRdn("sn=doe+cn=john doe"); + + assertThat(rdn2).as("Should be equal").isEqualTo(rdn1); + } + + @Test + public void verifyThatHashcodeDisregardsOrder_Ldap260() throws Exception { + LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); + LdapRdn rdn2 = new LdapRdn("sn=doe+cn=john doe"); + + assertThat(rdn2.hashCode()).as("Should be equal").isEqualTo(rdn1.hashCode()); + } + + @Test + public void testCompareTo_EqualsComplex() throws Exception { + LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); + LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe"); + + int result = rdn1.compareTo(rdn2); + assertThat(result).isEqualTo(0); + } + + @Test + public void testCompareTo_LessWithMissingKey() { + LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); + LdapRdn rdn2 = new LdapRdn("cn=john doe+tn=doe"); + + int result = rdn1.compareTo(rdn2); + assertThat(result < 0).isTrue(); + } + + @Test + public void testCompareTo_LessWithExistingKey() { + LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doa"); + LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe"); + + int result = rdn1.compareTo(rdn2); + assertThat(result < 0).isTrue(); + } + + @Test + public void testCompareTo_Greater() { + LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); + LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doa"); + + int result = rdn1.compareTo(rdn2); + assertThat(result > 0).isTrue(); + } + + @Test + public void testCompareTo_Shorter() { + LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe"); + LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe+description=tjo"); + + int result = rdn1.compareTo(rdn2); + assertThat(result < 0).isTrue(); + } + + @Test + public void testCompareTo_Longer() { + LdapRdn rdn1 = new LdapRdn("cn=john doe+sn=doe+description=tjo"); + LdapRdn rdn2 = new LdapRdn("cn=john doe+sn=doe"); + + 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 d13b5759..b11f3765 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateListTest.java @@ -1,322 +1,322 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.LimitExceededException; -import org.springframework.ldap.PartialResultException; - -import javax.naming.Binding; -import javax.naming.Name; -import javax.naming.NameClassPair; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.ldap.LdapContext; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Unit tests for the list operations in {@link LdapTemplate}. - * - * @author Ulrik Sandberg - */ -public class LdapTemplateListTest { - - private static final String NAME = "o=example.com"; - - private static final String CLASS = "com.example.SomeClass"; - - private ContextSource contextSourceMock; - - private DirContext dirContextMock; - - private NamingEnumeration namingEnumerationMock; - - private Name nameMock; - - private NameClassPairCallbackHandler handlerMock; - - private ContextMapper contextMapperMock; - - private LdapTemplate tested; - - @Before - public void setUp() throws Exception { - // Setup ContextSource mock - contextSourceMock = mock(ContextSource.class); - - // Setup LdapContext mock - dirContextMock = mock(LdapContext.class); - - // Setup NamingEnumeration mock - namingEnumerationMock = mock(NamingEnumeration.class); - - // Setup Name mock - nameMock = mock(Name.class); - - // Setup Handler mock - handlerMock = mock(NameClassPairCallbackHandler.class); - - contextMapperMock = mock(ContextMapper.class); - - tested = new LdapTemplate(contextSourceMock); - } - - private void expectGetReadOnlyContext() { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - } - - private void setupStringListAndNamingEnumeration(NameClassPair listResult) - throws NamingException { - when(dirContextMock.list(NAME)).thenReturn(namingEnumerationMock); - - setupNamingEnumeration(listResult); - } - - private void setupListAndNamingEnumeration(NameClassPair listResult) - throws NamingException { - when(dirContextMock.list(nameMock)).thenReturn(namingEnumerationMock); - - setupNamingEnumeration(listResult); - } - - private void setupStringListBindingsAndNamingEnumeration( - NameClassPair listResult) throws NamingException { - when(dirContextMock.listBindings(NAME)).thenReturn(namingEnumerationMock); - - setupNamingEnumeration(listResult); - } - - private void setupListBindingsAndNamingEnumeration(NameClassPair listResult) - throws NamingException { - when(dirContextMock.listBindings(nameMock)).thenReturn(namingEnumerationMock); - - setupNamingEnumeration(listResult); - } - - private void setupNamingEnumeration(NameClassPair listResult) - throws NamingException { - when(namingEnumerationMock.hasMore()).thenReturn(true, false); - when(namingEnumerationMock.next()).thenReturn(listResult); - } - - @Test - public void testList_Name() throws NamingException { - expectGetReadOnlyContext(); - - NameClassPair listResult = new NameClassPair(NAME, CLASS); - - setupListAndNamingEnumeration(listResult); - - List list = tested.list(nameMock); - - verify(dirContextMock).close(); - verify(namingEnumerationMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(NAME); - } - - @Test - public void testList_String() throws NamingException { - expectGetReadOnlyContext(); - - NameClassPair listResult = new NameClassPair(NAME, CLASS); - - setupStringListAndNamingEnumeration(listResult); - - List list = tested.list(NAME); - - verify(dirContextMock).close(); - verify(namingEnumerationMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(NAME); - } - - @Test - public void testList_Name_CallbackHandler() throws NamingException { - expectGetReadOnlyContext(); - - NameClassPair listResult = new NameClassPair(NAME, CLASS); - - setupListAndNamingEnumeration(listResult); - - tested.list(nameMock, handlerMock); - - verify(handlerMock).handleNameClassPair(listResult); - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void testList_String_CallbackHandler() throws NamingException { - expectGetReadOnlyContext(); - - NameClassPair listResult = new NameClassPair(NAME, CLASS); - - setupStringListAndNamingEnumeration(listResult); - - tested.list("o=example.com", handlerMock); - - verify(handlerMock).handleNameClassPair(listResult); - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void testList_PartialResultException() throws NamingException { - expectGetReadOnlyContext(); - - javax.naming.PartialResultException pre = new javax.naming.PartialResultException(); - when(dirContextMock.list(NAME)).thenThrow(pre); - - try { - tested.list(NAME); - fail("PartialResultException expected"); - } catch (PartialResultException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testList_PartialResultException_Ignore() throws NamingException { - expectGetReadOnlyContext(); - - javax.naming.PartialResultException pre = new javax.naming.PartialResultException(); - when(dirContextMock.list(NAME)).thenThrow(pre); - - tested.setIgnorePartialResultException(true); - - List list = tested.list(NAME); - - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).isEmpty(); - } - - @Test - public void testList_NamingException() throws NamingException { - expectGetReadOnlyContext(); - - javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - when(dirContextMock.list(NAME)).thenThrow(ne); - - try { - tested.list(NAME); - fail("LimitExceededException expected"); - } catch (LimitExceededException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - // Tests for listBindings - - @Test - public void testListBindings_String() throws NamingException { - expectGetReadOnlyContext(); - - Binding listResult = new Binding(NAME, CLASS, null); - - setupStringListBindingsAndNamingEnumeration(listResult); - - List list = tested.listBindings(NAME); - - verify(dirContextMock).close(); - verify(namingEnumerationMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(NAME); - } - - @Test - public void testListBindings_Name() throws NamingException { - expectGetReadOnlyContext(); - - Binding listResult = new Binding(NAME, CLASS, null); - - setupListBindingsAndNamingEnumeration(listResult); - - List list = tested.listBindings(nameMock); - - verify(dirContextMock).close(); - verify(namingEnumerationMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(NAME); - } - - @Test - public void testListBindings_ContextMapper() throws NamingException { - expectGetReadOnlyContext(); - - Object expectedObject = new Object(); - Binding listResult = new Binding("", expectedObject); - - setupStringListBindingsAndNamingEnumeration(listResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.listBindings(NAME, contextMapperMock); - - verify(dirContextMock).close(); - verify(namingEnumerationMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testListBindings_Name_ContextMapper() throws NamingException { - expectGetReadOnlyContext(); - - Object expectedObject = new Object(); - Binding listResult = new Binding("", expectedObject); - - setupListBindingsAndNamingEnumeration(listResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.listBindings(nameMock, contextMapperMock); - - verify(dirContextMock).close(); - verify(namingEnumerationMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.LimitExceededException; +import org.springframework.ldap.PartialResultException; + +import javax.naming.Binding; +import javax.naming.Name; +import javax.naming.NameClassPair; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.ldap.LdapContext; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Unit tests for the list operations in {@link LdapTemplate}. + * + * @author Ulrik Sandberg + */ +public class LdapTemplateListTest { + + private static final String NAME = "o=example.com"; + + private static final String CLASS = "com.example.SomeClass"; + + private ContextSource contextSourceMock; + + private DirContext dirContextMock; + + private NamingEnumeration namingEnumerationMock; + + private Name nameMock; + + private NameClassPairCallbackHandler handlerMock; + + private ContextMapper contextMapperMock; + + private LdapTemplate tested; + + @Before + public void setUp() throws Exception { + // Setup ContextSource mock + contextSourceMock = mock(ContextSource.class); + + // Setup LdapContext mock + dirContextMock = mock(LdapContext.class); + + // Setup NamingEnumeration mock + namingEnumerationMock = mock(NamingEnumeration.class); + + // Setup Name mock + nameMock = mock(Name.class); + + // Setup Handler mock + handlerMock = mock(NameClassPairCallbackHandler.class); + + contextMapperMock = mock(ContextMapper.class); + + tested = new LdapTemplate(contextSourceMock); + } + + private void expectGetReadOnlyContext() { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + } + + private void setupStringListAndNamingEnumeration(NameClassPair listResult) + throws NamingException { + when(dirContextMock.list(NAME)).thenReturn(namingEnumerationMock); + + setupNamingEnumeration(listResult); + } + + private void setupListAndNamingEnumeration(NameClassPair listResult) + throws NamingException { + when(dirContextMock.list(nameMock)).thenReturn(namingEnumerationMock); + + setupNamingEnumeration(listResult); + } + + private void setupStringListBindingsAndNamingEnumeration( + NameClassPair listResult) throws NamingException { + when(dirContextMock.listBindings(NAME)).thenReturn(namingEnumerationMock); + + setupNamingEnumeration(listResult); + } + + private void setupListBindingsAndNamingEnumeration(NameClassPair listResult) + throws NamingException { + when(dirContextMock.listBindings(nameMock)).thenReturn(namingEnumerationMock); + + setupNamingEnumeration(listResult); + } + + private void setupNamingEnumeration(NameClassPair listResult) + throws NamingException { + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(listResult); + } + + @Test + public void testList_Name() throws NamingException { + expectGetReadOnlyContext(); + + NameClassPair listResult = new NameClassPair(NAME, CLASS); + + setupListAndNamingEnumeration(listResult); + + List list = tested.list(nameMock); + + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(NAME); + } + + @Test + public void testList_String() throws NamingException { + expectGetReadOnlyContext(); + + NameClassPair listResult = new NameClassPair(NAME, CLASS); + + setupStringListAndNamingEnumeration(listResult); + + List list = tested.list(NAME); + + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(NAME); + } + + @Test + public void testList_Name_CallbackHandler() throws NamingException { + expectGetReadOnlyContext(); + + NameClassPair listResult = new NameClassPair(NAME, CLASS); + + setupListAndNamingEnumeration(listResult); + + tested.list(nameMock, handlerMock); + + verify(handlerMock).handleNameClassPair(listResult); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void testList_String_CallbackHandler() throws NamingException { + expectGetReadOnlyContext(); + + NameClassPair listResult = new NameClassPair(NAME, CLASS); + + setupStringListAndNamingEnumeration(listResult); + + tested.list("o=example.com", handlerMock); + + verify(handlerMock).handleNameClassPair(listResult); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void testList_PartialResultException() throws NamingException { + expectGetReadOnlyContext(); + + javax.naming.PartialResultException pre = new javax.naming.PartialResultException(); + when(dirContextMock.list(NAME)).thenThrow(pre); + + try { + tested.list(NAME); + fail("PartialResultException expected"); + } catch (PartialResultException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testList_PartialResultException_Ignore() throws NamingException { + expectGetReadOnlyContext(); + + javax.naming.PartialResultException pre = new javax.naming.PartialResultException(); + when(dirContextMock.list(NAME)).thenThrow(pre); + + tested.setIgnorePartialResultException(true); + + List list = tested.list(NAME); + + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).isEmpty(); + } + + @Test + public void testList_NamingException() throws NamingException { + expectGetReadOnlyContext(); + + javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); + when(dirContextMock.list(NAME)).thenThrow(ne); + + try { + tested.list(NAME); + fail("LimitExceededException expected"); + } catch (LimitExceededException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + // Tests for listBindings + + @Test + public void testListBindings_String() throws NamingException { + expectGetReadOnlyContext(); + + Binding listResult = new Binding(NAME, CLASS, null); + + setupStringListBindingsAndNamingEnumeration(listResult); + + List list = tested.listBindings(NAME); + + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(NAME); + } + + @Test + public void testListBindings_Name() throws NamingException { + expectGetReadOnlyContext(); + + Binding listResult = new Binding(NAME, CLASS, null); + + setupListBindingsAndNamingEnumeration(listResult); + + List list = tested.listBindings(nameMock); + + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(NAME); + } + + @Test + public void testListBindings_ContextMapper() throws NamingException { + expectGetReadOnlyContext(); + + Object expectedObject = new Object(); + Binding listResult = new Binding("", expectedObject); + + setupStringListBindingsAndNamingEnumeration(listResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.listBindings(NAME, contextMapperMock); + + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testListBindings_Name_ContextMapper() throws NamingException { + expectGetReadOnlyContext(); + + Object expectedObject = new Object(); + Binding listResult = new Binding("", expectedObject); + + setupListBindingsAndNamingEnumeration(listResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.listBindings(nameMock, contextMapperMock); + + verify(dirContextMock).close(); + verify(namingEnumerationMock).close(); + + assertThat(list).isNotNull(); + 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 8cecb8c4..2dc1d658 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateLookupTest.java @@ -1,354 +1,354 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.util.Collections; - -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.directory.BasicAttributes; -import javax.naming.directory.DirContext; -import javax.naming.ldap.LdapContext; -import javax.naming.ldap.LdapName; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.odm.core.ObjectDirectoryMapper; -import org.springframework.ldap.support.LdapUtils; - -public class LdapTemplateLookupTest { - - private static final String DEFAULT_BASE_STRING = "o=example.com"; - - private ContextSource contextSourceMock; - - private DirContext dirContextMock; - - private AttributesMapper attributesMapperMock; - - private Name nameMock; - - private ContextMapper contextMapperMock; - - private LdapTemplate tested; - private ObjectDirectoryMapper odmMock; - - @Before - public void setUp() throws Exception { - // Setup ContextSource mock - contextSourceMock = mock(ContextSource.class); - - // Setup LdapContext mock - dirContextMock = mock(LdapContext.class); - - // Setup Name mock - nameMock = mock(Name.class); - contextMapperMock = mock(ContextMapper.class); - attributesMapperMock = mock(AttributesMapper.class); - odmMock = mock(ObjectDirectoryMapper.class); - - tested = new LdapTemplate(contextSourceMock); - tested.setObjectDirectoryMapper(odmMock); - } - - private void expectGetReadOnlyContext() { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - } - - // Tests for lookup(name) - - @Test - public void testLookup() throws Exception { - expectGetReadOnlyContext(); - - Object expected = new Object(); - when(dirContextMock.lookup(nameMock)).thenReturn(expected); - - Object actual = tested.lookup(nameMock); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(expected); - } - - @Test - public void testLookup_String() throws Exception { - expectGetReadOnlyContext(); - - Object expected = new Object(); - when(dirContextMock.lookup(DEFAULT_BASE_STRING)).thenReturn(expected); - - Object actual = tested.lookup(DEFAULT_BASE_STRING); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(expected); - } - - @Test - public void testLookup_NamingException() throws Exception { - expectGetReadOnlyContext(); - - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - when(dirContextMock.lookup(nameMock)).thenThrow(ne); - - try { - tested.lookup(nameMock); - fail("NameNotFoundException expected"); - } catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - // Tests for lookup(name, AttributesMapper) - - @Test - public void testLookup_AttributesMapper() throws Exception { - expectGetReadOnlyContext(); - - BasicAttributes expectedAttributes = new BasicAttributes(); - when(dirContextMock.getAttributes(nameMock)).thenReturn(expectedAttributes); - - Object expected = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); - - Object actual = tested.lookup(nameMock, attributesMapperMock); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(expected); - } - - @Test - public void testLookup_String_AttributesMapper() throws Exception { - expectGetReadOnlyContext(); - - BasicAttributes expectedAttributes = new BasicAttributes(); - when(dirContextMock.getAttributes(DEFAULT_BASE_STRING)).thenReturn(expectedAttributes); - - Object expected = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); - - Object actual = tested - .lookup(DEFAULT_BASE_STRING, attributesMapperMock); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(expected); - } - - @Test - public void testLookup_AttributesMapper_NamingException() throws Exception { - expectGetReadOnlyContext(); - - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - when(dirContextMock.getAttributes(nameMock)).thenThrow(ne); - - try { - tested.lookup(nameMock, attributesMapperMock); - fail("NameNotFoundException expected"); - } catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - // Tests for lookup(name, ContextMapper) - - @Test - public void testLookup_ContextMapper() throws Exception { - expectGetReadOnlyContext(); - - Object transformed = new Object(); - Object expected = new Object(); - when(dirContextMock.lookup(nameMock)).thenReturn(expected); - - when(contextMapperMock.mapFromContext(expected)).thenReturn(transformed); - - Object actual = tested.lookup(nameMock, contextMapperMock); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(transformed); - } - - @Test - public void testFindByDn() throws NamingException { - expectGetReadOnlyContext(); - - Object transformed = new Object(); - Class expectedClass = Object.class; - - DirContextAdapter expectedContext = new DirContextAdapter(); - when(dirContextMock.lookup(nameMock)).thenReturn(expectedContext); - when(odmMock.mapFromLdapDataEntry(expectedContext, expectedClass)).thenReturn(transformed); - - when(nameMock.getAll()).thenReturn(Collections. enumeration(Collections. emptyList())); - // Perform test - Object result = tested.findByDn(nameMock, expectedClass); - assertThat(result).isSameAs(transformed); - - verify(odmMock).manageClass(expectedClass); - } - - - - @Test - public void testLookup_String_ContextMapper() throws Exception { - expectGetReadOnlyContext(); - - Object transformed = new Object(); - Object expected = new Object(); - when(dirContextMock.lookup(DEFAULT_BASE_STRING)).thenReturn(expected); - - when(contextMapperMock.mapFromContext(expected)).thenReturn(transformed); - - Object actual = tested.lookup(DEFAULT_BASE_STRING, contextMapperMock); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(transformed); - } - - @Test - public void testLookup_ContextMapper_NamingException() throws Exception { - expectGetReadOnlyContext(); - - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - when(dirContextMock.lookup(nameMock)).thenThrow(ne); - - try { - tested.lookup(nameMock, contextMapperMock); - fail("NameNotFoundException expected"); - } catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - // Tests for lookup(name, attributes, AttributesMapper) - - @Test - public void testLookup_ReturnAttributes_AttributesMapper() throws Exception { - expectGetReadOnlyContext(); - - String[] attributeNames = new String[] { "cn" }; - - BasicAttributes expectedAttributes = new BasicAttributes(); - expectedAttributes.put("cn", "Some Name"); - - when(dirContextMock.getAttributes(nameMock, attributeNames)).thenReturn(expectedAttributes); - - Object expected = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); - - Object actual = tested.lookup(nameMock, attributeNames, - attributesMapperMock); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(expected); - } - - @Test - public void testLookup_String_ReturnAttributes_AttributesMapper() - throws Exception { - expectGetReadOnlyContext(); - - String[] attributeNames = new String[] { "cn" }; - - BasicAttributes expectedAttributes = new BasicAttributes(); - expectedAttributes.put("cn", "Some Name"); - - when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); - - Object expected = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); - - Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, - attributesMapperMock); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(expected); - } - - // Tests for lookup(name, attributes, ContextMapper) - - @Test - public void testLookup_ReturnAttributes_ContextMapper() throws Exception { - expectGetReadOnlyContext(); - - String[] attributeNames = new String[] { "cn" }; - - BasicAttributes expectedAttributes = new BasicAttributes(); - expectedAttributes.put("cn", "Some Name"); - - LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING); - DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, - name); - - when(dirContextMock.getAttributes(name,attributeNames)).thenReturn(expectedAttributes); - - Object transformed = new Object(); - when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed); - - Object actual = tested.lookup(name, attributeNames, contextMapperMock); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(transformed); - } - - @Test - public void testLookup_String_ReturnAttributes_ContextMapper() - throws Exception { - expectGetReadOnlyContext(); - - String[] attributeNames = new String[] { "cn" }; - - BasicAttributes expectedAttributes = new BasicAttributes(); - expectedAttributes.put("cn", "Some Name"); - - when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); - - LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING); - 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); - - verify(dirContextMock).close(); - - assertThat(actual).isSameAs(transformed); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Collections; + +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.directory.BasicAttributes; +import javax.naming.directory.DirContext; +import javax.naming.ldap.LdapContext; +import javax.naming.ldap.LdapName; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.odm.core.ObjectDirectoryMapper; +import org.springframework.ldap.support.LdapUtils; + +public class LdapTemplateLookupTest { + + private static final String DEFAULT_BASE_STRING = "o=example.com"; + + private ContextSource contextSourceMock; + + private DirContext dirContextMock; + + private AttributesMapper attributesMapperMock; + + private Name nameMock; + + private ContextMapper contextMapperMock; + + private LdapTemplate tested; + private ObjectDirectoryMapper odmMock; + + @Before + public void setUp() throws Exception { + // Setup ContextSource mock + contextSourceMock = mock(ContextSource.class); + + // Setup LdapContext mock + dirContextMock = mock(LdapContext.class); + + // Setup Name mock + nameMock = mock(Name.class); + contextMapperMock = mock(ContextMapper.class); + attributesMapperMock = mock(AttributesMapper.class); + odmMock = mock(ObjectDirectoryMapper.class); + + tested = new LdapTemplate(contextSourceMock); + tested.setObjectDirectoryMapper(odmMock); + } + + private void expectGetReadOnlyContext() { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + } + + // Tests for lookup(name) + + @Test + public void testLookup() throws Exception { + expectGetReadOnlyContext(); + + Object expected = new Object(); + when(dirContextMock.lookup(nameMock)).thenReturn(expected); + + Object actual = tested.lookup(nameMock); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(expected); + } + + @Test + public void testLookup_String() throws Exception { + expectGetReadOnlyContext(); + + Object expected = new Object(); + when(dirContextMock.lookup(DEFAULT_BASE_STRING)).thenReturn(expected); + + Object actual = tested.lookup(DEFAULT_BASE_STRING); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(expected); + } + + @Test + public void testLookup_NamingException() throws Exception { + expectGetReadOnlyContext(); + + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + when(dirContextMock.lookup(nameMock)).thenThrow(ne); + + try { + tested.lookup(nameMock); + fail("NameNotFoundException expected"); + } catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + // Tests for lookup(name, AttributesMapper) + + @Test + public void testLookup_AttributesMapper() throws Exception { + expectGetReadOnlyContext(); + + BasicAttributes expectedAttributes = new BasicAttributes(); + when(dirContextMock.getAttributes(nameMock)).thenReturn(expectedAttributes); + + Object expected = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); + + Object actual = tested.lookup(nameMock, attributesMapperMock); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(expected); + } + + @Test + public void testLookup_String_AttributesMapper() throws Exception { + expectGetReadOnlyContext(); + + BasicAttributes expectedAttributes = new BasicAttributes(); + when(dirContextMock.getAttributes(DEFAULT_BASE_STRING)).thenReturn(expectedAttributes); + + Object expected = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); + + Object actual = tested + .lookup(DEFAULT_BASE_STRING, attributesMapperMock); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(expected); + } + + @Test + public void testLookup_AttributesMapper_NamingException() throws Exception { + expectGetReadOnlyContext(); + + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + when(dirContextMock.getAttributes(nameMock)).thenThrow(ne); + + try { + tested.lookup(nameMock, attributesMapperMock); + fail("NameNotFoundException expected"); + } catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + // Tests for lookup(name, ContextMapper) + + @Test + public void testLookup_ContextMapper() throws Exception { + expectGetReadOnlyContext(); + + Object transformed = new Object(); + Object expected = new Object(); + when(dirContextMock.lookup(nameMock)).thenReturn(expected); + + when(contextMapperMock.mapFromContext(expected)).thenReturn(transformed); + + Object actual = tested.lookup(nameMock, contextMapperMock); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(transformed); + } + + @Test + public void testFindByDn() throws NamingException { + expectGetReadOnlyContext(); + + Object transformed = new Object(); + Class expectedClass = Object.class; + + DirContextAdapter expectedContext = new DirContextAdapter(); + when(dirContextMock.lookup(nameMock)).thenReturn(expectedContext); + when(odmMock.mapFromLdapDataEntry(expectedContext, expectedClass)).thenReturn(transformed); + + when(nameMock.getAll()).thenReturn(Collections. enumeration(Collections. emptyList())); + // Perform test + Object result = tested.findByDn(nameMock, expectedClass); + assertThat(result).isSameAs(transformed); + + verify(odmMock).manageClass(expectedClass); + } + + + + @Test + public void testLookup_String_ContextMapper() throws Exception { + expectGetReadOnlyContext(); + + Object transformed = new Object(); + Object expected = new Object(); + when(dirContextMock.lookup(DEFAULT_BASE_STRING)).thenReturn(expected); + + when(contextMapperMock.mapFromContext(expected)).thenReturn(transformed); + + Object actual = tested.lookup(DEFAULT_BASE_STRING, contextMapperMock); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(transformed); + } + + @Test + public void testLookup_ContextMapper_NamingException() throws Exception { + expectGetReadOnlyContext(); + + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + when(dirContextMock.lookup(nameMock)).thenThrow(ne); + + try { + tested.lookup(nameMock, contextMapperMock); + fail("NameNotFoundException expected"); + } catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + // Tests for lookup(name, attributes, AttributesMapper) + + @Test + public void testLookup_ReturnAttributes_AttributesMapper() throws Exception { + expectGetReadOnlyContext(); + + String[] attributeNames = new String[] { "cn" }; + + BasicAttributes expectedAttributes = new BasicAttributes(); + expectedAttributes.put("cn", "Some Name"); + + when(dirContextMock.getAttributes(nameMock, attributeNames)).thenReturn(expectedAttributes); + + Object expected = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); + + Object actual = tested.lookup(nameMock, attributeNames, + attributesMapperMock); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(expected); + } + + @Test + public void testLookup_String_ReturnAttributes_AttributesMapper() + throws Exception { + expectGetReadOnlyContext(); + + String[] attributeNames = new String[] { "cn" }; + + BasicAttributes expectedAttributes = new BasicAttributes(); + expectedAttributes.put("cn", "Some Name"); + + when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); + + Object expected = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expected); + + Object actual = tested.lookup(DEFAULT_BASE_STRING, attributeNames, + attributesMapperMock); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(expected); + } + + // Tests for lookup(name, attributes, ContextMapper) + + @Test + public void testLookup_ReturnAttributes_ContextMapper() throws Exception { + expectGetReadOnlyContext(); + + String[] attributeNames = new String[] { "cn" }; + + BasicAttributes expectedAttributes = new BasicAttributes(); + expectedAttributes.put("cn", "Some Name"); + + LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING); + DirContextAdapter adapter = new DirContextAdapter(expectedAttributes, + name); + + when(dirContextMock.getAttributes(name,attributeNames)).thenReturn(expectedAttributes); + + Object transformed = new Object(); + when(contextMapperMock.mapFromContext(adapter)).thenReturn(transformed); + + Object actual = tested.lookup(name, attributeNames, contextMapperMock); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(transformed); + } + + @Test + public void testLookup_String_ReturnAttributes_ContextMapper() + throws Exception { + expectGetReadOnlyContext(); + + String[] attributeNames = new String[] { "cn" }; + + BasicAttributes expectedAttributes = new BasicAttributes(); + expectedAttributes.put("cn", "Some Name"); + + when(dirContextMock.getAttributes(DEFAULT_BASE_STRING, attributeNames)).thenReturn(expectedAttributes); + + LdapName name = LdapUtils.newLdapName(DEFAULT_BASE_STRING); + 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); + + verify(dirContextMock).close(); + + assertThat(actual).isSameAs(transformed); + } +} 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 62ea8373..6d0b7680 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateRenameTest.java @@ -1,127 +1,127 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.NameAlreadyBoundException; -import org.springframework.ldap.UncategorizedLdapException; - -import javax.naming.Name; -import javax.naming.directory.DirContext; -import javax.naming.ldap.LdapContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * Unit tests for the rename operations in the LdapTemplate class. - * - * @author Ulrik Sandberg - */ -public class LdapTemplateRenameTest { - - private ContextSource contextSourceMock; - - private DirContext dirContextMock; - - private Name oldNameMock; - - private Name newNameMock; - - private LdapTemplate tested; - - @Before - public void setUp() throws Exception { - // Setup ContextSource mock - contextSourceMock = mock(ContextSource.class); - - // Setup LdapContext mock - dirContextMock = mock(LdapContext.class); - - // Setup Name mock for old name - oldNameMock = mock(Name.class); - - // Setup Name mock for new name - newNameMock = mock(Name.class); - - tested = new LdapTemplate(contextSourceMock); - } - - private void expectGetReadWriteContext() { - when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); - } - - @Test - public void testRename() throws Exception { - expectGetReadWriteContext(); - - tested.rename(oldNameMock, newNameMock); - - verify(dirContextMock).rename(oldNameMock, newNameMock); - verify(dirContextMock).close(); - } - - @Test - public void testRename_NameAlreadyBoundException() throws Exception { - expectGetReadWriteContext(); - - javax.naming.NameAlreadyBoundException ne = new javax.naming.NameAlreadyBoundException(); - doThrow(ne).when(dirContextMock).rename(oldNameMock, newNameMock); - - try { - tested.rename(oldNameMock, newNameMock); - fail("NameAlreadyBoundException expected"); - } catch (NameAlreadyBoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testRename_NamingException() throws Exception { - expectGetReadWriteContext(); - - javax.naming.NamingException ne = new javax.naming.NamingException(); - - doThrow(ne).when(dirContextMock).rename(oldNameMock, newNameMock); - - try { - tested.rename(oldNameMock, newNameMock); - fail("UncategorizedLdapException expected"); - } catch (UncategorizedLdapException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testRename_String() throws Exception { - expectGetReadWriteContext(); - - tested.rename("o=example.com", "o=somethingelse.com"); - - verify(dirContextMock).rename("o=example.com", "o=somethingelse.com"); - verify(dirContextMock).close(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.NameAlreadyBoundException; +import org.springframework.ldap.UncategorizedLdapException; + +import javax.naming.Name; +import javax.naming.directory.DirContext; +import javax.naming.ldap.LdapContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Unit tests for the rename operations in the LdapTemplate class. + * + * @author Ulrik Sandberg + */ +public class LdapTemplateRenameTest { + + private ContextSource contextSourceMock; + + private DirContext dirContextMock; + + private Name oldNameMock; + + private Name newNameMock; + + private LdapTemplate tested; + + @Before + public void setUp() throws Exception { + // Setup ContextSource mock + contextSourceMock = mock(ContextSource.class); + + // Setup LdapContext mock + dirContextMock = mock(LdapContext.class); + + // Setup Name mock for old name + oldNameMock = mock(Name.class); + + // Setup Name mock for new name + newNameMock = mock(Name.class); + + tested = new LdapTemplate(contextSourceMock); + } + + private void expectGetReadWriteContext() { + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); + } + + @Test + public void testRename() throws Exception { + expectGetReadWriteContext(); + + tested.rename(oldNameMock, newNameMock); + + verify(dirContextMock).rename(oldNameMock, newNameMock); + verify(dirContextMock).close(); + } + + @Test + public void testRename_NameAlreadyBoundException() throws Exception { + expectGetReadWriteContext(); + + javax.naming.NameAlreadyBoundException ne = new javax.naming.NameAlreadyBoundException(); + doThrow(ne).when(dirContextMock).rename(oldNameMock, newNameMock); + + try { + tested.rename(oldNameMock, newNameMock); + fail("NameAlreadyBoundException expected"); + } catch (NameAlreadyBoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testRename_NamingException() throws Exception { + expectGetReadWriteContext(); + + javax.naming.NamingException ne = new javax.naming.NamingException(); + + doThrow(ne).when(dirContextMock).rename(oldNameMock, newNameMock); + + try { + tested.rename(oldNameMock, newNameMock); + fail("UncategorizedLdapException expected"); + } catch (UncategorizedLdapException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testRename_String() throws Exception { + expectGetReadWriteContext(); + + tested.rename("o=example.com", "o=somethingelse.com"); + + 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 ac05017c..7e704121 100644 --- a/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java +++ b/core/src/test/java/org/springframework/ldap/core/LdapTemplateTest.java @@ -1,1939 +1,1939 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core; - -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.ArgumentMatcher; -import org.mockito.verification.VerificationMode; - -import org.springframework.LdapDataEntry; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.ldap.LimitExceededException; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.PartialResultException; -import org.springframework.ldap.UncategorizedLdapException; -import org.springframework.ldap.filter.EqualsFilter; -import org.springframework.ldap.filter.Filter; -import org.springframework.ldap.odm.core.ObjectDirectoryMapper; -import org.springframework.ldap.query.LdapQuery; -import org.springframework.ldap.query.LdapQueryBuilder; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.Binding; -import javax.naming.CompositeName; -import javax.naming.Name; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.BasicAttributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.ModificationItem; -import javax.naming.directory.SearchControls; -import javax.naming.directory.SearchResult; -import javax.naming.ldap.LdapContext; -import javax.naming.ldap.LdapName; - -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.argThat; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import static org.springframework.ldap.query.LdapQueryBuilder.query; - -/** - * Unit tests for the LdapTemplate class. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public class LdapTemplateTest { - - private static final String DEFAULT_BASE_STRING = "o=example.com"; - - private ContextSource contextSourceMock; - - private DirContext dirContextMock; - - private AttributesMapper attributesMapperMock; - - private NamingEnumeration namingEnumerationMock; - - private Name nameMock; - - private NameClassPairCallbackHandler handlerMock; - - private ContextMapper contextMapperMock; - - private ContextExecutor contextExecutorMock; - - private SearchExecutor searchExecutorMock; - - private LdapTemplate tested; - - private DirContextProcessor dirContextProcessorMock; - - private DirContextOperations dirContextOperationsMock; - - private DirContext authenticatedContextMock; - - private AuthenticatedLdapEntryContextCallback entryContextCallbackMock; - private ObjectDirectoryMapper odmMock; - - private LdapQuery query; - private AuthenticatedLdapEntryContextMapper authContextMapperMock; - - @Before - public void setUp() throws Exception { - - // Setup ContextSource mock - contextSourceMock = mock(ContextSource.class); - // Setup LdapContext mock - dirContextMock = mock(LdapContext.class); - // Setup NamingEnumeration mock - namingEnumerationMock = mock(NamingEnumeration.class); - // Setup Name mock - nameMock = LdapUtils.emptyLdapName(); - // Setup Handler mock - handlerMock = mock(NameClassPairCallbackHandler.class); - contextMapperMock = mock(ContextMapper.class); - attributesMapperMock = mock(AttributesMapper.class); - contextExecutorMock = mock(ContextExecutor.class); - searchExecutorMock = mock(SearchExecutor.class); - dirContextProcessorMock = mock(DirContextProcessor.class); - dirContextOperationsMock = mock(DirContextOperations.class); - authenticatedContextMock = mock(DirContext.class); - entryContextCallbackMock = mock(AuthenticatedLdapEntryContextCallback.class); - odmMock = mock(ObjectDirectoryMapper.class); - query = LdapQueryBuilder.query().base("ou=spring").filter("ou=user"); - authContextMapperMock = mock(AuthenticatedLdapEntryContextMapper.class); - - tested = new LdapTemplate(contextSourceMock); - tested.setObjectDirectoryMapper(odmMock); - } - - private void expectGetReadWriteContext() { - when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); - } - - private void expectGetReadOnlyContext() { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - } - - @Test - public void testSearch_CallbackHandler() throws Exception { - expectGetReadOnlyContext(); - - SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); - - singleSearchResult(searchControlsOneLevel(), searchResult); - - tested.search(nameMock, "(ou=somevalue)", 1, true, handlerMock); - - verify(handlerMock).handleNameClassPair(searchResult); - verify(dirContextMock).close(); - } - - @Test - public void testSearch_StringBase_CallbackHandler() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsOneLevel(); - - SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); - - singleSearchResultWithStringBase(controls, searchResult); - - tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, true, handlerMock); - - verify(handlerMock).handleNameClassPair(searchResult); - verify(dirContextMock).close(); - } - - @Test - public void testSearch_CallbackHandler_Defaults() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - controls.setReturningObjFlag(false); - - SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); - - singleSearchResult(controls, searchResult); - - tested.search(nameMock, "(ou=somevalue)", handlerMock); - - verify(handlerMock).handleNameClassPair(searchResult); - verify(dirContextMock).close(); - } - - @Test - public void testSearch_String_CallbackHandler_Defaults() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - controls.setReturningObjFlag(false); - - SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); - - singleSearchResultWithStringBase(controls, searchResult); - - tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", handlerMock); - - verify(handlerMock).handleNameClassPair(searchResult); - verify(dirContextMock).close(); - } - - @Test - public void testSearch_NameNotFoundException() throws Exception { - expectGetReadOnlyContext(); - - final SearchControls controls = searchControlsRecursive(); - 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); - - try { - tested.search(nameMock, "(ou=somevalue)", handlerMock); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - verify(dirContextMock).close(); - } - - @Test - public void testSearch_NamingException() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - 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); - - try { - tested.search(nameMock, "(ou=somevalue)", handlerMock); - fail("LimitExceededException expected"); - } - catch (LimitExceededException expected) { - // expected - } - - verify(dirContextMock).close(); - } - - @Test - public void testSearch_CallbackHandler_DirContextProcessor() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - controls.setReturningObjFlag(false); - - SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); - - singleSearchResult(controls, searchResult); - - tested.search(nameMock, "(ou=somevalue)", controls, handlerMock, dirContextProcessorMock); - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(namingEnumerationMock).close(); - verify(handlerMock).handleNameClassPair(searchResult); - verify(dirContextMock).close(); - } - - @Test - public void testSearch_String_CallbackHandler_DirContextProcessor() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - controls.setReturningObjFlag(false); - - SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); - - singleSearchResultWithStringBase(controls, searchResult); - - tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, handlerMock, dirContextProcessorMock); - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(namingEnumerationMock).close(); - verify(handlerMock).handleNameClassPair(searchResult); - verify(dirContextMock).close(); - } - - @Test - public void testSearch_String_AttributesMapper_DirContextProcessor() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsOneLevel(); - controls.setReturningObjFlag(false); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, attributesMapperMock, - dirContextProcessorMock); - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_Name_AttributesMapper_DirContextProcessor() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsOneLevel(); - controls.setReturningObjFlag(false); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResult(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", controls, attributesMapperMock, dirContextProcessorMock); - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_SearchControls_ContextMapper_DirContextProcessor() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock, - dirContextProcessorMock); - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_Name_SearchControls_ContextMapper_DirContextProcessor() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResult(controls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", controls, contextMapperMock, dirContextProcessorMock); - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_AttributesMapper_ReturningAttrs() throws Exception { - expectGetReadOnlyContext(); - - String[] attrs = new String[0]; - SearchControls controls = new SearchControls(); - controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); - controls.setReturningObjFlag(false); - controls.setReturningAttributes(attrs); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResult(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", 1, attrs, attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_AttributesMapper_ReturningAttrs() throws Exception { - expectGetReadOnlyContext(); - - String[] attrs = new String[0]; - SearchControls controls = new SearchControls(); - controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); - controls.setReturningObjFlag(false); - controls.setReturningAttributes(attrs); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attrs, attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void verifyThatDefaultSearchControlParametersAreAutomaticallyAppliedInSearch() throws Exception { - tested.setDefaultSearchScope(SearchControls.ONELEVEL_SCOPE); - tested.setDefaultCountLimit(5000); - tested.setDefaultTimeLimit(500); - - expectGetReadOnlyContext(); - - SearchControls controls = new SearchControls(); - controls.setReturningObjFlag(false); - controls.setCountLimit(5000); - controls.setTimeLimit(500); - controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResult(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_AttributesMapper() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsOneLevel(); - controls.setReturningObjFlag(false); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResult(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", 1, attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_AttributesMapper() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsOneLevel(); - controls.setReturningObjFlag(false); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_AttributesMapper_Default() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - controls.setReturningObjFlag(false); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResult(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_AttributesMapper_Default() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - controls.setReturningObjFlag(false); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_ContextMapper() throws Exception { - expectGetReadOnlyContext(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - singleSearchResult(searchControlsOneLevel(), searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", 1, contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testFindOne() throws Exception { - Class expectedClass = Object.class; - - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(odmMock.filterFor(expectedClass, - new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue")); - - DirContextAdapter expectedObject = new DirContextAdapter(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - singleSearchResult(searchControlsRecursive(), searchResult); - - Object expectedResult = expectedObject; - when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult); - - Object result = tested.findOne(query() - .where("ou").is("somevalue"), expectedClass); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(result).isSameAs(expectedResult); - } - - @Test - public void verifyThatFindOneThrowsEmptyResultIfNoResult() throws Exception { - Class expectedClass = Object.class; - - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - 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) { - assertThat(true).isTrue(); - } - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - verify(odmMock, never()).mapFromLdapDataEntry(any(LdapDataEntry.class), any(Class.class)); - } - - @Test - public void verifyThatFindOneThrowsIncorrectResultSizeDataAccessExceptionWhenMoreResults() throws Exception { - Class expectedClass = Object.class; - - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - 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}); - - Object expectedResult = expectedObject; - when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult); - - try { - tested.findOne(query().where("ou").is("somevalue"), expectedClass); - fail("EmptyResultDataAccessException expected"); - } catch (IncorrectResultSizeDataAccessException expected) { - assertThat(true).isTrue(); - } - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void findWhenSearchControlsReturningAttributesSpecifiedThenOverridesOdmReturningAttributes() throws Exception { - Class expectedClass = Object.class; - - Filter filter = new EqualsFilter("ou", "somevalue"); - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(odmMock.filterFor(any(Class.class), any(Filter.class))).thenReturn(filter); - SearchControls controls = new SearchControls(); - controls.setReturningAttributes(new String[] { "attribute" }); - DirContextAdapter expectedObject = new DirContextAdapter(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - setupSearchResults(controls, searchResult); - Object expectedResult = expectedObject; - when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult); - - List results = tested.find(nameMock, filter, controls, expectedClass); - assertThat(results).hasSize(1); - verify(odmMock, never()).manageClass(any(Class.class)); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void findWhenSearchControlsReturningAttributesUnspecifiedThenOdmReturningAttributesOverrides() throws Exception { - Class expectedClass = Object.class; - String[] expectedReturningAttributes = new String[] { "odmattribute" }; - SearchControls expectedControls = new SearchControls(); - expectedControls.setReturningObjFlag(true); - expectedControls.setReturningAttributes(expectedReturningAttributes); - - Filter filter = new EqualsFilter("ou", "somevalue"); - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(odmMock.filterFor(eq(expectedClass), any(Filter.class))).thenReturn(filter); - when(odmMock.manageClass(eq(expectedClass))).thenReturn(expectedReturningAttributes); - SearchControls controls = new SearchControls(); - DirContextAdapter expectedObject = new DirContextAdapter(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - setupSearchResults(expectedControls, searchResult); - Object expectedResult = expectedObject; - when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult); - - List results = tested.find(nameMock, filter, controls, expectedClass); - assertThat(results).hasSize(1); - verify(odmMock).manageClass(eq(expectedClass)); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void testSearch_ContextMapper_ReturningAttrs() throws Exception { - expectGetReadOnlyContext(); - - String[] attrs = new String[0]; - - SearchControls controls = searchControlsOneLevel(); - controls.setReturningAttributes(attrs); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResult(controls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", 1, attrs, contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_ContextMapper_ReturningAttrs() throws Exception { - expectGetReadOnlyContext(); - - String[] attrs = new String[0]; - - SearchControls controls = searchControlsOneLevel(); - controls.setReturningAttributes(attrs); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attrs, contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_ContextMapper() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsOneLevel(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_ContextMapper_Default() throws Exception { - expectGetReadOnlyContext(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResult(searchControlsRecursive(), searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_ContextMapper_Default() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_SearchControls_ContextMapper() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_SearchControls_ContextMapper_ReturningObjFlagNotSet() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = new SearchControls(); - controls.setSearchScope(SearchControls.SUBTREE_SCOPE); - - SearchControls expectedControls = new SearchControls(); - expectedControls.setSearchScope(SearchControls.SUBTREE_SCOPE); - expectedControls.setReturningObjFlag(true); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResultWithStringBase(expectedControls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_Name_SearchControls_ContextMapper() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResult(controls, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", controls, contextMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_String_SearchControls_AttributesMapper() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsOneLevel(); - controls.setReturningObjFlag(false); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResultWithStringBase(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testSearch_Name_SearchControls_AttributesMapper() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsOneLevel(); - controls.setReturningObjFlag(false); - - BasicAttributes expectedAttributes = new BasicAttributes(); - SearchResult searchResult = new SearchResult("", null, expectedAttributes); - - singleSearchResult(controls, searchResult); - - Object expectedResult = new Object(); - when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); - - List list = tested.search(nameMock, "(ou=somevalue)", controls, attributesMapperMock); - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - - assertThat(list).isNotNull(); - assertThat(list).hasSize(1); - assertThat(list.get(0)).isSameAs(expectedResult); - } - - @Test - public void testModifyAttributes() throws Exception { - expectGetReadWriteContext(); - - ModificationItem[] mods = new ModificationItem[0]; - - tested.modifyAttributes(nameMock, mods); - - verify(dirContextMock).modifyAttributes(nameMock, mods); - verify(dirContextMock).close(); - } - - @Test - public void testModifyAttributes_String() throws Exception { - expectGetReadWriteContext(); - - ModificationItem[] mods = new ModificationItem[0]; - - tested.modifyAttributes(DEFAULT_BASE_STRING, mods); - - verify(dirContextMock).modifyAttributes(DEFAULT_BASE_STRING, mods); - verify(dirContextMock).close(); - } - - @Test - public void testModifyAttributes_NamingException() throws Exception { - expectGetReadWriteContext(); - - ModificationItem[] mods = new ModificationItem[0]; - - javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - doThrow(ne).when(dirContextMock).modifyAttributes(nameMock, mods); - - try { - tested.modifyAttributes(nameMock, mods); - fail("LimitExceededException expected"); - } - catch (LimitExceededException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testBind() throws Exception { - expectGetReadWriteContext(); - - Object expectedObject = new Object(); - BasicAttributes expectedAttributes = new BasicAttributes(); - - tested.bind(nameMock, expectedObject, expectedAttributes); - - verify(dirContextMock).bind(nameMock, expectedObject, expectedAttributes); - verify(dirContextMock).close(); - - } - - @Test - public void testBind_String() throws Exception { - expectGetReadWriteContext(); - - Object expectedObject = new Object(); - BasicAttributes expectedAttributes = new BasicAttributes(); - - tested.bind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); - - verify(dirContextMock).bind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); - verify(dirContextMock).close(); - } - - @Test - public void testBind_NamingException() throws Exception { - expectGetReadWriteContext(); - - Object expectedObject = new Object(); - BasicAttributes expectedAttributes = new BasicAttributes(); - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - doThrow(ne).when(dirContextMock).bind(nameMock, expectedObject, expectedAttributes); - - try { - tested.bind(nameMock, expectedObject, expectedAttributes); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testBindWithContext() throws Exception { - expectGetReadWriteContext(); - - when(dirContextOperationsMock.getDn()).thenReturn(nameMock); - when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); - - tested.bind(dirContextOperationsMock); - - verify(dirContextMock).bind(nameMock, dirContextOperationsMock, null); - verify(dirContextMock).close(); - } - - @Test - public void testCreateWithIdSpecified() throws NamingException { - expectGetReadWriteContext(); - - Object expectedObject = new Object(); - LdapName expectedName = LdapUtils.newLdapName("ou=someOu"); - when(odmMock.getId(expectedObject)).thenReturn(expectedName); - - ArgumentCaptor ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class); - doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture()); - - tested.create(expectedObject); - - verify(odmMock, never()).setId(expectedObject, expectedName); - verify(dirContextMock).bind(expectedName, ctxCaptor.getValue(), null); - verify(dirContextMock).close(); - } - - @Test - public void testCreateWithCalculatedId() throws NamingException { - expectGetReadWriteContext(); - - Object expectedObject = new Object(); - LdapName expectedName = LdapUtils.newLdapName("ou=someOu"); - when(odmMock.getId(expectedObject)).thenReturn(null); - when(odmMock.getCalculatedId(expectedObject)).thenReturn(expectedName); - - ArgumentCaptor ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class); - doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture()); - - tested.create(expectedObject); - - verify(odmMock).setId(expectedObject, expectedName); - verify(dirContextMock).bind(expectedName, ctxCaptor.getValue(), null); - verify(dirContextMock).close(); - } - - @Test - public void testCreateWithNoIdAvailableThrows() throws NamingException { - Object expectedObject = new Object(); - when(odmMock.getId(expectedObject)).thenReturn(null); - when(odmMock.getCalculatedId(expectedObject)).thenReturn(null); - - try { - tested.create(expectedObject); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testUpdateWithIdSpecified() throws NamingException { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); - LdapName expectedName = LdapUtils.newLdapName("ou=someOu"); - - ModificationItem[] expectedModificationItems = new ModificationItem[0]; - DirContextOperations ctxMock = mock(DirContextOperations.class); - when(ctxMock.getDn()).thenReturn(expectedName); - when(ctxMock.isUpdateMode()).thenReturn(true); - when(ctxMock.getModificationItems()).thenReturn(expectedModificationItems); - - Object expectedObject = new Object(); - when(odmMock.getId(expectedObject)).thenReturn(expectedName); - when(odmMock.getCalculatedId(expectedObject)).thenReturn(null); - - when(dirContextMock.lookup(expectedName)).thenReturn(ctxMock); - - tested.update(expectedObject); - - verify(odmMock, never()).setId(expectedObject, expectedName); - verify(odmMock).mapToLdapDataEntry(expectedObject, ctxMock); - verify(dirContextMock).modifyAttributes(expectedName, expectedModificationItems); - - verify(dirContextMock, times(2)).close(); - } - - @Test - public void testUpdateWithIdCalculated() throws NamingException { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); - LdapName expectedName = LdapUtils.newLdapName("ou=someOu"); - - ModificationItem[] expectedModificationItems = new ModificationItem[0]; - DirContextOperations ctxMock = mock(DirContextOperations.class); - when(ctxMock.getDn()).thenReturn(expectedName); - when(ctxMock.isUpdateMode()).thenReturn(true); - when(ctxMock.getModificationItems()).thenReturn(expectedModificationItems); - - Object expectedObject = new Object(); - when(odmMock.getId(expectedObject)).thenReturn(null); - when(odmMock.getCalculatedId(expectedObject)).thenReturn(expectedName); - - when(dirContextMock.lookup(expectedName)).thenReturn(ctxMock); - - tested.update(expectedObject); - - verify(odmMock).setId(expectedObject, expectedName); - verify(odmMock).mapToLdapDataEntry(expectedObject, ctxMock); - verify(dirContextMock).modifyAttributes(expectedName, expectedModificationItems); - - verify(dirContextMock, times(2)).close(); - } - - @Test - public void testUpdateWithIdChanged() throws NamingException { - Object expectedObject = new Object(); - - when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock, dirContextMock); - LdapName expectedOriginalName = LdapUtils.newLdapName("ou=someOu"); - LdapName expectedNewName = LdapUtils.newLdapName("ou=someOtherOu"); - - ArgumentCaptor ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class); - doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture()); - - when(odmMock.getId(expectedObject)).thenReturn(expectedOriginalName); - when(odmMock.getCalculatedId(expectedObject)).thenReturn(expectedNewName); - - tested.update(expectedObject); - - verify(odmMock).setId(expectedObject, expectedNewName); - verify(dirContextMock).unbind(expectedOriginalName); - verify(dirContextMock).bind(expectedNewName, ctxCaptor.getValue(), null); - verify(dirContextMock, times(2)).close(); - } - - @Test - public void testUnbind() throws Exception { - expectGetReadWriteContext(); - - tested.unbind(nameMock); - - verify(dirContextMock).unbind(nameMock); - verify(dirContextMock).close(); - } - - @Test - public void testUnbind_String() throws Exception { - expectGetReadWriteContext(); - - tested.unbind(DEFAULT_BASE_STRING); - - verify(dirContextMock).unbind(DEFAULT_BASE_STRING); - verify(dirContextMock).close(); - } - - @Test - public void testRebindWithContext() throws Exception { - expectGetReadWriteContext(); - - when(dirContextOperationsMock.getDn()).thenReturn(nameMock); - when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); - - tested.rebind(dirContextOperationsMock); - - verify(dirContextMock).rebind(nameMock, dirContextOperationsMock, null); - verify(dirContextMock).close(); - } - - @Test - public void testUnbindRecursive() throws Exception { - expectGetReadWriteContext(); - - when(namingEnumerationMock.hasMore()).thenReturn(true, false, false); - Binding binding = new Binding("cn=Some name", null); - when(namingEnumerationMock.next()).thenReturn(binding); - - LdapName listDn = LdapUtils.newLdapName(DEFAULT_BASE_STRING); - when(dirContextMock.listBindings(listDn)).thenReturn(namingEnumerationMock); - LdapName subListDn = LdapUtils.newLdapName("cn=Some name, o=example.com"); - when(dirContextMock.listBindings(subListDn)).thenReturn(namingEnumerationMock); - - tested.unbind(new CompositeName(DEFAULT_BASE_STRING), true); - - verify(dirContextMock).unbind(subListDn); - verify(dirContextMock).unbind(listDn); - verify(namingEnumerationMock, times(2)).close(); - verify(dirContextMock).close(); - } - - @Test - public void testUnbindRecursive_String() throws Exception { - expectGetReadWriteContext(); - - when(namingEnumerationMock.hasMore()).thenReturn(true, false, false); - Binding binding = new Binding("cn=Some name", null); - when(namingEnumerationMock.next()).thenReturn(binding); - - LdapName listDn = LdapUtils.newLdapName(DEFAULT_BASE_STRING); - when(dirContextMock.listBindings(listDn)).thenReturn(namingEnumerationMock); - LdapName subListDn = LdapUtils.newLdapName("cn=Some name, o=example.com"); - when(dirContextMock.listBindings(subListDn)).thenReturn(namingEnumerationMock); - - tested.unbind(DEFAULT_BASE_STRING, true); - - verify(dirContextMock).unbind(subListDn); - verify(dirContextMock).unbind(listDn); - verify(namingEnumerationMock, times(2)).close(); - verify(dirContextMock).close(); - } - - @Test - public void testRebind() throws Exception { - expectGetReadWriteContext(); - - Object expectedObject = new Object(); - BasicAttributes expectedAttributes = new BasicAttributes(); - - tested.rebind(nameMock, expectedObject, expectedAttributes); - - verify(dirContextMock).rebind(nameMock, expectedObject, expectedAttributes); - verify(dirContextMock).close(); - } - - @Test - public void testRebind_String() throws Exception { - expectGetReadWriteContext(); - - Object expectedObject = new Object(); - BasicAttributes expectedAttributes = new BasicAttributes(); - - tested.rebind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); - - verify(dirContextMock).rebind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); - verify(dirContextMock).close(); - } - - @Test - public void testUnbind_NamingException() throws Exception { - expectGetReadWriteContext(); - - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - doThrow(ne).when(dirContextMock).unbind(nameMock); - - try { - tested.unbind(nameMock); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testExecuteReadOnly() throws Exception { - expectGetReadOnlyContext(); - - Object object = new Object(); - when(contextExecutorMock.executeWithContext(dirContextMock)).thenReturn(object); - - Object result = tested.executeReadOnly(contextExecutorMock); - - verify(dirContextMock).close(); - - assertThat(result).isSameAs(object); - } - - @Test - public void testExecuteReadOnly_NamingException() throws Exception { - expectGetReadOnlyContext(); - - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - when(contextExecutorMock.executeWithContext(dirContextMock)).thenThrow(ne); - - try { - tested.executeReadOnly(contextExecutorMock); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testExecuteReadWrite() throws Exception { - expectGetReadWriteContext(); - - Object object = new Object(); - when(contextExecutorMock.executeWithContext(dirContextMock)).thenReturn(object); - - Object result = tested.executeReadWrite(contextExecutorMock); - - verify(dirContextMock).close(); - - assertThat(result).isSameAs(object); - } - - @Test - public void testExecuteReadWrite_NamingException() throws Exception { - expectGetReadWriteContext(); - - javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); - when(contextExecutorMock.executeWithContext(dirContextMock)).thenThrow(ne); - - try { - tested.executeReadWrite(contextExecutorMock); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testDoSearch_DirContextProcessor() throws Exception { - expectGetReadOnlyContext(); - - SearchResult searchResult = new SearchResult(null, null, null); - - when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); - - when(namingEnumerationMock.hasMore()).thenReturn(true, false); - when(namingEnumerationMock.next()).thenReturn(searchResult); - - tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(handlerMock).handleNameClassPair(searchResult); - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void testDoSearch_DirContextProcessor_NamingException() throws Exception { - expectGetReadOnlyContext(); - - javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ne); - - try { - tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); - fail("LimitExceededException expected"); - } - catch (LimitExceededException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(dirContextMock).close(); - } - - @Test - public void testDoSearch() throws Exception { - expectGetReadOnlyContext(); - - SearchResult searchResult = new SearchResult(null, null, null); - - when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); - - when(namingEnumerationMock.hasMore()).thenReturn(true, false); - when(namingEnumerationMock.next()).thenReturn(searchResult); - - tested.search(searchExecutorMock, handlerMock); - - verify(handlerMock).handleNameClassPair(searchResult); - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void testDoSearch_NamingException() throws Exception { - expectGetReadOnlyContext(); - - javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ne); - - try { - tested.search(searchExecutorMock, handlerMock); - fail("LimitExceededException expected"); - } - catch (LimitExceededException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testDoSearch_NamingException_NamingEnumeration() throws Exception { - expectGetReadOnlyContext(); - - when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); - - javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); - when(namingEnumerationMock.hasMore()).thenThrow(ne); - - try { - tested.search(searchExecutorMock, handlerMock); - fail("LimitExceededException expected"); - } - catch (LimitExceededException expected) { - assertThat(true).isTrue(); - } - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void testDoSearch_NameNotFoundException() throws Exception { - expectGetReadOnlyContext(); - - when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(new javax.naming.NameNotFoundException()); - - try { - tested.search(searchExecutorMock, handlerMock); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testSearch_PartialResult_IgnoreNotSet() throws Exception { - expectGetReadOnlyContext(); - - javax.naming.PartialResultException ex = new javax.naming.PartialResultException(); - when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ex); - - try { - tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); - fail("PartialResultException expected"); - } - catch (PartialResultException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(dirContextMock).close(); - } - - @Test - public void testSearch_PartialResult_IgnoreSet() throws Exception { - tested.setIgnorePartialResultException(true); - - expectGetReadOnlyContext(); - - when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(new javax.naming.PartialResultException()); - - tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); - - verify(dirContextProcessorMock).preProcess(dirContextMock); - verify(dirContextProcessorMock).postProcess(dirContextMock); - verify(dirContextMock).close(); - } - - @Test - public void testLookupContextWithName() { - final DirContextAdapter expectedResult = new DirContextAdapter(); - - final LdapName expectedName = LdapUtils.emptyLdapName(); - LdapTemplate tested = new LdapTemplate() { - public Object lookup(Name dn) { - assertThat(dn).isSameAs(dn); - return expectedResult; - } - }; - - DirContextOperations result = tested.lookupContext(expectedName); - assertThat(result).isSameAs(expectedResult); - - } - - @Test - public void testLookupContextWithString() { - final DirContextAdapter expectedResult = new DirContextAdapter(); - final String expectedName = "cn=John Doe"; - - LdapTemplate tested = new LdapTemplate() { - public Object lookup(String dn) { - assertThat(dn).isSameAs(expectedName); - return expectedResult; - } - }; - - DirContextOperations result = tested.lookupContext(expectedName); - assertThat(result).isSameAs(expectedResult); - } - - @Test - public void testModifyAttributesWithDirContextOperations() throws Exception { - final ModificationItem[] expectedModifications = new ModificationItem[0]; - - final LdapName epectedDn = LdapUtils.emptyLdapName(); - when(dirContextOperationsMock.getDn()).thenReturn(epectedDn); - when(dirContextOperationsMock.isUpdateMode()).thenReturn(true); - when(dirContextOperationsMock.getModificationItems()).thenReturn(expectedModifications); - - LdapTemplate tested = new LdapTemplate() { - public void modifyAttributes(Name dn, ModificationItem[] mods) { - assertThat(dn).isSameAs(epectedDn); - assertThat(mods).isSameAs(expectedModifications); - } - }; - - tested.modifyAttributes(dirContextOperationsMock); - } - - @Test - public void testModifyAttributesWithDirContextOperationsNotInitializedDn() throws Exception { - - when(dirContextOperationsMock.getDn()).thenReturn(LdapUtils.emptyLdapName()); - when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); - - LdapTemplate tested = new LdapTemplate() { - public void modifyAttributes(Name dn, ModificationItem[] mods) { - fail("The call to the base modifyAttributes should not have occured."); - } - }; - - try { - tested.modifyAttributes(dirContextOperationsMock); - fail("IllegalStateException expected"); - } - catch (IllegalStateException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testModifyAttributesWithDirContextOperationsNotInitializedInUpdateMode() throws Exception { - when(dirContextOperationsMock.getDn()).thenReturn(null); - - LdapTemplate tested = new LdapTemplate() { - public void modifyAttributes(Name dn, ModificationItem[] mods) { - fail("The call to the base modifyAttributes should not have occured."); - } - }; - - try { - tested.modifyAttributes(dirContextOperationsMock); - fail("IllegalStateException expected"); - } - catch (IllegalStateException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testSearchForObject() throws Exception { - expectGetReadOnlyContext(); - - Object expectedObject = new Object(); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResult(searchControlsRecursive(), searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - Object result = tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); - - verify(dirContextMock).close(); - - assertThat(result).isNotNull(); - assertThat(result).isSameAs(expectedResult); - } - - @Test - public void testSearchForObjectWithMultipleResults() throws Exception { - expectGetReadOnlyContext(); - - SearchControls controls = searchControlsRecursive(); - - 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(namingEnumerationMock.hasMore()).thenReturn(true, true, false); - when(namingEnumerationMock.next()).thenReturn(searchResult, searchResult); - - Object expectedResult = expectedObject; - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); - - try { - tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); - fail("IncorrectResultSizeDataAccessException expected"); - } - catch (IncorrectResultSizeDataAccessException expected) { - assertThat(true).isTrue(); - } - - verify(namingEnumerationMock).close(); - verify(dirContextMock).close(); - } - - @Test - public void testSearchForObjectWithNoResults() throws Exception { - expectGetReadOnlyContext(); - - noSearchResults(searchControlsRecursive()); - - try { - tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); - fail("EmptyResultDataAccessException expected"); - } - catch (EmptyResultDataAccessException expected) { - assertThat(true).isTrue(); - } - - verify(dirContextMock).close(); - } - - @Test - public void testAuthenticateWithSingleUserFoundShouldBeSuccessful() throws Exception { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - - Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), - LdapUtils.newLdapName("dc=jayway, dc=se")); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResult(searchControlsRecursive(), searchResult); - - when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password")) - .thenReturn(authenticatedContextMock); - entryContextCallbackMock.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); - - verify(authenticatedContextMock).close(); - verify(dirContextMock).close(); - - assertThat(result).isTrue(); - } - - @Test - public void testAuthenticateWithTwoUsersFoundShouldThrowException() throws Exception { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - - Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), - LdapUtils.newLdapName("dc=jayway, dc=se")); - SearchResult searchResult1 = new SearchResult("", expectedObject, new BasicAttributes()); - SearchResult searchResult2 = new SearchResult("", expectedObject, new BasicAttributes()); - - setupSearchResults(searchControlsRecursive(), new SearchResult[] { searchResult1, searchResult2 }); - - try { - tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); - fail("IncorrectResultSizeDataAccessException expected"); - } - catch (IncorrectResultSizeDataAccessException expected) { - // expected - } - - verify(dirContextMock).close(); - } - - @Test - public void testAuthenticateWhenNoUserWasFoundShouldFail() throws Exception { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - - noSearchResults(searchControlsRecursive()); - - boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); - - verify(dirContextMock).close(); - - assertThat(result).isFalse(); - } - - @Test - @SuppressWarnings("unchecked") - public void testAuthenticateQueryPasswordMapperWhenNoUserWasFoundShouldThrowEmptyResult() throws Exception { - - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - - when(dirContextMock.search( - any(Name.class), - any(String.class), - any(SearchControls.class))).thenReturn(namingEnumerationMock); - - when(namingEnumerationMock.hasMore()).thenReturn(false); - - try { - tested.authenticate(query, "", authContextMapperMock); - fail("Expected Exception"); - }catch(EmptyResultDataAccessException success) {} - verify(dirContextMock).close(); - } - - @Test - @SuppressWarnings("unchecked") - public void testAuthenticateQueryPasswordWhenNoUserWasFoundShouldThrowEmptyResult() throws Exception { - - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - - when(dirContextMock.search( - any(Name.class), - any(String.class), - any(SearchControls.class))).thenReturn(namingEnumerationMock); - - when(namingEnumerationMock.hasMore()).thenReturn(false); - - try { - tested.authenticate(query, ""); - fail("Expected Exception"); - }catch(EmptyResultDataAccessException success) {} - verify(dirContextMock).close(); - } - - @Test - public void testAuthenticateWithFailedAuthenticationShouldFail() throws Exception { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - - Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), - LdapUtils.newLdapName("dc=jayway, dc=se")); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResult(searchControlsRecursive(), searchResult); - - when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password")) - .thenThrow(new UncategorizedLdapException("Authentication failed")); - - boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); - - verify(dirContextMock).close(); - - assertThat(result).isFalse(); - } - - @Test - public void testAuthenticateWithErrorInCallbackShouldFail() throws Exception { - when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); - - Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), - LdapUtils.newLdapName("dc=jayway, dc=se")); - SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); - - singleSearchResult(searchControlsRecursive(), searchResult); - - 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"))); - - boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); - - verify(authenticatedContextMock).close(); - verify(dirContextMock).close(); - - assertThat(result).isFalse(); - } - - private void noSearchResults(SearchControls controls) throws Exception { - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); - - when(namingEnumerationMock.hasMore()).thenReturn(false); - } - - private void singleSearchResult(SearchControls controls, SearchResult searchResult) throws Exception { - setupSearchResults(controls, new SearchResult[] { searchResult }); - } - - private void setupSearchResults(SearchControls controls, SearchResult... searchResults) throws Exception { - when(dirContextMock.search( - eq(nameMock), - eq("(ou=somevalue)"), - argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); - - if(searchResults.length == 1) { - when(namingEnumerationMock.hasMore()).thenReturn(true, false); - when(namingEnumerationMock.next()).thenReturn(searchResults[0]); - } else if(searchResults.length ==2) { - when(namingEnumerationMock.hasMore()).thenReturn(true, true, false); - when(namingEnumerationMock.next()).thenReturn(searchResults[0], searchResults[1]); - } 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)"), - argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); - - when(namingEnumerationMock.hasMore()).thenReturn(true, false); - when(namingEnumerationMock.next()).thenReturn(searchResult); - } - - private SearchControls searchControlsRecursive() { - SearchControls controls = new SearchControls(); - controls.setSearchScope(SearchControls.SUBTREE_SCOPE); - controls.setReturningObjFlag(true); - return controls; - } - - private SearchControls searchControlsOneLevel() { - SearchControls controls = new SearchControls(); - controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); - controls.setReturningObjFlag(true); - return controls; - } - - private static class SearchControlsMatcher implements ArgumentMatcher { - private final SearchControls controls; - - public SearchControlsMatcher(SearchControls controls) { - this.controls = controls; - } - - @Override - public boolean matches(SearchControls item) { - if (item instanceof SearchControls) { - SearchControls s1 = item; - - return controls.getSearchScope() == s1.getSearchScope() - && controls.getReturningObjFlag() == s1.getReturningObjFlag() - && controls.getDerefLinkFlag() == s1.getDerefLinkFlag() - && controls.getCountLimit() == s1.getCountLimit() - && controls.getTimeLimit() == s1.getTimeLimit() - && controls.getReturningAttributes() == s1.getReturningAttributes(); - } - else { - throw new IllegalArgumentException(); - } - } - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core; + +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.ArgumentMatcher; +import org.mockito.verification.VerificationMode; + +import org.springframework.LdapDataEntry; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.ldap.LimitExceededException; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.PartialResultException; +import org.springframework.ldap.UncategorizedLdapException; +import org.springframework.ldap.filter.EqualsFilter; +import org.springframework.ldap.filter.Filter; +import org.springframework.ldap.odm.core.ObjectDirectoryMapper; +import org.springframework.ldap.query.LdapQuery; +import org.springframework.ldap.query.LdapQueryBuilder; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.Binding; +import javax.naming.CompositeName; +import javax.naming.Name; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.BasicAttributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.ModificationItem; +import javax.naming.directory.SearchControls; +import javax.naming.directory.SearchResult; +import javax.naming.ldap.LdapContext; +import javax.naming.ldap.LdapName; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; +import static org.springframework.ldap.query.LdapQueryBuilder.query; + +/** + * Unit tests for the LdapTemplate class. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public class LdapTemplateTest { + + private static final String DEFAULT_BASE_STRING = "o=example.com"; + + private ContextSource contextSourceMock; + + private DirContext dirContextMock; + + private AttributesMapper attributesMapperMock; + + private NamingEnumeration namingEnumerationMock; + + private Name nameMock; + + private NameClassPairCallbackHandler handlerMock; + + private ContextMapper contextMapperMock; + + private ContextExecutor contextExecutorMock; + + private SearchExecutor searchExecutorMock; + + private LdapTemplate tested; + + private DirContextProcessor dirContextProcessorMock; + + private DirContextOperations dirContextOperationsMock; + + private DirContext authenticatedContextMock; + + private AuthenticatedLdapEntryContextCallback entryContextCallbackMock; + private ObjectDirectoryMapper odmMock; + + private LdapQuery query; + private AuthenticatedLdapEntryContextMapper authContextMapperMock; + + @Before + public void setUp() throws Exception { + + // Setup ContextSource mock + contextSourceMock = mock(ContextSource.class); + // Setup LdapContext mock + dirContextMock = mock(LdapContext.class); + // Setup NamingEnumeration mock + namingEnumerationMock = mock(NamingEnumeration.class); + // Setup Name mock + nameMock = LdapUtils.emptyLdapName(); + // Setup Handler mock + handlerMock = mock(NameClassPairCallbackHandler.class); + contextMapperMock = mock(ContextMapper.class); + attributesMapperMock = mock(AttributesMapper.class); + contextExecutorMock = mock(ContextExecutor.class); + searchExecutorMock = mock(SearchExecutor.class); + dirContextProcessorMock = mock(DirContextProcessor.class); + dirContextOperationsMock = mock(DirContextOperations.class); + authenticatedContextMock = mock(DirContext.class); + entryContextCallbackMock = mock(AuthenticatedLdapEntryContextCallback.class); + odmMock = mock(ObjectDirectoryMapper.class); + query = LdapQueryBuilder.query().base("ou=spring").filter("ou=user"); + authContextMapperMock = mock(AuthenticatedLdapEntryContextMapper.class); + + tested = new LdapTemplate(contextSourceMock); + tested.setObjectDirectoryMapper(odmMock); + } + + private void expectGetReadWriteContext() { + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); + } + + private void expectGetReadOnlyContext() { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + } + + @Test + public void testSearch_CallbackHandler() throws Exception { + expectGetReadOnlyContext(); + + SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); + + singleSearchResult(searchControlsOneLevel(), searchResult); + + tested.search(nameMock, "(ou=somevalue)", 1, true, handlerMock); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); + } + + @Test + public void testSearch_StringBase_CallbackHandler() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsOneLevel(); + + SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); + + singleSearchResultWithStringBase(controls, searchResult); + + tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, true, handlerMock); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); + } + + @Test + public void testSearch_CallbackHandler_Defaults() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + controls.setReturningObjFlag(false); + + SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); + + singleSearchResult(controls, searchResult); + + tested.search(nameMock, "(ou=somevalue)", handlerMock); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); + } + + @Test + public void testSearch_String_CallbackHandler_Defaults() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + controls.setReturningObjFlag(false); + + SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); + + singleSearchResultWithStringBase(controls, searchResult); + + tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", handlerMock); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); + } + + @Test + public void testSearch_NameNotFoundException() throws Exception { + expectGetReadOnlyContext(); + + final SearchControls controls = searchControlsRecursive(); + 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); + + try { + tested.search(nameMock, "(ou=somevalue)", handlerMock); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + verify(dirContextMock).close(); + } + + @Test + public void testSearch_NamingException() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + 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); + + try { + tested.search(nameMock, "(ou=somevalue)", handlerMock); + fail("LimitExceededException expected"); + } + catch (LimitExceededException expected) { + // expected + } + + verify(dirContextMock).close(); + } + + @Test + public void testSearch_CallbackHandler_DirContextProcessor() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + controls.setReturningObjFlag(false); + + SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); + + singleSearchResult(controls, searchResult); + + tested.search(nameMock, "(ou=somevalue)", controls, handlerMock, dirContextProcessorMock); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); + } + + @Test + public void testSearch_String_CallbackHandler_DirContextProcessor() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + controls.setReturningObjFlag(false); + + SearchResult searchResult = new SearchResult("", new Object(), new BasicAttributes()); + + singleSearchResultWithStringBase(controls, searchResult); + + tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, handlerMock, dirContextProcessorMock); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(handlerMock).handleNameClassPair(searchResult); + verify(dirContextMock).close(); + } + + @Test + public void testSearch_String_AttributesMapper_DirContextProcessor() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsOneLevel(); + controls.setReturningObjFlag(false); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, attributesMapperMock, + dirContextProcessorMock); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_Name_AttributesMapper_DirContextProcessor() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsOneLevel(); + controls.setReturningObjFlag(false); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResult(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", controls, attributesMapperMock, dirContextProcessorMock); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_SearchControls_ContextMapper_DirContextProcessor() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock, + dirContextProcessorMock); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_Name_SearchControls_ContextMapper_DirContextProcessor() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResult(controls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", controls, contextMapperMock, dirContextProcessorMock); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_AttributesMapper_ReturningAttrs() throws Exception { + expectGetReadOnlyContext(); + + String[] attrs = new String[0]; + SearchControls controls = new SearchControls(); + controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); + controls.setReturningObjFlag(false); + controls.setReturningAttributes(attrs); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResult(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", 1, attrs, attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_AttributesMapper_ReturningAttrs() throws Exception { + expectGetReadOnlyContext(); + + String[] attrs = new String[0]; + SearchControls controls = new SearchControls(); + controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); + controls.setReturningObjFlag(false); + controls.setReturningAttributes(attrs); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attrs, attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void verifyThatDefaultSearchControlParametersAreAutomaticallyAppliedInSearch() throws Exception { + tested.setDefaultSearchScope(SearchControls.ONELEVEL_SCOPE); + tested.setDefaultCountLimit(5000); + tested.setDefaultTimeLimit(500); + + expectGetReadOnlyContext(); + + SearchControls controls = new SearchControls(); + controls.setReturningObjFlag(false); + controls.setCountLimit(5000); + controls.setTimeLimit(500); + controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResult(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_AttributesMapper() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsOneLevel(); + controls.setReturningObjFlag(false); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResult(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", 1, attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_AttributesMapper() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsOneLevel(); + controls.setReturningObjFlag(false); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_AttributesMapper_Default() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + controls.setReturningObjFlag(false); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResult(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_AttributesMapper_Default() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + controls.setReturningObjFlag(false); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_ContextMapper() throws Exception { + expectGetReadOnlyContext(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + singleSearchResult(searchControlsOneLevel(), searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", 1, contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testFindOne() throws Exception { + Class expectedClass = Object.class; + + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + when(odmMock.filterFor(expectedClass, + new EqualsFilter("ou", "somevalue"))).thenReturn(new EqualsFilter("ou", "somevalue")); + + DirContextAdapter expectedObject = new DirContextAdapter(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + singleSearchResult(searchControlsRecursive(), searchResult); + + Object expectedResult = expectedObject; + when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult); + + Object result = tested.findOne(query() + .where("ou").is("somevalue"), expectedClass); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(result).isSameAs(expectedResult); + } + + @Test + public void verifyThatFindOneThrowsEmptyResultIfNoResult() throws Exception { + Class expectedClass = Object.class; + + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + 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) { + assertThat(true).isTrue(); + } + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + verify(odmMock, never()).mapFromLdapDataEntry(any(LdapDataEntry.class), any(Class.class)); + } + + @Test + public void verifyThatFindOneThrowsIncorrectResultSizeDataAccessExceptionWhenMoreResults() throws Exception { + Class expectedClass = Object.class; + + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + 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}); + + Object expectedResult = expectedObject; + when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult); + + try { + tested.findOne(query().where("ou").is("somevalue"), expectedClass); + fail("EmptyResultDataAccessException expected"); + } catch (IncorrectResultSizeDataAccessException expected) { + assertThat(true).isTrue(); + } + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void findWhenSearchControlsReturningAttributesSpecifiedThenOverridesOdmReturningAttributes() throws Exception { + Class expectedClass = Object.class; + + Filter filter = new EqualsFilter("ou", "somevalue"); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + when(odmMock.filterFor(any(Class.class), any(Filter.class))).thenReturn(filter); + SearchControls controls = new SearchControls(); + controls.setReturningAttributes(new String[] { "attribute" }); + DirContextAdapter expectedObject = new DirContextAdapter(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + setupSearchResults(controls, searchResult); + Object expectedResult = expectedObject; + when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult); + + List results = tested.find(nameMock, filter, controls, expectedClass); + assertThat(results).hasSize(1); + verify(odmMock, never()).manageClass(any(Class.class)); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void findWhenSearchControlsReturningAttributesUnspecifiedThenOdmReturningAttributesOverrides() throws Exception { + Class expectedClass = Object.class; + String[] expectedReturningAttributes = new String[] { "odmattribute" }; + SearchControls expectedControls = new SearchControls(); + expectedControls.setReturningObjFlag(true); + expectedControls.setReturningAttributes(expectedReturningAttributes); + + Filter filter = new EqualsFilter("ou", "somevalue"); + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + when(odmMock.filterFor(eq(expectedClass), any(Filter.class))).thenReturn(filter); + when(odmMock.manageClass(eq(expectedClass))).thenReturn(expectedReturningAttributes); + SearchControls controls = new SearchControls(); + DirContextAdapter expectedObject = new DirContextAdapter(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + setupSearchResults(expectedControls, searchResult); + Object expectedResult = expectedObject; + when(odmMock.mapFromLdapDataEntry(expectedObject, expectedClass)).thenReturn(expectedResult, expectedResult); + + List results = tested.find(nameMock, filter, controls, expectedClass); + assertThat(results).hasSize(1); + verify(odmMock).manageClass(eq(expectedClass)); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void testSearch_ContextMapper_ReturningAttrs() throws Exception { + expectGetReadOnlyContext(); + + String[] attrs = new String[0]; + + SearchControls controls = searchControlsOneLevel(); + controls.setReturningAttributes(attrs); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResult(controls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", 1, attrs, contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_ContextMapper_ReturningAttrs() throws Exception { + expectGetReadOnlyContext(); + + String[] attrs = new String[0]; + + SearchControls controls = searchControlsOneLevel(); + controls.setReturningAttributes(attrs); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, attrs, contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_ContextMapper() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsOneLevel(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", 1, contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_ContextMapper_Default() throws Exception { + expectGetReadOnlyContext(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResult(searchControlsRecursive(), searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_ContextMapper_Default() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_SearchControls_ContextMapper() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_SearchControls_ContextMapper_ReturningObjFlagNotSet() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = new SearchControls(); + controls.setSearchScope(SearchControls.SUBTREE_SCOPE); + + SearchControls expectedControls = new SearchControls(); + expectedControls.setSearchScope(SearchControls.SUBTREE_SCOPE); + expectedControls.setReturningObjFlag(true); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResultWithStringBase(expectedControls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_Name_SearchControls_ContextMapper() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResult(controls, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", controls, contextMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_String_SearchControls_AttributesMapper() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsOneLevel(); + controls.setReturningObjFlag(false); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResultWithStringBase(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(DEFAULT_BASE_STRING, "(ou=somevalue)", controls, attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testSearch_Name_SearchControls_AttributesMapper() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsOneLevel(); + controls.setReturningObjFlag(false); + + BasicAttributes expectedAttributes = new BasicAttributes(); + SearchResult searchResult = new SearchResult("", null, expectedAttributes); + + singleSearchResult(controls, searchResult); + + Object expectedResult = new Object(); + when(attributesMapperMock.mapFromAttributes(expectedAttributes)).thenReturn(expectedResult); + + List list = tested.search(nameMock, "(ou=somevalue)", controls, attributesMapperMock); + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + + assertThat(list).isNotNull(); + assertThat(list).hasSize(1); + assertThat(list.get(0)).isSameAs(expectedResult); + } + + @Test + public void testModifyAttributes() throws Exception { + expectGetReadWriteContext(); + + ModificationItem[] mods = new ModificationItem[0]; + + tested.modifyAttributes(nameMock, mods); + + verify(dirContextMock).modifyAttributes(nameMock, mods); + verify(dirContextMock).close(); + } + + @Test + public void testModifyAttributes_String() throws Exception { + expectGetReadWriteContext(); + + ModificationItem[] mods = new ModificationItem[0]; + + tested.modifyAttributes(DEFAULT_BASE_STRING, mods); + + verify(dirContextMock).modifyAttributes(DEFAULT_BASE_STRING, mods); + verify(dirContextMock).close(); + } + + @Test + public void testModifyAttributes_NamingException() throws Exception { + expectGetReadWriteContext(); + + ModificationItem[] mods = new ModificationItem[0]; + + javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); + doThrow(ne).when(dirContextMock).modifyAttributes(nameMock, mods); + + try { + tested.modifyAttributes(nameMock, mods); + fail("LimitExceededException expected"); + } + catch (LimitExceededException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testBind() throws Exception { + expectGetReadWriteContext(); + + Object expectedObject = new Object(); + BasicAttributes expectedAttributes = new BasicAttributes(); + + tested.bind(nameMock, expectedObject, expectedAttributes); + + verify(dirContextMock).bind(nameMock, expectedObject, expectedAttributes); + verify(dirContextMock).close(); + + } + + @Test + public void testBind_String() throws Exception { + expectGetReadWriteContext(); + + Object expectedObject = new Object(); + BasicAttributes expectedAttributes = new BasicAttributes(); + + tested.bind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); + + verify(dirContextMock).bind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); + verify(dirContextMock).close(); + } + + @Test + public void testBind_NamingException() throws Exception { + expectGetReadWriteContext(); + + Object expectedObject = new Object(); + BasicAttributes expectedAttributes = new BasicAttributes(); + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + doThrow(ne).when(dirContextMock).bind(nameMock, expectedObject, expectedAttributes); + + try { + tested.bind(nameMock, expectedObject, expectedAttributes); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testBindWithContext() throws Exception { + expectGetReadWriteContext(); + + when(dirContextOperationsMock.getDn()).thenReturn(nameMock); + when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); + + tested.bind(dirContextOperationsMock); + + verify(dirContextMock).bind(nameMock, dirContextOperationsMock, null); + verify(dirContextMock).close(); + } + + @Test + public void testCreateWithIdSpecified() throws NamingException { + expectGetReadWriteContext(); + + Object expectedObject = new Object(); + LdapName expectedName = LdapUtils.newLdapName("ou=someOu"); + when(odmMock.getId(expectedObject)).thenReturn(expectedName); + + ArgumentCaptor ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class); + doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture()); + + tested.create(expectedObject); + + verify(odmMock, never()).setId(expectedObject, expectedName); + verify(dirContextMock).bind(expectedName, ctxCaptor.getValue(), null); + verify(dirContextMock).close(); + } + + @Test + public void testCreateWithCalculatedId() throws NamingException { + expectGetReadWriteContext(); + + Object expectedObject = new Object(); + LdapName expectedName = LdapUtils.newLdapName("ou=someOu"); + when(odmMock.getId(expectedObject)).thenReturn(null); + when(odmMock.getCalculatedId(expectedObject)).thenReturn(expectedName); + + ArgumentCaptor ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class); + doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture()); + + tested.create(expectedObject); + + verify(odmMock).setId(expectedObject, expectedName); + verify(dirContextMock).bind(expectedName, ctxCaptor.getValue(), null); + verify(dirContextMock).close(); + } + + @Test + public void testCreateWithNoIdAvailableThrows() throws NamingException { + Object expectedObject = new Object(); + when(odmMock.getId(expectedObject)).thenReturn(null); + when(odmMock.getCalculatedId(expectedObject)).thenReturn(null); + + try { + tested.create(expectedObject); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testUpdateWithIdSpecified() throws NamingException { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); + LdapName expectedName = LdapUtils.newLdapName("ou=someOu"); + + ModificationItem[] expectedModificationItems = new ModificationItem[0]; + DirContextOperations ctxMock = mock(DirContextOperations.class); + when(ctxMock.getDn()).thenReturn(expectedName); + when(ctxMock.isUpdateMode()).thenReturn(true); + when(ctxMock.getModificationItems()).thenReturn(expectedModificationItems); + + Object expectedObject = new Object(); + when(odmMock.getId(expectedObject)).thenReturn(expectedName); + when(odmMock.getCalculatedId(expectedObject)).thenReturn(null); + + when(dirContextMock.lookup(expectedName)).thenReturn(ctxMock); + + tested.update(expectedObject); + + verify(odmMock, never()).setId(expectedObject, expectedName); + verify(odmMock).mapToLdapDataEntry(expectedObject, ctxMock); + verify(dirContextMock).modifyAttributes(expectedName, expectedModificationItems); + + verify(dirContextMock, times(2)).close(); + } + + @Test + public void testUpdateWithIdCalculated() throws NamingException { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); + LdapName expectedName = LdapUtils.newLdapName("ou=someOu"); + + ModificationItem[] expectedModificationItems = new ModificationItem[0]; + DirContextOperations ctxMock = mock(DirContextOperations.class); + when(ctxMock.getDn()).thenReturn(expectedName); + when(ctxMock.isUpdateMode()).thenReturn(true); + when(ctxMock.getModificationItems()).thenReturn(expectedModificationItems); + + Object expectedObject = new Object(); + when(odmMock.getId(expectedObject)).thenReturn(null); + when(odmMock.getCalculatedId(expectedObject)).thenReturn(expectedName); + + when(dirContextMock.lookup(expectedName)).thenReturn(ctxMock); + + tested.update(expectedObject); + + verify(odmMock).setId(expectedObject, expectedName); + verify(odmMock).mapToLdapDataEntry(expectedObject, ctxMock); + verify(dirContextMock).modifyAttributes(expectedName, expectedModificationItems); + + verify(dirContextMock, times(2)).close(); + } + + @Test + public void testUpdateWithIdChanged() throws NamingException { + Object expectedObject = new Object(); + + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock, dirContextMock); + LdapName expectedOriginalName = LdapUtils.newLdapName("ou=someOu"); + LdapName expectedNewName = LdapUtils.newLdapName("ou=someOtherOu"); + + ArgumentCaptor ctxCaptor = ArgumentCaptor.forClass(DirContextAdapter.class); + doNothing().when(odmMock).mapToLdapDataEntry(eq(expectedObject), ctxCaptor.capture()); + + when(odmMock.getId(expectedObject)).thenReturn(expectedOriginalName); + when(odmMock.getCalculatedId(expectedObject)).thenReturn(expectedNewName); + + tested.update(expectedObject); + + verify(odmMock).setId(expectedObject, expectedNewName); + verify(dirContextMock).unbind(expectedOriginalName); + verify(dirContextMock).bind(expectedNewName, ctxCaptor.getValue(), null); + verify(dirContextMock, times(2)).close(); + } + + @Test + public void testUnbind() throws Exception { + expectGetReadWriteContext(); + + tested.unbind(nameMock); + + verify(dirContextMock).unbind(nameMock); + verify(dirContextMock).close(); + } + + @Test + public void testUnbind_String() throws Exception { + expectGetReadWriteContext(); + + tested.unbind(DEFAULT_BASE_STRING); + + verify(dirContextMock).unbind(DEFAULT_BASE_STRING); + verify(dirContextMock).close(); + } + + @Test + public void testRebindWithContext() throws Exception { + expectGetReadWriteContext(); + + when(dirContextOperationsMock.getDn()).thenReturn(nameMock); + when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); + + tested.rebind(dirContextOperationsMock); + + verify(dirContextMock).rebind(nameMock, dirContextOperationsMock, null); + verify(dirContextMock).close(); + } + + @Test + public void testUnbindRecursive() throws Exception { + expectGetReadWriteContext(); + + when(namingEnumerationMock.hasMore()).thenReturn(true, false, false); + Binding binding = new Binding("cn=Some name", null); + when(namingEnumerationMock.next()).thenReturn(binding); + + LdapName listDn = LdapUtils.newLdapName(DEFAULT_BASE_STRING); + when(dirContextMock.listBindings(listDn)).thenReturn(namingEnumerationMock); + LdapName subListDn = LdapUtils.newLdapName("cn=Some name, o=example.com"); + when(dirContextMock.listBindings(subListDn)).thenReturn(namingEnumerationMock); + + tested.unbind(new CompositeName(DEFAULT_BASE_STRING), true); + + verify(dirContextMock).unbind(subListDn); + verify(dirContextMock).unbind(listDn); + verify(namingEnumerationMock, times(2)).close(); + verify(dirContextMock).close(); + } + + @Test + public void testUnbindRecursive_String() throws Exception { + expectGetReadWriteContext(); + + when(namingEnumerationMock.hasMore()).thenReturn(true, false, false); + Binding binding = new Binding("cn=Some name", null); + when(namingEnumerationMock.next()).thenReturn(binding); + + LdapName listDn = LdapUtils.newLdapName(DEFAULT_BASE_STRING); + when(dirContextMock.listBindings(listDn)).thenReturn(namingEnumerationMock); + LdapName subListDn = LdapUtils.newLdapName("cn=Some name, o=example.com"); + when(dirContextMock.listBindings(subListDn)).thenReturn(namingEnumerationMock); + + tested.unbind(DEFAULT_BASE_STRING, true); + + verify(dirContextMock).unbind(subListDn); + verify(dirContextMock).unbind(listDn); + verify(namingEnumerationMock, times(2)).close(); + verify(dirContextMock).close(); + } + + @Test + public void testRebind() throws Exception { + expectGetReadWriteContext(); + + Object expectedObject = new Object(); + BasicAttributes expectedAttributes = new BasicAttributes(); + + tested.rebind(nameMock, expectedObject, expectedAttributes); + + verify(dirContextMock).rebind(nameMock, expectedObject, expectedAttributes); + verify(dirContextMock).close(); + } + + @Test + public void testRebind_String() throws Exception { + expectGetReadWriteContext(); + + Object expectedObject = new Object(); + BasicAttributes expectedAttributes = new BasicAttributes(); + + tested.rebind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); + + verify(dirContextMock).rebind(DEFAULT_BASE_STRING, expectedObject, expectedAttributes); + verify(dirContextMock).close(); + } + + @Test + public void testUnbind_NamingException() throws Exception { + expectGetReadWriteContext(); + + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + doThrow(ne).when(dirContextMock).unbind(nameMock); + + try { + tested.unbind(nameMock); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testExecuteReadOnly() throws Exception { + expectGetReadOnlyContext(); + + Object object = new Object(); + when(contextExecutorMock.executeWithContext(dirContextMock)).thenReturn(object); + + Object result = tested.executeReadOnly(contextExecutorMock); + + verify(dirContextMock).close(); + + assertThat(result).isSameAs(object); + } + + @Test + public void testExecuteReadOnly_NamingException() throws Exception { + expectGetReadOnlyContext(); + + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + when(contextExecutorMock.executeWithContext(dirContextMock)).thenThrow(ne); + + try { + tested.executeReadOnly(contextExecutorMock); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testExecuteReadWrite() throws Exception { + expectGetReadWriteContext(); + + Object object = new Object(); + when(contextExecutorMock.executeWithContext(dirContextMock)).thenReturn(object); + + Object result = tested.executeReadWrite(contextExecutorMock); + + verify(dirContextMock).close(); + + assertThat(result).isSameAs(object); + } + + @Test + public void testExecuteReadWrite_NamingException() throws Exception { + expectGetReadWriteContext(); + + javax.naming.NameNotFoundException ne = new javax.naming.NameNotFoundException(); + when(contextExecutorMock.executeWithContext(dirContextMock)).thenThrow(ne); + + try { + tested.executeReadWrite(contextExecutorMock); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testDoSearch_DirContextProcessor() throws Exception { + expectGetReadOnlyContext(); + + SearchResult searchResult = new SearchResult(null, null, null); + + when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); + + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(searchResult); + + tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(handlerMock).handleNameClassPair(searchResult); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void testDoSearch_DirContextProcessor_NamingException() throws Exception { + expectGetReadOnlyContext(); + + javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ne); + + try { + tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); + fail("LimitExceededException expected"); + } + catch (LimitExceededException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(dirContextMock).close(); + } + + @Test + public void testDoSearch() throws Exception { + expectGetReadOnlyContext(); + + SearchResult searchResult = new SearchResult(null, null, null); + + when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); + + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(searchResult); + + tested.search(searchExecutorMock, handlerMock); + + verify(handlerMock).handleNameClassPair(searchResult); + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void testDoSearch_NamingException() throws Exception { + expectGetReadOnlyContext(); + + javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ne); + + try { + tested.search(searchExecutorMock, handlerMock); + fail("LimitExceededException expected"); + } + catch (LimitExceededException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testDoSearch_NamingException_NamingEnumeration() throws Exception { + expectGetReadOnlyContext(); + + when(searchExecutorMock.executeSearch(dirContextMock)).thenReturn(namingEnumerationMock); + + javax.naming.LimitExceededException ne = new javax.naming.LimitExceededException(); + when(namingEnumerationMock.hasMore()).thenThrow(ne); + + try { + tested.search(searchExecutorMock, handlerMock); + fail("LimitExceededException expected"); + } + catch (LimitExceededException expected) { + assertThat(true).isTrue(); + } + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void testDoSearch_NameNotFoundException() throws Exception { + expectGetReadOnlyContext(); + + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(new javax.naming.NameNotFoundException()); + + try { + tested.search(searchExecutorMock, handlerMock); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testSearch_PartialResult_IgnoreNotSet() throws Exception { + expectGetReadOnlyContext(); + + javax.naming.PartialResultException ex = new javax.naming.PartialResultException(); + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(ex); + + try { + tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); + fail("PartialResultException expected"); + } + catch (PartialResultException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(dirContextMock).close(); + } + + @Test + public void testSearch_PartialResult_IgnoreSet() throws Exception { + tested.setIgnorePartialResultException(true); + + expectGetReadOnlyContext(); + + when(searchExecutorMock.executeSearch(dirContextMock)).thenThrow(new javax.naming.PartialResultException()); + + tested.search(searchExecutorMock, handlerMock, dirContextProcessorMock); + + verify(dirContextProcessorMock).preProcess(dirContextMock); + verify(dirContextProcessorMock).postProcess(dirContextMock); + verify(dirContextMock).close(); + } + + @Test + public void testLookupContextWithName() { + final DirContextAdapter expectedResult = new DirContextAdapter(); + + final LdapName expectedName = LdapUtils.emptyLdapName(); + LdapTemplate tested = new LdapTemplate() { + public Object lookup(Name dn) { + assertThat(dn).isSameAs(dn); + return expectedResult; + } + }; + + DirContextOperations result = tested.lookupContext(expectedName); + assertThat(result).isSameAs(expectedResult); + + } + + @Test + public void testLookupContextWithString() { + final DirContextAdapter expectedResult = new DirContextAdapter(); + final String expectedName = "cn=John Doe"; + + LdapTemplate tested = new LdapTemplate() { + public Object lookup(String dn) { + assertThat(dn).isSameAs(expectedName); + return expectedResult; + } + }; + + DirContextOperations result = tested.lookupContext(expectedName); + assertThat(result).isSameAs(expectedResult); + } + + @Test + public void testModifyAttributesWithDirContextOperations() throws Exception { + final ModificationItem[] expectedModifications = new ModificationItem[0]; + + final LdapName epectedDn = LdapUtils.emptyLdapName(); + when(dirContextOperationsMock.getDn()).thenReturn(epectedDn); + when(dirContextOperationsMock.isUpdateMode()).thenReturn(true); + when(dirContextOperationsMock.getModificationItems()).thenReturn(expectedModifications); + + LdapTemplate tested = new LdapTemplate() { + public void modifyAttributes(Name dn, ModificationItem[] mods) { + assertThat(dn).isSameAs(epectedDn); + assertThat(mods).isSameAs(expectedModifications); + } + }; + + tested.modifyAttributes(dirContextOperationsMock); + } + + @Test + public void testModifyAttributesWithDirContextOperationsNotInitializedDn() throws Exception { + + when(dirContextOperationsMock.getDn()).thenReturn(LdapUtils.emptyLdapName()); + when(dirContextOperationsMock.isUpdateMode()).thenReturn(false); + + LdapTemplate tested = new LdapTemplate() { + public void modifyAttributes(Name dn, ModificationItem[] mods) { + fail("The call to the base modifyAttributes should not have occured."); + } + }; + + try { + tested.modifyAttributes(dirContextOperationsMock); + fail("IllegalStateException expected"); + } + catch (IllegalStateException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testModifyAttributesWithDirContextOperationsNotInitializedInUpdateMode() throws Exception { + when(dirContextOperationsMock.getDn()).thenReturn(null); + + LdapTemplate tested = new LdapTemplate() { + public void modifyAttributes(Name dn, ModificationItem[] mods) { + fail("The call to the base modifyAttributes should not have occured."); + } + }; + + try { + tested.modifyAttributes(dirContextOperationsMock); + fail("IllegalStateException expected"); + } + catch (IllegalStateException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testSearchForObject() throws Exception { + expectGetReadOnlyContext(); + + Object expectedObject = new Object(); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResult(searchControlsRecursive(), searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + Object result = tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); + + verify(dirContextMock).close(); + + assertThat(result).isNotNull(); + assertThat(result).isSameAs(expectedResult); + } + + @Test + public void testSearchForObjectWithMultipleResults() throws Exception { + expectGetReadOnlyContext(); + + SearchControls controls = searchControlsRecursive(); + + 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(namingEnumerationMock.hasMore()).thenReturn(true, true, false); + when(namingEnumerationMock.next()).thenReturn(searchResult, searchResult); + + Object expectedResult = expectedObject; + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + when(contextMapperMock.mapFromContext(expectedObject)).thenReturn(expectedResult); + + try { + tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); + fail("IncorrectResultSizeDataAccessException expected"); + } + catch (IncorrectResultSizeDataAccessException expected) { + assertThat(true).isTrue(); + } + + verify(namingEnumerationMock).close(); + verify(dirContextMock).close(); + } + + @Test + public void testSearchForObjectWithNoResults() throws Exception { + expectGetReadOnlyContext(); + + noSearchResults(searchControlsRecursive()); + + try { + tested.searchForObject(nameMock, "(ou=somevalue)", contextMapperMock); + fail("EmptyResultDataAccessException expected"); + } + catch (EmptyResultDataAccessException expected) { + assertThat(true).isTrue(); + } + + verify(dirContextMock).close(); + } + + @Test + public void testAuthenticateWithSingleUserFoundShouldBeSuccessful() throws Exception { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + + Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), + LdapUtils.newLdapName("dc=jayway, dc=se")); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResult(searchControlsRecursive(), searchResult); + + when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password")) + .thenReturn(authenticatedContextMock); + entryContextCallbackMock.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); + + verify(authenticatedContextMock).close(); + verify(dirContextMock).close(); + + assertThat(result).isTrue(); + } + + @Test + public void testAuthenticateWithTwoUsersFoundShouldThrowException() throws Exception { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + + Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), + LdapUtils.newLdapName("dc=jayway, dc=se")); + SearchResult searchResult1 = new SearchResult("", expectedObject, new BasicAttributes()); + SearchResult searchResult2 = new SearchResult("", expectedObject, new BasicAttributes()); + + setupSearchResults(searchControlsRecursive(), new SearchResult[] { searchResult1, searchResult2 }); + + try { + tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); + fail("IncorrectResultSizeDataAccessException expected"); + } + catch (IncorrectResultSizeDataAccessException expected) { + // expected + } + + verify(dirContextMock).close(); + } + + @Test + public void testAuthenticateWhenNoUserWasFoundShouldFail() throws Exception { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + + noSearchResults(searchControlsRecursive()); + + boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); + + verify(dirContextMock).close(); + + assertThat(result).isFalse(); + } + + @Test + @SuppressWarnings("unchecked") + public void testAuthenticateQueryPasswordMapperWhenNoUserWasFoundShouldThrowEmptyResult() throws Exception { + + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + + when(dirContextMock.search( + any(Name.class), + any(String.class), + any(SearchControls.class))).thenReturn(namingEnumerationMock); + + when(namingEnumerationMock.hasMore()).thenReturn(false); + + try { + tested.authenticate(query, "", authContextMapperMock); + fail("Expected Exception"); + }catch(EmptyResultDataAccessException success) {} + verify(dirContextMock).close(); + } + + @Test + @SuppressWarnings("unchecked") + public void testAuthenticateQueryPasswordWhenNoUserWasFoundShouldThrowEmptyResult() throws Exception { + + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + + when(dirContextMock.search( + any(Name.class), + any(String.class), + any(SearchControls.class))).thenReturn(namingEnumerationMock); + + when(namingEnumerationMock.hasMore()).thenReturn(false); + + try { + tested.authenticate(query, ""); + fail("Expected Exception"); + }catch(EmptyResultDataAccessException success) {} + verify(dirContextMock).close(); + } + + @Test + public void testAuthenticateWithFailedAuthenticationShouldFail() throws Exception { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + + Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), + LdapUtils.newLdapName("dc=jayway, dc=se")); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResult(searchControlsRecursive(), searchResult); + + when(contextSourceMock.getContext("cn=john doe,dc=jayway,dc=se", "password")) + .thenThrow(new UncategorizedLdapException("Authentication failed")); + + boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); + + verify(dirContextMock).close(); + + assertThat(result).isFalse(); + } + + @Test + public void testAuthenticateWithErrorInCallbackShouldFail() throws Exception { + when(contextSourceMock.getReadOnlyContext()).thenReturn(dirContextMock); + + Object expectedObject = new DirContextAdapter(new BasicAttributes(), LdapUtils.newLdapName("cn=john doe"), + LdapUtils.newLdapName("dc=jayway, dc=se")); + SearchResult searchResult = new SearchResult("", expectedObject, new BasicAttributes()); + + singleSearchResult(searchControlsRecursive(), searchResult); + + 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"))); + + boolean result = tested.authenticate(nameMock, "(ou=somevalue)", "password", entryContextCallbackMock); + + verify(authenticatedContextMock).close(); + verify(dirContextMock).close(); + + assertThat(result).isFalse(); + } + + private void noSearchResults(SearchControls controls) throws Exception { + when(dirContextMock.search( + eq(nameMock), + eq("(ou=somevalue)"), + argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + + when(namingEnumerationMock.hasMore()).thenReturn(false); + } + + private void singleSearchResult(SearchControls controls, SearchResult searchResult) throws Exception { + setupSearchResults(controls, new SearchResult[] { searchResult }); + } + + private void setupSearchResults(SearchControls controls, SearchResult... searchResults) throws Exception { + when(dirContextMock.search( + eq(nameMock), + eq("(ou=somevalue)"), + argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + + if(searchResults.length == 1) { + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(searchResults[0]); + } else if(searchResults.length ==2) { + when(namingEnumerationMock.hasMore()).thenReturn(true, true, false); + when(namingEnumerationMock.next()).thenReturn(searchResults[0], searchResults[1]); + } 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)"), + argThat(new SearchControlsMatcher(controls)))).thenReturn(namingEnumerationMock); + + when(namingEnumerationMock.hasMore()).thenReturn(true, false); + when(namingEnumerationMock.next()).thenReturn(searchResult); + } + + private SearchControls searchControlsRecursive() { + SearchControls controls = new SearchControls(); + controls.setSearchScope(SearchControls.SUBTREE_SCOPE); + controls.setReturningObjFlag(true); + return controls; + } + + private SearchControls searchControlsOneLevel() { + SearchControls controls = new SearchControls(); + controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); + controls.setReturningObjFlag(true); + return controls; + } + + private static class SearchControlsMatcher implements ArgumentMatcher { + private final SearchControls controls; + + public SearchControlsMatcher(SearchControls controls) { + this.controls = controls; + } + + @Override + public boolean matches(SearchControls item) { + if (item instanceof SearchControls) { + SearchControls s1 = item; + + return controls.getSearchScope() == s1.getSearchScope() + && controls.getReturningObjFlag() == s1.getReturningObjFlag() + && controls.getDerefLinkFlag() == s1.getDerefLinkFlag() + && controls.getCountLimit() == s1.getCountLimit() + && controls.getTimeLimit() == s1.getTimeLimit() + && controls.getReturningAttributes() == s1.getReturningAttributes(); + } + else { + throw new IllegalArgumentException(); + } + } + } +} 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 04059097..09045cd6 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 @@ -1,65 +1,65 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.DirContextProcessor; - -import javax.naming.NamingException; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class AggregateDirContextProcessorTest { - - private DirContextProcessor processor1Mock; - - private DirContextProcessor processor2Mock; - - private AggregateDirContextProcessor tested; - - @Before - public void setUp() throws Exception { - // Create processor1 mock - processor1Mock = mock(DirContextProcessor.class); - - // Create processor2 mock - processor2Mock = mock(DirContextProcessor.class); - - tested = new AggregateDirContextProcessor(); - tested.addDirContextProcessor(processor1Mock); - tested.addDirContextProcessor(processor2Mock); - - } - - @Test - public void testPreProcess() throws NamingException { - tested.preProcess(null); - - verify(processor1Mock).preProcess(null); - verify(processor2Mock).preProcess(null); - } - - @Test - public void testPostProcess() throws NamingException { - tested.postProcess(null); - - verify(processor1Mock).postProcess(null); - verify(processor2Mock).postProcess(null); - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.DirContextProcessor; + +import javax.naming.NamingException; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class AggregateDirContextProcessorTest { + + private DirContextProcessor processor1Mock; + + private DirContextProcessor processor2Mock; + + private AggregateDirContextProcessor tested; + + @Before + public void setUp() throws Exception { + // Create processor1 mock + processor1Mock = mock(DirContextProcessor.class); + + // Create processor2 mock + processor2Mock = mock(DirContextProcessor.class); + + tested = new AggregateDirContextProcessor(); + tested.addDirContextProcessor(processor1Mock); + tested.addDirContextProcessor(processor2Mock); + + } + + @Test + public void testPreProcess() throws NamingException { + tested.preProcess(null); + + verify(processor1Mock).preProcess(null); + verify(processor2Mock).preProcess(null); + } + + @Test + public void testPostProcess() throws NamingException { + tested.postProcess(null); + + verify(processor1Mock).postProcess(null); + verify(processor2Mock).postProcess(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 a6f92ee7..7e2c7ab5 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 @@ -1,160 +1,160 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.context.ApplicationContext; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.support.LdapUtils; - -import java.util.HashMap; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -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 - public void setUp() throws Exception { - tested = new BaseLdapPathBeanPostProcessor(); - - ldapPathAwareMock = mock(BaseLdapPathAware.class); - ldapNameAwareMock = mock(BaseLdapNameAware.class); - - applicationContextMock = mock(ApplicationContext.class); - - tested.setApplicationContext(applicationContextMock); - } - - @Test - public void testPostProcessBeforeInitializationWithLdapPathAwareBasePathSet() throws Exception { - String expectedPath = "dc=example, dc=com"; - tested.setBasePath(new DistinguishedName(expectedPath)); - - Object result = tested.postProcessBeforeInitialization(ldapPathAwareMock, "someName"); - - verify(ldapPathAwareMock).setBaseLdapPath(new DistinguishedName(expectedPath)); - - assertThat(result).isSameAs(ldapPathAwareMock); - } - - @Test - public void testPostProcessBeforeInitializationWithLdapNameAwareBasePathSet() throws Exception { - String expectedPath = "dc=example, dc=com"; - tested.setBasePath(expectedPath); - - Object result = tested.postProcessBeforeInitialization(ldapNameAwareMock, "someName"); - - verify(ldapNameAwareMock).setBaseLdapPath(LdapUtils.newLdapName(expectedPath)); - - assertThat(result).isSameAs(ldapNameAwareMock); - } - - - @Test - public void testPostProcessBeforeInitializationWithLdapPathAwareNoBasePathSet() throws Exception { - final LdapContextSource expectedContextSource = new LdapContextSource(); - String expectedPath = "dc=example, dc=com"; - expectedContextSource.setBase(expectedPath); - - tested = new BaseLdapPathBeanPostProcessor() { - BaseLdapPathSource getBaseLdapPathSourceFromApplicationContext() { - return expectedContextSource; - } - }; - - Object result = tested.postProcessBeforeInitialization(ldapPathAwareMock, "someName"); - - verify(ldapPathAwareMock).setBaseLdapPath(new DistinguishedName(expectedPath)); - - assertThat(result).isSameAs(ldapPathAwareMock); - } - - @Test - public void testPostProcessBeforeInitializationWithLdapNameAwareNoBasePathSet() throws Exception { - final LdapContextSource expectedContextSource = new LdapContextSource(); - String expectedPath = "dc=example, dc=com"; - expectedContextSource.setBase(expectedPath); - - tested = new BaseLdapPathBeanPostProcessor() { - BaseLdapPathSource getBaseLdapPathSourceFromApplicationContext() { - return expectedContextSource; - } - }; - - Object result = tested.postProcessBeforeInitialization(ldapNameAwareMock, "someName"); - - verify(ldapNameAwareMock).setBaseLdapPath(LdapUtils.newLdapName(expectedPath)); - - assertThat(result).isSameAs(ldapNameAwareMock); - } - - @Test - public void testGetAbstractContextSourceFromApplicationContext() throws Exception { - when(applicationContextMock.getBeanNamesForType(BaseLdapPathSource.class)) - .thenReturn(new String[]{"contextSource"}); - final LdapContextSource expectedContextSource = new LdapContextSource(); - - HashMap expectedBeans = new HashMap() {{ - put("dummy", expectedContextSource); - }}; - when(applicationContextMock.getBeansOfType(BaseLdapPathSource.class)).thenReturn(expectedBeans); - - BaseLdapPathSource result = tested.getBaseLdapPathSourceFromApplicationContext(); - - assertThat(result).isSameAs(expectedContextSource); - } - - @Test(expected = NoSuchBeanDefinitionException.class) - public void testGetAbstractContextSourceFromApplicationContextNoContextSource() throws Exception { - 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]); - - tested.getBaseLdapPathSourceFromApplicationContext(); - } - - @Test - public void testGetAbstractContextSourceFromApplicationContextTwoContextSourcesAndSpecifiedName() throws Exception { - LdapContextSource expectedContextSource = new LdapContextSource(); - - tested.setBaseLdapPathSourceName("myContextSource"); - when(applicationContextMock.getBean("myContextSource")).thenReturn(expectedContextSource); - - tested.getBaseLdapPathSourceFromApplicationContext(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.ApplicationContext; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.support.LdapUtils; + +import java.util.HashMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +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 + public void setUp() throws Exception { + tested = new BaseLdapPathBeanPostProcessor(); + + ldapPathAwareMock = mock(BaseLdapPathAware.class); + ldapNameAwareMock = mock(BaseLdapNameAware.class); + + applicationContextMock = mock(ApplicationContext.class); + + tested.setApplicationContext(applicationContextMock); + } + + @Test + public void testPostProcessBeforeInitializationWithLdapPathAwareBasePathSet() throws Exception { + String expectedPath = "dc=example, dc=com"; + tested.setBasePath(new DistinguishedName(expectedPath)); + + Object result = tested.postProcessBeforeInitialization(ldapPathAwareMock, "someName"); + + verify(ldapPathAwareMock).setBaseLdapPath(new DistinguishedName(expectedPath)); + + assertThat(result).isSameAs(ldapPathAwareMock); + } + + @Test + public void testPostProcessBeforeInitializationWithLdapNameAwareBasePathSet() throws Exception { + String expectedPath = "dc=example, dc=com"; + tested.setBasePath(expectedPath); + + Object result = tested.postProcessBeforeInitialization(ldapNameAwareMock, "someName"); + + verify(ldapNameAwareMock).setBaseLdapPath(LdapUtils.newLdapName(expectedPath)); + + assertThat(result).isSameAs(ldapNameAwareMock); + } + + + @Test + public void testPostProcessBeforeInitializationWithLdapPathAwareNoBasePathSet() throws Exception { + final LdapContextSource expectedContextSource = new LdapContextSource(); + String expectedPath = "dc=example, dc=com"; + expectedContextSource.setBase(expectedPath); + + tested = new BaseLdapPathBeanPostProcessor() { + BaseLdapPathSource getBaseLdapPathSourceFromApplicationContext() { + return expectedContextSource; + } + }; + + Object result = tested.postProcessBeforeInitialization(ldapPathAwareMock, "someName"); + + verify(ldapPathAwareMock).setBaseLdapPath(new DistinguishedName(expectedPath)); + + assertThat(result).isSameAs(ldapPathAwareMock); + } + + @Test + public void testPostProcessBeforeInitializationWithLdapNameAwareNoBasePathSet() throws Exception { + final LdapContextSource expectedContextSource = new LdapContextSource(); + String expectedPath = "dc=example, dc=com"; + expectedContextSource.setBase(expectedPath); + + tested = new BaseLdapPathBeanPostProcessor() { + BaseLdapPathSource getBaseLdapPathSourceFromApplicationContext() { + return expectedContextSource; + } + }; + + Object result = tested.postProcessBeforeInitialization(ldapNameAwareMock, "someName"); + + verify(ldapNameAwareMock).setBaseLdapPath(LdapUtils.newLdapName(expectedPath)); + + assertThat(result).isSameAs(ldapNameAwareMock); + } + + @Test + public void testGetAbstractContextSourceFromApplicationContext() throws Exception { + when(applicationContextMock.getBeanNamesForType(BaseLdapPathSource.class)) + .thenReturn(new String[]{"contextSource"}); + final LdapContextSource expectedContextSource = new LdapContextSource(); + + HashMap expectedBeans = new HashMap() {{ + put("dummy", expectedContextSource); + }}; + when(applicationContextMock.getBeansOfType(BaseLdapPathSource.class)).thenReturn(expectedBeans); + + BaseLdapPathSource result = tested.getBaseLdapPathSourceFromApplicationContext(); + + assertThat(result).isSameAs(expectedContextSource); + } + + @Test(expected = NoSuchBeanDefinitionException.class) + public void testGetAbstractContextSourceFromApplicationContextNoContextSource() throws Exception { + 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]); + + tested.getBaseLdapPathSourceFromApplicationContext(); + } + + @Test + public void testGetAbstractContextSourceFromApplicationContextTwoContextSourcesAndSpecifiedName() throws Exception { + LdapContextSource expectedContextSource = new LdapContextSource(); + + tested.setBaseLdapPathSourceName("myContextSource"); + when(applicationContextMock.getBean("myContextSource")).thenReturn(expectedContextSource); + + tested.getBaseLdapPathSourceFromApplicationContext(); + } +} 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 8dc7d7c0..5a32bd93 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 @@ -1,44 +1,44 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import org.junit.Before; -import org.junit.Test; - -import javax.naming.directory.SearchResult; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CountNameClassPairResultCallbackHandlerTest { - - private CountNameClassPairCallbackHandler tested; - - @Before - public void setUp() throws Exception { - tested = new CountNameClassPairCallbackHandler(); - } - - @Test - public void testHandleSearchResult() throws Exception { - SearchResult dummy = new SearchResult(null, null, null); - tested.handleNameClassPair(dummy); - tested.handleNameClassPair(dummy); - tested.handleNameClassPair(dummy); - - assertThat(tested.getNoOfRows()).isEqualTo(3); - } - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import org.junit.Before; +import org.junit.Test; + +import javax.naming.directory.SearchResult; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CountNameClassPairResultCallbackHandlerTest { + + private CountNameClassPairCallbackHandler tested; + + @Before + public void setUp() throws Exception { + tested = new CountNameClassPairCallbackHandler(); + } + + @Test + public void testHandleSearchResult() throws Exception { + SearchResult dummy = new SearchResult(null, null, null); + 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 eba94406..6676f051 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 @@ -1,177 +1,177 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.NameAwareAttributes; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.CompositeName; -import javax.naming.Context; -import javax.naming.InvalidNameException; -import javax.naming.Name; -import javax.naming.directory.Attributes; -import javax.naming.directory.BasicAttributes; -import java.util.Hashtable; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class DefaultDirObjectFactoryTest { - - private Context contextMock; - - private static final Name DN = LdapUtils.newLdapName("ou=some unit, dc=jayway, dc=se"); - - private static final String DN_STRING = "ou=some unit, dc=jayway, dc=se"; - - private DefaultDirObjectFactory tested; - - private Context contextMock2; - - @Before - public void setUp() throws Exception { - contextMock = mock(Context.class); - contextMock2 = mock(Context.class); - - tested = new DefaultDirObjectFactory(); - } - - @Test - public void testGetObjectInstance() throws Exception { - Attributes expectedAttributes = new NameAwareAttributes(); - expectedAttributes.put("someAttribute", "someValue"); - - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, DN, null, - new Hashtable(), expectedAttributes); - - verify(contextMock).close(); - - assertThat(adapter.getDn()).isEqualTo(DN); - assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); - } - - @Test - public void testGetObjectInstance_CompositeName() throws Exception { - Attributes expectedAttributes = new NameAwareAttributes(); - expectedAttributes.put("someAttribute", "someValue"); - - CompositeName name = new CompositeName(); - name.add(DN_STRING); - - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, name, null, - new Hashtable(), expectedAttributes); - - verify(contextMock).close(); - - assertThat(adapter.getDn()).isEqualTo(DN); - assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); - } - - @Test - public void testGetObjectInstance_nullObject() throws Exception { - Attributes expectedAttributes = new NameAwareAttributes(); - expectedAttributes.put("someAttribute", "someValue"); - - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(null, DN, null, new Hashtable(), - expectedAttributes); - - assertThat(adapter.getDn()).isEqualTo(DN); - assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); - } - - @Test - public void testGetObjectInstance_ObjectNotContext() throws Exception { - Attributes expectedAttributes = new NameAwareAttributes(); - expectedAttributes.put("someAttribute", "someValue"); - - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(new Object(), DN, null, - new Hashtable(), expectedAttributes); - - assertThat(adapter.getDn()).isEqualTo(DN); - assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); - } - - /** - * Make sure that the base suffix is stripped off from the DN. - * - * @throws Exception - */ - @Test - public void testGetObjectInstance_BaseSet() throws Exception { - Attributes expectedAttributes = new NameAwareAttributes(); - expectedAttributes.put("someAttribute", "someValue"); - - when(contextMock2.getNameInNamespace()).thenReturn("dc=jayway, dc=se"); - - DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, LdapUtils.newLdapName( - "ou=some unit"), contextMock2, new Hashtable(), expectedAttributes); - - verify(contextMock).close(); - - assertThat(adapter.getDn().toString()).isEqualTo("ou=some unit"); - assertThat(adapter.getNameInNamespace()).isEqualTo("ou=some unit,dc=jayway,dc=se"); - assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); - } - - @Test - public void testConstructAdapterFromName() throws InvalidNameException { - CompositeName name = new CompositeName(); - name.add("ldap://localhost:389/ou=People,o=JNDITutorial"); - DefaultDirObjectFactory tested = new DefaultDirObjectFactory(); - DirContextAdapter result = tested.constructAdapterFromName(new BasicAttributes(), name, ""); - - assertThat(result.getDn().toString()).isEqualTo("ou=People,o=JNDITutorial"); - assertThat(result.getReferralUrl().toString()).isEqualTo("ldap://localhost:389"); - } - - @Test - public void testConstructAdapterFromName_Ldaps() throws InvalidNameException { - CompositeName name = new CompositeName(); - name.add("ldaps://localhost:389/ou=People,o=JNDITutorial"); - DefaultDirObjectFactory tested = new DefaultDirObjectFactory(); - DirContextAdapter result = tested.constructAdapterFromName(new BasicAttributes(), name, ""); - - assertThat(result.getDn().toString()).isEqualTo("ou=People,o=JNDITutorial"); - assertThat(result.getReferralUrl().toString()).isEqualTo("ldaps://localhost:389"); - } - - @Test - public void testConstructAdapterFromName_EmptyName() throws InvalidNameException { - CompositeName name = new CompositeName(); - name.add("ldap://localhost:389"); - DefaultDirObjectFactory tested = new DefaultDirObjectFactory(); - DirContextAdapter result = tested.constructAdapterFromName(new BasicAttributes(), name, ""); - - assertThat(result.getDn().toString()).isEqualTo(""); - assertThat(result.getReferralUrl().toString()).isEqualTo("ldap://localhost:389"); - } - - @Test - public void testConstructAdapterFromName_OnlySlash() throws InvalidNameException { - CompositeName name = new CompositeName(); - name.add("ldap://localhost:389/"); - DefaultDirObjectFactory tested = new DefaultDirObjectFactory(); - DirContextAdapter result = tested.constructAdapterFromName(new BasicAttributes(), name, ""); - - assertThat(result.getDn().toString()).isEqualTo(""); - assertThat(result.getReferralUrl().toString()).isEqualTo("ldap://localhost:389"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.NameAwareAttributes; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.CompositeName; +import javax.naming.Context; +import javax.naming.InvalidNameException; +import javax.naming.Name; +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttributes; +import java.util.Hashtable; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class DefaultDirObjectFactoryTest { + + private Context contextMock; + + private static final Name DN = LdapUtils.newLdapName("ou=some unit, dc=jayway, dc=se"); + + private static final String DN_STRING = "ou=some unit, dc=jayway, dc=se"; + + private DefaultDirObjectFactory tested; + + private Context contextMock2; + + @Before + public void setUp() throws Exception { + contextMock = mock(Context.class); + contextMock2 = mock(Context.class); + + tested = new DefaultDirObjectFactory(); + } + + @Test + public void testGetObjectInstance() throws Exception { + Attributes expectedAttributes = new NameAwareAttributes(); + expectedAttributes.put("someAttribute", "someValue"); + + DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, DN, null, + new Hashtable(), expectedAttributes); + + verify(contextMock).close(); + + assertThat(adapter.getDn()).isEqualTo(DN); + assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); + } + + @Test + public void testGetObjectInstance_CompositeName() throws Exception { + Attributes expectedAttributes = new NameAwareAttributes(); + expectedAttributes.put("someAttribute", "someValue"); + + CompositeName name = new CompositeName(); + name.add(DN_STRING); + + DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, name, null, + new Hashtable(), expectedAttributes); + + verify(contextMock).close(); + + assertThat(adapter.getDn()).isEqualTo(DN); + assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); + } + + @Test + public void testGetObjectInstance_nullObject() throws Exception { + Attributes expectedAttributes = new NameAwareAttributes(); + expectedAttributes.put("someAttribute", "someValue"); + + DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(null, DN, null, new Hashtable(), + expectedAttributes); + + assertThat(adapter.getDn()).isEqualTo(DN); + assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); + } + + @Test + public void testGetObjectInstance_ObjectNotContext() throws Exception { + Attributes expectedAttributes = new NameAwareAttributes(); + expectedAttributes.put("someAttribute", "someValue"); + + DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(new Object(), DN, null, + new Hashtable(), expectedAttributes); + + assertThat(adapter.getDn()).isEqualTo(DN); + assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); + } + + /** + * Make sure that the base suffix is stripped off from the DN. + * + * @throws Exception + */ + @Test + public void testGetObjectInstance_BaseSet() throws Exception { + Attributes expectedAttributes = new NameAwareAttributes(); + expectedAttributes.put("someAttribute", "someValue"); + + when(contextMock2.getNameInNamespace()).thenReturn("dc=jayway, dc=se"); + + DirContextAdapter adapter = (DirContextAdapter) tested.getObjectInstance(contextMock, LdapUtils.newLdapName( + "ou=some unit"), contextMock2, new Hashtable(), expectedAttributes); + + verify(contextMock).close(); + + assertThat(adapter.getDn().toString()).isEqualTo("ou=some unit"); + assertThat(adapter.getNameInNamespace()).isEqualTo("ou=some unit,dc=jayway,dc=se"); + assertThat(adapter.getAttributes()).isEqualTo(expectedAttributes); + } + + @Test + public void testConstructAdapterFromName() throws InvalidNameException { + CompositeName name = new CompositeName(); + name.add("ldap://localhost:389/ou=People,o=JNDITutorial"); + DefaultDirObjectFactory tested = new DefaultDirObjectFactory(); + DirContextAdapter result = tested.constructAdapterFromName(new BasicAttributes(), name, ""); + + assertThat(result.getDn().toString()).isEqualTo("ou=People,o=JNDITutorial"); + assertThat(result.getReferralUrl().toString()).isEqualTo("ldap://localhost:389"); + } + + @Test + public void testConstructAdapterFromName_Ldaps() throws InvalidNameException { + CompositeName name = new CompositeName(); + name.add("ldaps://localhost:389/ou=People,o=JNDITutorial"); + DefaultDirObjectFactory tested = new DefaultDirObjectFactory(); + DirContextAdapter result = tested.constructAdapterFromName(new BasicAttributes(), name, ""); + + assertThat(result.getDn().toString()).isEqualTo("ou=People,o=JNDITutorial"); + assertThat(result.getReferralUrl().toString()).isEqualTo("ldaps://localhost:389"); + } + + @Test + public void testConstructAdapterFromName_EmptyName() throws InvalidNameException { + CompositeName name = new CompositeName(); + name.add("ldap://localhost:389"); + DefaultDirObjectFactory tested = new DefaultDirObjectFactory(); + DirContextAdapter result = tested.constructAdapterFromName(new BasicAttributes(), name, ""); + + assertThat(result.getDn().toString()).isEqualTo(""); + assertThat(result.getReferralUrl().toString()).isEqualTo("ldap://localhost:389"); + } + + @Test + public void testConstructAdapterFromName_OnlySlash() throws InvalidNameException { + CompositeName name = new CompositeName(); + name.add("ldap://localhost:389/"); + DefaultDirObjectFactory tested = new DefaultDirObjectFactory(); + DirContextAdapter result = tested.constructAdapterFromName(new BasicAttributes(), name, ""); + + 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/LdapContextSourceTest.java b/core/src/test/java/org/springframework/ldap/core/support/LdapContextSourceTest.java index 4759ee2f..36839c24 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 @@ -1,175 +1,175 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.core.support; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.Context; -import java.util.HashMap; -import java.util.Hashtable; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for the LdapContextSource class. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public class LdapContextSourceTest { - - private LdapContextSource tested; - - @Before - public void setUp() throws Exception { - tested = new LdapContextSource(); - } - - @Test(expected = IllegalArgumentException.class) - public void testAfterPropertiesSet_NoUrl() throws Exception { - tested.afterPropertiesSet(); - } - - // gh-538 - @Test(expected = IllegalArgumentException.class) - public void testAfterPropertiesSet_NullPassword() { - tested.setUrl("ldap://ldap.example.com:389"); - tested.setUserDn("value"); - tested.setPassword(null); - tested.afterPropertiesSet(); - } - - @Test - public void testGetAnonymousEnv() throws Exception { - tested.setBase("dc=some example,dc=se"); - tested.setUrl("ldap://ldap.example.com:389"); - tested.setPooled(true); - tested.setUserDn("cn=Some User"); - tested.setPassword("secret"); - tested.afterPropertiesSet(); - Hashtable env = tested.getAnonymousEnv(); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389/dc=some%20example,dc=se"); - assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isEqualTo("true"); - assertThat(env.get(Context.SECURITY_PRINCIPAL)).isNull(); - 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")); - - // Verify that changing values does not change the environment values. - tested.setBase("dc=other,dc=se"); - tested.setUrl("ldap://ldap2.example.com:389"); - tested.setPooled(false); - - env = tested.getAnonymousEnv(); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389/dc=some%20example,dc=se"); - assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isEqualTo("true"); - 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")); - } - - @Test - public void testGetAnonymousEnvWithNoBaseSet() throws Exception { - tested.setUrl("ldap://ldap.example.com:389"); - tested.afterPropertiesSet(); - Hashtable env = tested.getAnonymousEnv(); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389"); - - // check that base was not added to environment - assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)).isNull(); - } - - @Test - public void testGetAnonymousEnvWithBaseEnvironment() throws Exception { - tested.setUrl("ldap://ldap.example.com:389"); - HashMap map = new HashMap(); - map.put(LdapContextSource.SUN_LDAP_POOLING_FLAG, "true"); - tested.setBaseEnvironmentProperties(map); - tested.afterPropertiesSet(); - Hashtable env = tested.getAnonymousEnv(); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389"); - assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isNull(); - } - - @Test - public void testGetAnonymousEnvWithPoolingInBaseEnvironmentAndPoolingOff() throws Exception { - tested.setUrl("ldap://ldap.example.com:389"); - HashMap map = new HashMap(); - map.put(LdapContextSource.SUN_LDAP_POOLING_FLAG, "true"); - tested.setBaseEnvironmentProperties(map); - tested.setPooled(false); - tested.afterPropertiesSet(); - Hashtable env = tested.getAnonymousEnv(); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389"); - assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isNull(); - } - - @Test - public void testGetAnonymousEnvWithEmptyBaseSet() throws Exception { - tested.setUrl("ldap://ldap.example.com:389"); - tested.setBase(null); - tested.afterPropertiesSet(); - Hashtable env = tested.getAnonymousEnv(); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389"); - - // check that base was not added to environment - assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)).isNull(); - } - - @Test - public void testGetAuthenticatedEnv() throws Exception { - tested.setBase("dc=example,dc=se"); - tested.setUrl("ldap://ldap.example.com:389"); - tested.setPooled(true); - tested.setUserDn("cn=Some User"); - tested.setPassword("secret"); - tested.afterPropertiesSet(); - - Hashtable env = tested.getAuthenticatedEnv("cn=Some User", "secret"); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389/dc=example,dc=se"); - assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isEqualTo("true"); - assertThat(env.get(Context.SECURITY_PRINCIPAL)).isEqualTo("cn=Some User"); - 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")); - } - - @Test - public void testGetAnonymousEnvWhenCacheIsOff() throws Exception { - tested.setBase("dc=example,dc=se"); - tested.setUrl("ldap://ldap.example.com:389"); - tested.setPooled(true); - tested.setUserDn("cn=Some User"); - tested.setPassword("secret"); - tested.setCacheEnvironmentProperties(false); - tested.afterPropertiesSet(); - Hashtable env = tested.getAnonymousEnv(); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389/dc=example,dc=se"); - assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isEqualTo("true"); - assertThat(env.get(Context.SECURITY_PRINCIPAL)).isNull(); - assertThat(env.get(Context.SECURITY_CREDENTIALS)).isNull(); - - tested.setUrl("ldap://ldap2.example.com:389"); - env = tested.getAnonymousEnv(); - assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap2.example.com:389/dc=example,dc=se"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.core.support; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.Context; +import java.util.HashMap; +import java.util.Hashtable; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit tests for the LdapContextSource class. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public class LdapContextSourceTest { + + private LdapContextSource tested; + + @Before + public void setUp() throws Exception { + tested = new LdapContextSource(); + } + + @Test(expected = IllegalArgumentException.class) + public void testAfterPropertiesSet_NoUrl() throws Exception { + tested.afterPropertiesSet(); + } + + // gh-538 + @Test(expected = IllegalArgumentException.class) + public void testAfterPropertiesSet_NullPassword() { + tested.setUrl("ldap://ldap.example.com:389"); + tested.setUserDn("value"); + tested.setPassword(null); + tested.afterPropertiesSet(); + } + + @Test + public void testGetAnonymousEnv() throws Exception { + tested.setBase("dc=some example,dc=se"); + tested.setUrl("ldap://ldap.example.com:389"); + tested.setPooled(true); + tested.setUserDn("cn=Some User"); + tested.setPassword("secret"); + tested.afterPropertiesSet(); + Hashtable env = tested.getAnonymousEnv(); + assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389/dc=some%20example,dc=se"); + assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isEqualTo("true"); + assertThat(env.get(Context.SECURITY_PRINCIPAL)).isNull(); + 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")); + + // Verify that changing values does not change the environment values. + tested.setBase("dc=other,dc=se"); + tested.setUrl("ldap://ldap2.example.com:389"); + tested.setPooled(false); + + env = tested.getAnonymousEnv(); + assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389/dc=some%20example,dc=se"); + assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isEqualTo("true"); + 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")); + } + + @Test + public void testGetAnonymousEnvWithNoBaseSet() throws Exception { + tested.setUrl("ldap://ldap.example.com:389"); + tested.afterPropertiesSet(); + Hashtable env = tested.getAnonymousEnv(); + assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389"); + + // check that base was not added to environment + assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)).isNull(); + } + + @Test + public void testGetAnonymousEnvWithBaseEnvironment() throws Exception { + tested.setUrl("ldap://ldap.example.com:389"); + HashMap map = new HashMap(); + map.put(LdapContextSource.SUN_LDAP_POOLING_FLAG, "true"); + tested.setBaseEnvironmentProperties(map); + tested.afterPropertiesSet(); + Hashtable env = tested.getAnonymousEnv(); + assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389"); + assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isNull(); + } + + @Test + public void testGetAnonymousEnvWithPoolingInBaseEnvironmentAndPoolingOff() throws Exception { + tested.setUrl("ldap://ldap.example.com:389"); + HashMap map = new HashMap(); + map.put(LdapContextSource.SUN_LDAP_POOLING_FLAG, "true"); + tested.setBaseEnvironmentProperties(map); + tested.setPooled(false); + tested.afterPropertiesSet(); + Hashtable env = tested.getAnonymousEnv(); + assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389"); + assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isNull(); + } + + @Test + public void testGetAnonymousEnvWithEmptyBaseSet() throws Exception { + tested.setUrl("ldap://ldap.example.com:389"); + tested.setBase(null); + tested.afterPropertiesSet(); + Hashtable env = tested.getAnonymousEnv(); + assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389"); + + // check that base was not added to environment + assertThat(env.get(DefaultDirObjectFactory.JNDI_ENV_BASE_PATH_KEY)).isNull(); + } + + @Test + public void testGetAuthenticatedEnv() throws Exception { + tested.setBase("dc=example,dc=se"); + tested.setUrl("ldap://ldap.example.com:389"); + tested.setPooled(true); + tested.setUserDn("cn=Some User"); + tested.setPassword("secret"); + tested.afterPropertiesSet(); + + Hashtable env = tested.getAuthenticatedEnv("cn=Some User", "secret"); + assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389/dc=example,dc=se"); + assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isEqualTo("true"); + assertThat(env.get(Context.SECURITY_PRINCIPAL)).isEqualTo("cn=Some User"); + 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")); + } + + @Test + public void testGetAnonymousEnvWhenCacheIsOff() throws Exception { + tested.setBase("dc=example,dc=se"); + tested.setUrl("ldap://ldap.example.com:389"); + tested.setPooled(true); + tested.setUserDn("cn=Some User"); + tested.setPassword("secret"); + tested.setCacheEnvironmentProperties(false); + tested.afterPropertiesSet(); + Hashtable env = tested.getAnonymousEnv(); + assertThat(env.get(Context.PROVIDER_URL)).isEqualTo("ldap://ldap.example.com:389/dc=example,dc=se"); + assertThat(env.get(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isEqualTo("true"); + assertThat(env.get(Context.SECURITY_PRINCIPAL)).isNull(); + assertThat(env.get(Context.SECURITY_CREDENTIALS)).isNull(); + + tested.setUrl("ldap://ldap2.example.com:389"); + 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/SimpleDirContextAuthenticationStrategyTest.java b/core/src/test/java/org/springframework/ldap/core/support/SimpleDirContextAuthenticationStrategyTest.java index 7b747673..455f2c74 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 @@ -1,53 +1,53 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.core.support; - -import org.junit.Before; -import org.junit.Test; - -import javax.naming.Context; -import java.util.Hashtable; - -import static org.assertj.core.api.Assertions.assertThat; - -public class SimpleDirContextAuthenticationStrategyTest { - private SimpleDirContextAuthenticationStrategy tested; - - @Before - public void setUp() throws Exception { - tested = new SimpleDirContextAuthenticationStrategy(); - } - - @Test - public void testSetupEnvironment() { - Hashtable env = new Hashtable(); - tested.setupEnvironment(env, "cn=John Doe", "pw"); - - assertThat(env.get(Context.SECURITY_AUTHENTICATION)).isEqualTo("simple"); - assertThat(env.get(Context.SECURITY_PRINCIPAL)).isEqualTo("cn=John Doe"); - assertThat(env.get(Context.SECURITY_CREDENTIALS)).isEqualTo("pw"); - } - - @Test - public void testProcessContextAfterCreation() { - Hashtable env = new Hashtable(); - tested.processContextAfterCreation(null, "cn=John Doe", "pw"); - - assertThat(env.isEmpty()).isTrue(); - } - - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.core.support; + +import org.junit.Before; +import org.junit.Test; + +import javax.naming.Context; +import java.util.Hashtable; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SimpleDirContextAuthenticationStrategyTest { + private SimpleDirContextAuthenticationStrategy tested; + + @Before + public void setUp() throws Exception { + tested = new SimpleDirContextAuthenticationStrategy(); + } + + @Test + public void testSetupEnvironment() { + Hashtable env = new Hashtable(); + tested.setupEnvironment(env, "cn=John Doe", "pw"); + + assertThat(env.get(Context.SECURITY_AUTHENTICATION)).isEqualTo("simple"); + assertThat(env.get(Context.SECURITY_PRINCIPAL)).isEqualTo("cn=John Doe"); + assertThat(env.get(Context.SECURITY_CREDENTIALS)).isEqualTo("pw"); + } + + @Test + public void testProcessContextAfterCreation() { + Hashtable env = new Hashtable(); + tested.processContextAfterCreation(null, "cn=John Doe", "pw"); + + assertThat(env.isEmpty()).isTrue(); + } + + +} diff --git a/core/src/test/java/org/springframework/ldap/filter/AbstractFilterTest.java b/core/src/test/java/org/springframework/ldap/filter/AbstractFilterTest.java index b4f8b5bc..dfe162c6 100644 --- a/core/src/test/java/org/springframework/ldap/filter/AbstractFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/AbstractFilterTest.java @@ -1,59 +1,59 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Adam Skogman - */ -public class AbstractFilterTest { - - /* - * Test for String encode() - */ - @Test - public void testEncode() { - AbstractFilter af = new AbstractFilter() { - public StringBuffer encode(StringBuffer buff) { - return buff.append("foo"); - } - }; - - assertThat(af.encode()).isEqualTo("foo"); - - } - - /* - * Test for toString() - */ - @Test - public void testToString() { - - AbstractFilter af = new AbstractFilter() { - public StringBuffer encode(StringBuffer buff) { - return buff.append("foo"); - } - }; - - assertThat(af.toString()).isEqualTo("foo"); - - } - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Adam Skogman + */ +public class AbstractFilterTest { + + /* + * Test for String encode() + */ + @Test + public void testEncode() { + AbstractFilter af = new AbstractFilter() { + public StringBuffer encode(StringBuffer buff) { + return buff.append("foo"); + } + }; + + assertThat(af.encode()).isEqualTo("foo"); + + } + + /* + * Test for toString() + */ + @Test + public void testToString() { + + AbstractFilter af = new AbstractFilter() { + public StringBuffer encode(StringBuffer buff) { + return buff.append("foo"); + } + }; + + assertThat(af.toString()).isEqualTo("foo"); + + } + +} 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 c34feb5c..d771a217 100644 --- a/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/AndFilterTest.java @@ -1,71 +1,71 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Adam Skogman - */ -public class AndFilterTest { - - @Test - public void testZero() { - AndFilter aq = new AndFilter(); - - assertThat(aq.encode()).isEqualTo(""); - } - - @Test - public void testOne() { - AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")); - - assertThat(aq.encode()).isEqualTo("(a=b)"); - } - - @Test - public void testTwo() { - 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")); - - assertThat(aq.encode()).isEqualTo("(&(a=b)(c=d)(e=f))"); - } - - @Test - public void testEquals() { - EqualsFilter filter = new EqualsFilter("a", "b"); - AndFilter originalObject = new AndFilter().and(filter); - AndFilter identicalObject = new AndFilter().and(filter); - AndFilter differentObject = new AndFilter().and(new EqualsFilter("b", "b")); - AndFilter subclassObject = new AndFilter() { - }.and(filter); - - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Adam Skogman + */ +public class AndFilterTest { + + @Test + public void testZero() { + AndFilter aq = new AndFilter(); + + assertThat(aq.encode()).isEqualTo(""); + } + + @Test + public void testOne() { + AndFilter aq = new AndFilter().and(new EqualsFilter("a", "b")); + + assertThat(aq.encode()).isEqualTo("(a=b)"); + } + + @Test + public void testTwo() { + 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")); + + assertThat(aq.encode()).isEqualTo("(&(a=b)(c=d)(e=f))"); + } + + @Test + public void testEquals() { + EqualsFilter filter = new EqualsFilter("a", "b"); + AndFilter originalObject = new AndFilter().and(filter); + AndFilter identicalObject = new AndFilter().and(filter); + AndFilter differentObject = new AndFilter().and(new EqualsFilter("b", "b")); + AndFilter subclassObject = new AndFilter() { + }.and(filter); + + 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 57c89204..99c0ff39 100644 --- a/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/EqualsFilterTest.java @@ -1,64 +1,64 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Adam Skogman - */ -public class EqualsFilterTest { - - @Test - public void testEncode() { - - EqualsFilter eqq = new EqualsFilter("foo", "*bar(fie)"); - - StringBuffer buff = new StringBuffer(); - eqq.encode(buff); - - assertThat(buff.toString()).isEqualTo("(foo=\\2abar\\28fie\\29)"); - - } - - @Test - public void testEncodeInt() { - - EqualsFilter eqq = new EqualsFilter("foo", 456); - - StringBuffer buff = new StringBuffer(); - eqq.encode(buff); - - assertThat(buff.toString()).isEqualTo("(foo=456)"); - - } - - @Test - public void testEquals() { - EqualsFilter originalObject = new EqualsFilter("a", "b"); - EqualsFilter identicalObject = new EqualsFilter("a", "b"); - EqualsFilter differentObject = new EqualsFilter("b", "b"); - EqualsFilter subclassObject = new EqualsFilter("a", "b") { - }; - - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Adam Skogman + */ +public class EqualsFilterTest { + + @Test + public void testEncode() { + + EqualsFilter eqq = new EqualsFilter("foo", "*bar(fie)"); + + StringBuffer buff = new StringBuffer(); + eqq.encode(buff); + + assertThat(buff.toString()).isEqualTo("(foo=\\2abar\\28fie\\29)"); + + } + + @Test + public void testEncodeInt() { + + EqualsFilter eqq = new EqualsFilter("foo", 456); + + StringBuffer buff = new StringBuffer(); + eqq.encode(buff); + + assertThat(buff.toString()).isEqualTo("(foo=456)"); + + } + + @Test + public void testEquals() { + EqualsFilter originalObject = new EqualsFilter("a", "b"); + EqualsFilter identicalObject = new EqualsFilter("a", "b"); + EqualsFilter differentObject = new EqualsFilter("b", "b"); + EqualsFilter subclassObject = new EqualsFilter("a", "b") { + }; + + 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 b3db8439..0de2c223 100644 --- a/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/GreaterThanOrEqualsFilterTest.java @@ -1,67 +1,67 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Mattias Hellborg Arthursson - */ -public class GreaterThanOrEqualsFilterTest { - - @Test - public void testEncode() { - - GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", - "*bar(fie)"); - - StringBuffer buff = new StringBuffer(); - eqq.encode(buff); - - assertThat(buff.toString()).isEqualTo("(foo>=\\2abar\\28fie\\29)"); - - } - - @Test - public void testEncodeInt() { - - GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", - 456); - - StringBuffer buff = new StringBuffer(); - eqq.encode(buff); - - assertThat(buff.toString()).isEqualTo("(foo>=456)"); - - } - - @Test - public void testEquals() { - String attribute = "a"; - String value = "b"; - GreaterThanOrEqualsFilter originalObject = new GreaterThanOrEqualsFilter(attribute, value); - GreaterThanOrEqualsFilter identicalObject = new GreaterThanOrEqualsFilter(attribute, value); - GreaterThanOrEqualsFilter differentObject = new GreaterThanOrEqualsFilter(attribute, "c"); - GreaterThanOrEqualsFilter subclassObject = new GreaterThanOrEqualsFilter(attribute, value) { - }; - - new EqualsTester(originalObject, identicalObject, differentObject, subclassObject); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Mattias Hellborg Arthursson + */ +public class GreaterThanOrEqualsFilterTest { + + @Test + public void testEncode() { + + GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", + "*bar(fie)"); + + StringBuffer buff = new StringBuffer(); + eqq.encode(buff); + + assertThat(buff.toString()).isEqualTo("(foo>=\\2abar\\28fie\\29)"); + + } + + @Test + public void testEncodeInt() { + + GreaterThanOrEqualsFilter eqq = new GreaterThanOrEqualsFilter("foo", + 456); + + StringBuffer buff = new StringBuffer(); + eqq.encode(buff); + + assertThat(buff.toString()).isEqualTo("(foo>=456)"); + + } + + @Test + public void testEquals() { + String attribute = "a"; + String value = "b"; + GreaterThanOrEqualsFilter originalObject = new GreaterThanOrEqualsFilter(attribute, value); + GreaterThanOrEqualsFilter identicalObject = new GreaterThanOrEqualsFilter(attribute, value); + GreaterThanOrEqualsFilter differentObject = new GreaterThanOrEqualsFilter(attribute, "c"); + GreaterThanOrEqualsFilter subclassObject = new GreaterThanOrEqualsFilter(attribute, value) { + }; + + 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 d2f67511..dc2b9abb 100644 --- a/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/LessThanOrEqualsFilterTest.java @@ -1,67 +1,67 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Mattias Hellborg Arthursson - */ -public class LessThanOrEqualsFilterTest { - - @Test - public void testEncode() { - - LessThanOrEqualsFilter eqq = new LessThanOrEqualsFilter("foo", - "*bar(fie)"); - - StringBuffer buff = new StringBuffer(); - eqq.encode(buff); - - assertThat(buff.toString()).isEqualTo("(foo<=\\2abar\\28fie\\29)"); - - } - - @Test - public void testEncodeInt() { - - LessThanOrEqualsFilter eqq = new LessThanOrEqualsFilter("foo", 456); - - StringBuffer buff = new StringBuffer(); - eqq.encode(buff); - - assertThat(buff.toString()).isEqualTo("(foo<=456)"); - - } - - @Test - public void testEquals() { - String attribute = "a"; - String value = "b"; - LessThanOrEqualsFilter originalObject = new LessThanOrEqualsFilter(attribute, value); - LessThanOrEqualsFilter identicalObject = new LessThanOrEqualsFilter(attribute, value); - LessThanOrEqualsFilter differentObject = new LessThanOrEqualsFilter(attribute, "c"); - LessThanOrEqualsFilter subclassObject = new LessThanOrEqualsFilter(attribute, value) { - }; - - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Mattias Hellborg Arthursson + */ +public class LessThanOrEqualsFilterTest { + + @Test + public void testEncode() { + + LessThanOrEqualsFilter eqq = new LessThanOrEqualsFilter("foo", + "*bar(fie)"); + + StringBuffer buff = new StringBuffer(); + eqq.encode(buff); + + assertThat(buff.toString()).isEqualTo("(foo<=\\2abar\\28fie\\29)"); + + } + + @Test + public void testEncodeInt() { + + LessThanOrEqualsFilter eqq = new LessThanOrEqualsFilter("foo", 456); + + StringBuffer buff = new StringBuffer(); + eqq.encode(buff); + + assertThat(buff.toString()).isEqualTo("(foo<=456)"); + + } + + @Test + public void testEquals() { + String attribute = "a"; + String value = "b"; + LessThanOrEqualsFilter originalObject = new LessThanOrEqualsFilter(attribute, value); + LessThanOrEqualsFilter identicalObject = new LessThanOrEqualsFilter(attribute, value); + LessThanOrEqualsFilter differentObject = new LessThanOrEqualsFilter(attribute, "c"); + LessThanOrEqualsFilter subclassObject = new LessThanOrEqualsFilter(attribute, value) { + }; + + 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 ff8f65c2..faba35a6 100644 --- a/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/LikeFilterTest.java @@ -1,65 +1,65 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Anders Henja - */ -public class LikeFilterTest { - - @Test - public void testEncodeValue_blank() { - assertThat("").isEqualTo(new LikeFilter("", null).getEncodedValue()); - assertThat(" ").isEqualTo(new LikeFilter("", " ").getEncodedValue()); - } - - @Test - 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()); - } - - @Test - public void testEncodeValue_escape() { - assertThat("*\\28*\\29*").isEqualTo(new LikeFilter("", "*(*)*") - .getEncodedValue()); - assertThat("*\\5c2a*").isEqualTo(new LikeFilter("", "*\\2a*").getEncodedValue()); - } - - @Test - public void testEquals() { - String attribute = "a"; - String value = "b"; - LikeFilter originalObject = new LikeFilter(attribute, value); - LikeFilter identicalObject = new LikeFilter(attribute, value); - LikeFilter differentObject = new LikeFilter(attribute, "c"); - LikeFilter subclassObject = new LikeFilter(attribute, value) { - }; - - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Anders Henja + */ +public class LikeFilterTest { + + @Test + public void testEncodeValue_blank() { + assertThat("").isEqualTo(new LikeFilter("", null).getEncodedValue()); + assertThat(" ").isEqualTo(new LikeFilter("", " ").getEncodedValue()); + } + + @Test + 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()); + } + + @Test + public void testEncodeValue_escape() { + assertThat("*\\28*\\29*").isEqualTo(new LikeFilter("", "*(*)*") + .getEncodedValue()); + assertThat("*\\5c2a*").isEqualTo(new LikeFilter("", "*\\2a*").getEncodedValue()); + } + + @Test + public void testEquals() { + String attribute = "a"; + String value = "b"; + LikeFilter originalObject = new LikeFilter(attribute, value); + LikeFilter identicalObject = new LikeFilter(attribute, value); + LikeFilter differentObject = new LikeFilter(attribute, "c"); + LikeFilter subclassObject = new LikeFilter(attribute, value) { + }; + + 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 79506a72..92f7aea0 100644 --- a/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/NotFilterTest.java @@ -1,51 +1,51 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import com.gargoylesoftware.base.testing.EqualsTester; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for the NotFilter class. - * - * @author Mattias Hellborg Arthursson - */ -public class NotFilterTest { - - @Test - public void testConstructor() { - EqualsFilter filter = new EqualsFilter("a", "b"); - NotFilter notFilter = new NotFilter(filter); - - assertThat(notFilter.encode()).isEqualTo("(!(a=b))"); - } - - @Test - public void testEquals() { - EqualsFilter filter = new EqualsFilter("a", "b"); - NotFilter originalObject = new NotFilter(filter); - NotFilter identicalObject = new NotFilter(filter); - NotFilter differentObject = new NotFilter(new EqualsFilter("a", "a")); - NotFilter subclassObject = new NotFilter(filter) { - }; - - new EqualsTester(originalObject, identicalObject, differentObject, - subclassObject); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import com.gargoylesoftware.base.testing.EqualsTester; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit tests for the NotFilter class. + * + * @author Mattias Hellborg Arthursson + */ +public class NotFilterTest { + + @Test + public void testConstructor() { + EqualsFilter filter = new EqualsFilter("a", "b"); + NotFilter notFilter = new NotFilter(filter); + + assertThat(notFilter.encode()).isEqualTo("(!(a=b))"); + } + + @Test + public void testEquals() { + EqualsFilter filter = new EqualsFilter("a", "b"); + NotFilter originalObject = new NotFilter(filter); + NotFilter identicalObject = new NotFilter(filter); + NotFilter differentObject = new NotFilter(new EqualsFilter("a", "a")); + NotFilter subclassObject = new NotFilter(filter) { + }; + + 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 08b2ec4a..76dfe30f 100644 --- a/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/OrFilterTest.java @@ -1,60 +1,60 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for the OrFilter class. - * - * @author Adam Skogman - */ -public class OrFilterTest { - - @Test - public void testZero() { - OrFilter of = new OrFilter(); - - assertThat(of.encode()).isEqualTo(""); - } - - @Test - public void testOne() { - OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")); - - assertThat(of.encode()).isEqualTo("(a=b)"); - } - - @Test - public void testTwo() { - 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")); - - assertThat(of.encode()).isEqualTo("(|(a=b)(c=d)(e=f))"); - } - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit tests for the OrFilter class. + * + * @author Adam Skogman + */ +public class OrFilterTest { + + @Test + public void testZero() { + OrFilter of = new OrFilter(); + + assertThat(of.encode()).isEqualTo(""); + } + + @Test + public void testOne() { + OrFilter of = new OrFilter().or(new EqualsFilter("a", "b")); + + assertThat(of.encode()).isEqualTo("(a=b)"); + } + + @Test + public void testTwo() { + 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")); + + assertThat(of.encode()).isEqualTo("(|(a=b)(c=d)(e=f))"); + } + +} 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 a38931db..84b1dbf8 100644 --- a/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java +++ b/core/src/test/java/org/springframework/ldap/filter/WhitespaceWildcardsFilterTest.java @@ -1,69 +1,69 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.filter; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit tests for the WhitespaceWildcardsFilter class. - * - * @author Adam Skogman - */ -public class WhitespaceWildcardsFilterTest { - - @Test - 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()); - - } - - @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*"); - } - - @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()); - - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.filter; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit tests for the WhitespaceWildcardsFilter class. + * + * @author Adam Skogman + */ +public class WhitespaceWildcardsFilterTest { + + @Test + 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()); + + } + + @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*"); + } + + @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()); + + } +} 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 31940b45..2360d838 100644 --- a/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/DelegatingLdapContextTest.java @@ -1,252 +1,252 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.pool; - -import org.apache.commons.pool.KeyedObjectPool; -import org.junit.Test; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.ldap.LdapContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -/** - * @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); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - - try { - new DelegatingLdapContext(keyedObjectPoolMock, ldapContextMock, - null); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testHelperMethods() throws Exception { - // Wrap the LdapContext once - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); - - final DirContext delegateDirContext = delegatingLdapContext - .getDelegateDirContext(); - assertThat(delegateDirContext).isEqualTo(ldapContextMock); - - final LdapContext delegateLdapContext = delegatingLdapContext - .getDelegateLdapContext(); - assertThat(delegateLdapContext).isEqualTo(ldapContextMock); - - final LdapContext innerDelegateLdapContext = delegatingLdapContext - .getInnermostDelegateLdapContext(); - assertThat(innerDelegateLdapContext).isEqualTo(ldapContextMock); - - delegatingLdapContext.assertOpen(); - - // Wrap the wrapper - KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); - - final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext( - secondKeyedObjectPoolMock, delegatingLdapContext, - DirContextType.READ_ONLY); - - final LdapContext delegateLdapContext2 = delegatingLdapContext2 - .getDelegateLdapContext(); - assertThat(delegateLdapContext2).isEqualTo(delegatingLdapContext); - - final LdapContext innerDelegateLdapContext2 = delegatingLdapContext2 - .getInnermostDelegateLdapContext(); - assertThat(innerDelegateLdapContext2).isEqualTo(ldapContextMock); - - delegatingLdapContext2.assertOpen(); - - // Close the outer wrapper - delegatingLdapContext2.close(); - - final LdapContext delegateContext2closed = delegatingLdapContext2 - .getDelegateLdapContext(); - assertThat(delegateContext2closed).isNull(); - - final LdapContext innerDelegateContext2closed = delegatingLdapContext2 - .getInnermostDelegateLdapContext(); - assertThat(innerDelegateContext2closed).isNull(); - - try { - delegatingLdapContext2.assertOpen(); - fail("delegatingLdapContext2.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected - } - - // Close the outer wrapper - delegatingLdapContext.close(); - - final LdapContext delegateLdapContextClosed = delegatingLdapContext - .getDelegateLdapContext(); - assertThat(delegateLdapContextClosed).isNull(); - - final LdapContext innerDelegateLdapContextClosed = delegatingLdapContext - .getInnermostDelegateLdapContext(); - assertThat(innerDelegateLdapContextClosed).isNull(); - - try { - delegatingLdapContext.assertOpen(); - fail("delegatingLdapContext.assertOpen() should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected - } - - 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); - 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); - assertThat(delegatingLdapContext.equals(delegatingLdapContext2)).isTrue(); - assertThat(delegatingLdapContext2.equals(delegatingLdapContext)).isTrue(); - assertThat(delegatingLdapContext.equals(ldapContextMock)).isTrue(); - - // Close the context and try again - delegatingLdapContext.close(); - - assertThat(delegatingLdapContext.toString()).isEqualTo("LdapContext is closed"); - assertThat(delegatingLdapContext.hashCode()).isEqualTo(0); // Run it to make - // sure it doesn't - // fail - - assertThat(delegatingLdapContext.equals(delegatingLdapContext)).isTrue(); - assertThat(delegatingLdapContext.equals(new Object())).isFalse(); - - assertThat(delegatingLdapContext.equals(delegatingLdapContext2)).isFalse(); - assertThat(delegatingLdapContext2.equals(delegatingLdapContext)).isFalse(); - assertThat(delegatingLdapContext.equals(ldapContextMock)).isFalse(); - - verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); - } - - @Test - public void testUnsupportedMethods() throws Exception { - 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) { - // Expected - } - try { - delegatingLdapContext.reconnect(null); - fail("DelegatingLdapContext.reconnect Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { - // Expected - } - try { - delegatingLdapContext.setRequestControls(null); - fail("DelegatingLdapContext.setRequestControls Should have thrown an UnsupportedOperationException"); - } catch (UnsupportedOperationException uoe) { - // Expected - } - } - - // nice - @Test - public void testAllMethodsOpened() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); - - delegatingLdapContext.extendedOperation(null); - delegatingLdapContext.getConnectControls(); - delegatingLdapContext.getRequestControls(); - delegatingLdapContext.getResponseControls(); - } - - @Test - public void testAllMethodsClosed() throws Exception { - 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 - } - try { - delegatingLdapContext.getConnectControls(); - fail("DelegatingLdapContext.getConnectControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected - } - try { - delegatingLdapContext.getRequestControls(); - fail("DelegatingLdapContext.getRequestControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected - } - try { - delegatingLdapContext.getResponseControls(); - fail("DelegatingLdapContext.getResponseControls should have thrown a NamingException"); - } catch (NamingException ne) { - // Expected - } - - verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); - } - - @Test - public void testDoubleClose() throws Exception { - final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( - keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); - - delegatingLdapContext.close(); - - // noop close - delegatingLdapContext.close(); - - verify(keyedObjectPoolMock, times(1)).returnObject(DirContextType.READ_ONLY, ldapContextMock); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.pool; + +import org.apache.commons.pool.KeyedObjectPool; +import org.junit.Test; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.ldap.LdapContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +/** + * @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); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + + try { + new DelegatingLdapContext(keyedObjectPoolMock, ldapContextMock, + null); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testHelperMethods() throws Exception { + // Wrap the LdapContext once + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( + keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + + final DirContext delegateDirContext = delegatingLdapContext + .getDelegateDirContext(); + assertThat(delegateDirContext).isEqualTo(ldapContextMock); + + final LdapContext delegateLdapContext = delegatingLdapContext + .getDelegateLdapContext(); + assertThat(delegateLdapContext).isEqualTo(ldapContextMock); + + final LdapContext innerDelegateLdapContext = delegatingLdapContext + .getInnermostDelegateLdapContext(); + assertThat(innerDelegateLdapContext).isEqualTo(ldapContextMock); + + delegatingLdapContext.assertOpen(); + + // Wrap the wrapper + KeyedObjectPool secondKeyedObjectPoolMock = mock(KeyedObjectPool.class); + + final DelegatingLdapContext delegatingLdapContext2 = new DelegatingLdapContext( + secondKeyedObjectPoolMock, delegatingLdapContext, + DirContextType.READ_ONLY); + + final LdapContext delegateLdapContext2 = delegatingLdapContext2 + .getDelegateLdapContext(); + assertThat(delegateLdapContext2).isEqualTo(delegatingLdapContext); + + final LdapContext innerDelegateLdapContext2 = delegatingLdapContext2 + .getInnermostDelegateLdapContext(); + assertThat(innerDelegateLdapContext2).isEqualTo(ldapContextMock); + + delegatingLdapContext2.assertOpen(); + + // Close the outer wrapper + delegatingLdapContext2.close(); + + final LdapContext delegateContext2closed = delegatingLdapContext2 + .getDelegateLdapContext(); + assertThat(delegateContext2closed).isNull(); + + final LdapContext innerDelegateContext2closed = delegatingLdapContext2 + .getInnermostDelegateLdapContext(); + assertThat(innerDelegateContext2closed).isNull(); + + try { + delegatingLdapContext2.assertOpen(); + fail("delegatingLdapContext2.assertOpen() should have thrown a NamingException"); + } catch (NamingException ne) { + // Expected + } + + // Close the outer wrapper + delegatingLdapContext.close(); + + final LdapContext delegateLdapContextClosed = delegatingLdapContext + .getDelegateLdapContext(); + assertThat(delegateLdapContextClosed).isNull(); + + final LdapContext innerDelegateLdapContextClosed = delegatingLdapContext + .getInnermostDelegateLdapContext(); + assertThat(innerDelegateLdapContextClosed).isNull(); + + try { + delegatingLdapContext.assertOpen(); + fail("delegatingLdapContext.assertOpen() should have thrown a NamingException"); + } catch (NamingException ne) { + // Expected + } + + 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); + 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); + assertThat(delegatingLdapContext.equals(delegatingLdapContext2)).isTrue(); + assertThat(delegatingLdapContext2.equals(delegatingLdapContext)).isTrue(); + assertThat(delegatingLdapContext.equals(ldapContextMock)).isTrue(); + + // Close the context and try again + delegatingLdapContext.close(); + + assertThat(delegatingLdapContext.toString()).isEqualTo("LdapContext is closed"); + assertThat(delegatingLdapContext.hashCode()).isEqualTo(0); // Run it to make + // sure it doesn't + // fail + + assertThat(delegatingLdapContext.equals(delegatingLdapContext)).isTrue(); + assertThat(delegatingLdapContext.equals(new Object())).isFalse(); + + assertThat(delegatingLdapContext.equals(delegatingLdapContext2)).isFalse(); + assertThat(delegatingLdapContext2.equals(delegatingLdapContext)).isFalse(); + assertThat(delegatingLdapContext.equals(ldapContextMock)).isFalse(); + + verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); + } + + @Test + public void testUnsupportedMethods() throws Exception { + 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) { + // Expected + } + try { + delegatingLdapContext.reconnect(null); + fail("DelegatingLdapContext.reconnect Should have thrown an UnsupportedOperationException"); + } catch (UnsupportedOperationException uoe) { + // Expected + } + try { + delegatingLdapContext.setRequestControls(null); + fail("DelegatingLdapContext.setRequestControls Should have thrown an UnsupportedOperationException"); + } catch (UnsupportedOperationException uoe) { + // Expected + } + } + + // nice + @Test + public void testAllMethodsOpened() throws Exception { + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( + keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + + delegatingLdapContext.extendedOperation(null); + delegatingLdapContext.getConnectControls(); + delegatingLdapContext.getRequestControls(); + delegatingLdapContext.getResponseControls(); + } + + @Test + public void testAllMethodsClosed() throws Exception { + 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 + } + try { + delegatingLdapContext.getConnectControls(); + fail("DelegatingLdapContext.getConnectControls should have thrown a NamingException"); + } catch (NamingException ne) { + // Expected + } + try { + delegatingLdapContext.getRequestControls(); + fail("DelegatingLdapContext.getRequestControls should have thrown a NamingException"); + } catch (NamingException ne) { + // Expected + } + try { + delegatingLdapContext.getResponseControls(); + fail("DelegatingLdapContext.getResponseControls should have thrown a NamingException"); + } catch (NamingException ne) { + // Expected + } + + verify(keyedObjectPoolMock).returnObject(DirContextType.READ_ONLY, ldapContextMock); + } + + @Test + public void testDoubleClose() throws Exception { + final DelegatingLdapContext delegatingLdapContext = new DelegatingLdapContext( + keyedObjectPoolMock, ldapContextMock, DirContextType.READ_ONLY); + + delegatingLdapContext.close(); + + // noop close + delegatingLdapContext.close(); + + 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 fcc4834d..c088befc 100644 --- a/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java +++ b/core/src/test/java/org/springframework/ldap/pool/MutableDelegatingLdapContextTest.java @@ -1,37 +1,37 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.pool; - -import org.junit.Test; - -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); - - delegatingLdapContext.setRequestControls(null); - - verify(ldapContextMock).setRequestControls(null); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.pool; + +import org.junit.Test; + +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); + + delegatingLdapContext.setRequestControls(null); + + verify(ldapContextMock).setRequestControls(null); + } +} 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 066929f7..e2a811a1 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 @@ -1,173 +1,173 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.pool.validation; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.pool.DirContextType; - -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import javax.naming.directory.SearchControls; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author Eric Dalquist eric.dalquist@doit.wisc.edu - */ -public class DefaultDirContextValidatorTest { - - private NamingEnumeration namingEnumerationMock; - - private DirContext dirContextMock; - - @Before - public void setUp() throws Exception { - namingEnumerationMock = mock(NamingEnumeration.class); - dirContextMock = mock(DirContext.class); - } - - // LDAP-189 - @Test - public void testSearchScopeOneLevelScopeSetInConstructorIsUsed() throws Exception { - DefaultDirContextValidator tested = new DefaultDirContextValidator(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); - } - - // 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); - } - - @Test - public void testProperties() throws Exception { - final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); - - dirContextValidator.setBase("baseName"); - final String baseName = dirContextValidator.getBase(); - assertThat(baseName).isEqualTo("baseName"); - - try { - dirContextValidator.setFilter(null); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - dirContextValidator.setFilter("filter"); - final String filter = dirContextValidator.getFilter(); - assertThat(filter).isEqualTo("filter"); - - try { - dirContextValidator.setSearchControls(null); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - final SearchControls sc = new SearchControls(); - dirContextValidator.setSearchControls(sc); - final SearchControls sc2 = dirContextValidator.getSearchControls(); - assertThat(sc2).isEqualTo(sc); - } - - @Test - public void testValidateDirContextAssertions() throws Exception { - final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); - - try { - dirContextValidator.validateDirContext(DirContextType.READ_ONLY, - null); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - - try { - dirContextValidator.validateDirContext(null, dirContextMock); - fail("IllegalArgumentException expected"); - } catch (IllegalArgumentException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testValidateDirContextHasResult() throws Exception { - final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); - - final String baseName = dirContextValidator.getBase(); - final String filter = dirContextValidator.getFilter(); - final SearchControls searchControls = dirContextValidator - .getSearchControls(); - - when(namingEnumerationMock.hasMore()).thenReturn(true); - when(dirContextMock.search(baseName, filter, searchControls)) - .thenReturn(namingEnumerationMock); - - final boolean valid = dirContextValidator.validateDirContext( - DirContextType.READ_ONLY, dirContextMock); - assertThat(valid).isTrue(); - } - - @Test - public void testValidateDirContextNoResult() throws Exception { - final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); - - final String baseName = dirContextValidator.getBase(); - final String filter = dirContextValidator.getFilter(); - final SearchControls searchControls = dirContextValidator - .getSearchControls(); - - when(namingEnumerationMock.hasMore()).thenReturn(false); - when(dirContextMock.search(baseName, filter, searchControls)) - .thenReturn(namingEnumerationMock); - - final boolean valid = dirContextValidator.validateDirContext( - DirContextType.READ_ONLY, dirContextMock); - - assertThat(valid).isFalse(); - } - - @Test - public void testValidateDirContextException() throws Exception { - final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); - - final String baseName = dirContextValidator.getBase(); - final String filter = dirContextValidator.getFilter(); - 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); - - assertThat(valid).isFalse(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.pool.validation; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.pool.DirContextType; + +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import javax.naming.directory.SearchControls; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * @author Eric Dalquist eric.dalquist@doit.wisc.edu + */ +public class DefaultDirContextValidatorTest { + + private NamingEnumeration namingEnumerationMock; + + private DirContext dirContextMock; + + @Before + public void setUp() throws Exception { + namingEnumerationMock = mock(NamingEnumeration.class); + dirContextMock = mock(DirContext.class); + } + + // LDAP-189 + @Test + public void testSearchScopeOneLevelScopeSetInConstructorIsUsed() throws Exception { + DefaultDirContextValidator tested = new DefaultDirContextValidator(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); + } + + // 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); + } + + @Test + public void testProperties() throws Exception { + final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); + + dirContextValidator.setBase("baseName"); + final String baseName = dirContextValidator.getBase(); + assertThat(baseName).isEqualTo("baseName"); + + try { + dirContextValidator.setFilter(null); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + dirContextValidator.setFilter("filter"); + final String filter = dirContextValidator.getFilter(); + assertThat(filter).isEqualTo("filter"); + + try { + dirContextValidator.setSearchControls(null); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + final SearchControls sc = new SearchControls(); + dirContextValidator.setSearchControls(sc); + final SearchControls sc2 = dirContextValidator.getSearchControls(); + assertThat(sc2).isEqualTo(sc); + } + + @Test + public void testValidateDirContextAssertions() throws Exception { + final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); + + try { + dirContextValidator.validateDirContext(DirContextType.READ_ONLY, + null); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + + try { + dirContextValidator.validateDirContext(null, dirContextMock); + fail("IllegalArgumentException expected"); + } catch (IllegalArgumentException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testValidateDirContextHasResult() throws Exception { + final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); + + final String baseName = dirContextValidator.getBase(); + final String filter = dirContextValidator.getFilter(); + final SearchControls searchControls = dirContextValidator + .getSearchControls(); + + when(namingEnumerationMock.hasMore()).thenReturn(true); + when(dirContextMock.search(baseName, filter, searchControls)) + .thenReturn(namingEnumerationMock); + + final boolean valid = dirContextValidator.validateDirContext( + DirContextType.READ_ONLY, dirContextMock); + assertThat(valid).isTrue(); + } + + @Test + public void testValidateDirContextNoResult() throws Exception { + final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); + + final String baseName = dirContextValidator.getBase(); + final String filter = dirContextValidator.getFilter(); + final SearchControls searchControls = dirContextValidator + .getSearchControls(); + + when(namingEnumerationMock.hasMore()).thenReturn(false); + when(dirContextMock.search(baseName, filter, searchControls)) + .thenReturn(namingEnumerationMock); + + final boolean valid = dirContextValidator.validateDirContext( + DirContextType.READ_ONLY, dirContextMock); + + assertThat(valid).isFalse(); + } + + @Test + public void testValidateDirContextException() throws Exception { + final DefaultDirContextValidator dirContextValidator = new DefaultDirContextValidator(); + + final String baseName = dirContextValidator.getBase(); + final String filter = dirContextValidator.getFilter(); + 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); + + assertThat(valid).isFalse(); + } +} 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 190f415b..aa67262a 100644 --- a/core/src/test/java/org/springframework/ldap/support/LdapEncoderTest.java +++ b/core/src/test/java/org/springframework/ldap/support/LdapEncoderTest.java @@ -1,91 +1,91 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.support; - -import org.junit.Test; -import org.springframework.ldap.BadLdapGrammarException; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Unit test for the LdapEncode class. - * - * @author Adam Skogman - */ -public class LdapEncoderTest { - - @Test - public void testFilterEncode() { - String correct = "\\2aa\\2ab\\28c\\29d\\2a\\5c"; - assertThat(LdapEncoder.filterEncode("*a*b(c)d*\\")).isEqualTo(correct); - - } - - @Test - public void testNameEncode() { - - String res = LdapEncoder.nameEncode("# foo ,+\"\\<>; "); - - assertThat(res).isEqualTo("\\# foo \\,\\+\\\"\\\\\\<\\>\\;\\ "); - } - - @Test - public void testNameDecode() { - - String res = LdapEncoder - .nameDecode("\\# foo \\,\\+\\\"\\\\\\<\\>\\;\\ "); - - assertThat(res).isEqualTo("# foo ,+\"\\<>; "); - } - - @Test(expected = BadLdapGrammarException.class) - public void testNameDecode_slashlast() { - LdapEncoder.nameDecode("\\"); - } - - // gh-413 - @Test - public void printBase64WhenReallyLongThenNewLineStartsWithSpace() throws Exception { - String toBase64Encode = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - String expected = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\n NTY3ODk="; - - String actual = LdapEncoder.printBase64Binary(toBase64Encode.getBytes("UTF-8")); - - assertThat(actual).isEqualTo(expected); - } - - // gh-413 - @Test - public void parseBase64BinaryWhenReallyLongThenRemovesNewlineAndSpace() { - String toParse = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\n NTY3ODk="; - String expected = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - - String actual = new String(LdapEncoder.parseBase64Binary(toParse)); - - assertThat(actual).isEqualTo(expected); - } - - @Test - public void parseBase64BinaryWhenReallyLongThenRemovesNewlineWithNoSpaceForPassivity() { - String toParse = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNTY3ODk="; - String expected = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; - - String actual = new String(LdapEncoder.parseBase64Binary(toParse)); - - assertThat(actual).isEqualTo(expected); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.support; + +import org.junit.Test; +import org.springframework.ldap.BadLdapGrammarException; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit test for the LdapEncode class. + * + * @author Adam Skogman + */ +public class LdapEncoderTest { + + @Test + public void testFilterEncode() { + String correct = "\\2aa\\2ab\\28c\\29d\\2a\\5c"; + assertThat(LdapEncoder.filterEncode("*a*b(c)d*\\")).isEqualTo(correct); + + } + + @Test + public void testNameEncode() { + + String res = LdapEncoder.nameEncode("# foo ,+\"\\<>; "); + + assertThat(res).isEqualTo("\\# foo \\,\\+\\\"\\\\\\<\\>\\;\\ "); + } + + @Test + public void testNameDecode() { + + String res = LdapEncoder + .nameDecode("\\# foo \\,\\+\\\"\\\\\\<\\>\\;\\ "); + + assertThat(res).isEqualTo("# foo ,+\"\\<>; "); + } + + @Test(expected = BadLdapGrammarException.class) + public void testNameDecode_slashlast() { + LdapEncoder.nameDecode("\\"); + } + + // gh-413 + @Test + public void printBase64WhenReallyLongThenNewLineStartsWithSpace() throws Exception { + String toBase64Encode = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + String expected = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\n NTY3ODk="; + + String actual = LdapEncoder.printBase64Binary(toBase64Encode.getBytes("UTF-8")); + + assertThat(actual).isEqualTo(expected); + } + + // gh-413 + @Test + public void parseBase64BinaryWhenReallyLongThenRemovesNewlineAndSpace() { + String toParse = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\n NTY3ODk="; + String expected = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + + String actual = new String(LdapEncoder.parseBase64Binary(toParse)); + + assertThat(actual).isEqualTo(expected); + } + + @Test + public void parseBase64BinaryWhenReallyLongThenRemovesNewlineWithNoSpaceForPassivity() { + String toParse = "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0\nNTY3ODk="; + String expected = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + + String actual = new String(LdapEncoder.parseBase64Binary(toParse)); + + assertThat(actual).isEqualTo(expected); + } +} 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 c01282da..9d6ccd80 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 @@ -1,80 +1,80 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.directory.BasicAttributes; -import javax.naming.ldap.LdapName; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class BindOperationExecutorTest { - private LdapOperations ldapOperationsMock; - - @Before - public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class); - } - - @Test - public void testPerformOperation() { - LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); - Object expectedObject = new Object(); - BasicAttributes expectedAttributes = new BasicAttributes(); - BindOperationExecutor tested = new BindOperationExecutor( - ldapOperationsMock, expectedDn, expectedObject, - expectedAttributes); - - // perform teste - tested.performOperation(); - - verify(ldapOperationsMock).bind(expectedDn, expectedObject, expectedAttributes); - } - - @Test - public void testCommit() { - LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); - Object expectedObject = new Object(); - BasicAttributes expectedAttributes = new BasicAttributes(); - BindOperationExecutor tested = new BindOperationExecutor( - ldapOperationsMock, expectedDn, expectedObject, - expectedAttributes); - - verifyNoMoreInteractions(ldapOperationsMock); - - // perform teste - tested.commit(); - } - - @Test - public void testRollback() { - LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); - BindOperationExecutor tested = new BindOperationExecutor( - ldapOperationsMock, expectedDn, null, null); - - // perform teste - tested.rollback(); - - verify(ldapOperationsMock).unbind(expectedDn); - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.directory.BasicAttributes; +import javax.naming.ldap.LdapName; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +public class BindOperationExecutorTest { + private LdapOperations ldapOperationsMock; + + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + } + + @Test + public void testPerformOperation() { + LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); + Object expectedObject = new Object(); + BasicAttributes expectedAttributes = new BasicAttributes(); + BindOperationExecutor tested = new BindOperationExecutor( + ldapOperationsMock, expectedDn, expectedObject, + expectedAttributes); + + // perform teste + tested.performOperation(); + + verify(ldapOperationsMock).bind(expectedDn, expectedObject, expectedAttributes); + } + + @Test + public void testCommit() { + LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); + Object expectedObject = new Object(); + BasicAttributes expectedAttributes = new BasicAttributes(); + BindOperationExecutor tested = new BindOperationExecutor( + ldapOperationsMock, expectedDn, expectedObject, + expectedAttributes); + + verifyNoMoreInteractions(ldapOperationsMock); + + // perform teste + tested.commit(); + } + + @Test + public void testRollback() { + LdapName expectedDn = LdapUtils.newLdapName("cn=john doe"); + BindOperationExecutor tested = new BindOperationExecutor( + ldapOperationsMock, expectedDn, null, null); + + // perform teste + tested.rollback(); + + verify(ldapOperationsMock).unbind(expectedDn); + } + +} 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 c2232015..d0bf9385 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 @@ -1,91 +1,91 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; - -import javax.naming.directory.BasicAttributes; -import javax.naming.ldap.LdapName; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; - -public class BindOperationRecorderTest { - private LdapOperations ldapOperationsMock; - - @Before - public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class); - - } - - @Test - public void testRecordOperation_Name() { - 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 }); - - 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()); - } - - @Test - public void testPerformOperation_String() { - 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 }); - - assertThat(operation instanceof BindOperationExecutor).isTrue(); - BindOperationExecutor rollbackOperation = (BindOperationExecutor) operation; - assertThat(rollbackOperation.getDn().toString()).isEqualTo(expectedDn); - assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); - } - - @Test(expected = IllegalArgumentException.class) - public void testPerformOperation_Invalid() { - BindOperationRecorder tested = new BindOperationRecorder( - ldapOperationsMock); - Object expectedDn = new Object(); - - // Perform test. - tested.recordOperation(new Object[]{expectedDn}); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; + +import javax.naming.directory.BasicAttributes; +import javax.naming.ldap.LdapName; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; + +public class BindOperationRecorderTest { + private LdapOperations ldapOperationsMock; + + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + + } + + @Test + public void testRecordOperation_Name() { + 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 }); + + 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()); + } + + @Test + public void testPerformOperation_String() { + 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 }); + + assertThat(operation instanceof BindOperationExecutor).isTrue(); + BindOperationExecutor rollbackOperation = (BindOperationExecutor) operation; + assertThat(rollbackOperation.getDn().toString()).isEqualTo(expectedDn); + assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); + } + + @Test(expected = IllegalArgumentException.class) + public void testPerformOperation_Invalid() { + BindOperationRecorder tested = new BindOperationRecorder( + ldapOperationsMock); + Object expectedDn = new Object(); + + // Perform test. + 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 c96ed8c0..b96f5617 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 @@ -1,100 +1,100 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; - -import javax.naming.directory.DirContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class LdapCompensatingTransactionOperationFactoryTest { - private LdapOperations ldapOperationsMock; - - private TempEntryRenamingStrategy renamingStrategyMock; - - private DirContext dirContextMock; - - private LdapCompensatingTransactionOperationFactory tested; - - @Before - public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class); - renamingStrategyMock = mock(TempEntryRenamingStrategy.class); - dirContextMock = mock(DirContext.class); - - tested = new LdapCompensatingTransactionOperationFactory( - renamingStrategyMock) { - - LdapOperations createLdapOperationsInstance(DirContext ctx) { - assertThat(ctx).isEqualTo(dirContextMock); - return ldapOperationsMock; - } - }; - } - - @Test - public void testGetRecordingOperation_Bind() throws Exception { - - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "bind"); - assertThat(result instanceof BindOperationRecorder).isTrue(); - BindOperationRecorder bindOperationRecorder = (BindOperationRecorder) result; - assertThat(bindOperationRecorder.getLdapOperations()).isSameAs(ldapOperationsMock); - } - - @Test - public void testGetRecordingOperation_Rebind() throws Exception { - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "rebind"); - assertThat(result instanceof RebindOperationRecorder).isTrue(); - RebindOperationRecorder rebindOperationRecorder = (RebindOperationRecorder) result; - assertThat(rebindOperationRecorder.getLdapOperations()).isSameAs(ldapOperationsMock); - assertThat(rebindOperationRecorder.getRenamingStrategy()).isSameAs(renamingStrategyMock); - } - - @Test - public void testGetRecordingOperation_Rename() throws Exception { - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "rename"); - assertThat(result instanceof RenameOperationRecorder).isTrue(); - RenameOperationRecorder recordingOperation = (RenameOperationRecorder) result; - assertThat(recordingOperation.getLdapOperations()).isSameAs(ldapOperationsMock); - } - - @Test - public void testGetRecordingOperation_ModifyAttributes() throws Exception { - CompensatingTransactionOperationRecorder result = tested - .createRecordingOperation(dirContextMock, "modifyAttributes"); - assertThat(result instanceof ModifyAttributesOperationRecorder).isTrue(); - ModifyAttributesOperationRecorder recordingOperation = (ModifyAttributesOperationRecorder) result; - assertThat(recordingOperation.getLdapOperations()).isSameAs(ldapOperationsMock); - } - - @Test - public void testGetRecordingOperation_Unbind() throws Exception { - 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); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; + +import javax.naming.directory.DirContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +public class LdapCompensatingTransactionOperationFactoryTest { + private LdapOperations ldapOperationsMock; + + private TempEntryRenamingStrategy renamingStrategyMock; + + private DirContext dirContextMock; + + private LdapCompensatingTransactionOperationFactory tested; + + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + renamingStrategyMock = mock(TempEntryRenamingStrategy.class); + dirContextMock = mock(DirContext.class); + + tested = new LdapCompensatingTransactionOperationFactory( + renamingStrategyMock) { + + LdapOperations createLdapOperationsInstance(DirContext ctx) { + assertThat(ctx).isEqualTo(dirContextMock); + return ldapOperationsMock; + } + }; + } + + @Test + public void testGetRecordingOperation_Bind() throws Exception { + + CompensatingTransactionOperationRecorder result = tested + .createRecordingOperation(dirContextMock, "bind"); + assertThat(result instanceof BindOperationRecorder).isTrue(); + BindOperationRecorder bindOperationRecorder = (BindOperationRecorder) result; + assertThat(bindOperationRecorder.getLdapOperations()).isSameAs(ldapOperationsMock); + } + + @Test + public void testGetRecordingOperation_Rebind() throws Exception { + CompensatingTransactionOperationRecorder result = tested + .createRecordingOperation(dirContextMock, "rebind"); + assertThat(result instanceof RebindOperationRecorder).isTrue(); + RebindOperationRecorder rebindOperationRecorder = (RebindOperationRecorder) result; + assertThat(rebindOperationRecorder.getLdapOperations()).isSameAs(ldapOperationsMock); + assertThat(rebindOperationRecorder.getRenamingStrategy()).isSameAs(renamingStrategyMock); + } + + @Test + public void testGetRecordingOperation_Rename() throws Exception { + CompensatingTransactionOperationRecorder result = tested + .createRecordingOperation(dirContextMock, "rename"); + assertThat(result instanceof RenameOperationRecorder).isTrue(); + RenameOperationRecorder recordingOperation = (RenameOperationRecorder) result; + assertThat(recordingOperation.getLdapOperations()).isSameAs(ldapOperationsMock); + } + + @Test + public void testGetRecordingOperation_ModifyAttributes() throws Exception { + CompensatingTransactionOperationRecorder result = tested + .createRecordingOperation(dirContextMock, "modifyAttributes"); + assertThat(result instanceof ModifyAttributesOperationRecorder).isTrue(); + ModifyAttributesOperationRecorder recordingOperation = (ModifyAttributesOperationRecorder) result; + assertThat(recordingOperation.getLdapOperations()).isSameAs(ldapOperationsMock); + } + + @Test + public void testGetRecordingOperation_Unbind() throws Exception { + 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 6a88ebd7..2c1c9d21 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 @@ -1,77 +1,77 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class LdapTransactionUtilsTest { - - private DirContext dirContextMock; - - @Before - public void setUp() throws Exception { - dirContextMock = mock(DirContext.class); - - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.clearSynchronization(); - } - } - - @Test - public void testCloseContext() throws NamingException { - LdapUtils.closeContext(dirContextMock); - verify(dirContextMock).close(); - } - - @Test - public void testCloseContext_NullContext() throws NamingException { - LdapUtils.closeContext(null); - } - - @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")); - } - - public void dummyMethod() { - - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class LdapTransactionUtilsTest { + + private DirContext dirContextMock; + + @Before + public void setUp() throws Exception { + dirContextMock = mock(DirContext.class); + + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + public void testCloseContext() throws NamingException { + LdapUtils.closeContext(dirContextMock); + verify(dirContextMock).close(); + } + + @Test + public void testCloseContext_NullContext() throws NamingException { + LdapUtils.closeContext(null); + } + + @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")); + } + + 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 b1cc3907..58372b3c 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 @@ -1,86 +1,86 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.Name; -import javax.naming.directory.ModificationItem; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class ModifyAttributesOperationExecutorTest { - private LdapOperations ldapOperationsMock; - - @Before - public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class); - } - - @Test - public void testPerformOperation() { - ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; - ModificationItem[] expectedActualItems = new ModificationItem[0]; - - Name expectedDn = LdapUtils.newLdapName("cn=john doe"); - - ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, - expectedDn, expectedActualItems, expectedCompensatingItems); - - // Perform test - tested.performOperation(); - - verify(ldapOperationsMock).modifyAttributes(expectedDn, expectedActualItems); - } - - @Test - public void testCommit() { - ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; - ModificationItem[] expectedActualItems = new ModificationItem[0]; - - Name expectedDn = LdapUtils.newLdapName("cn=john doe"); - - ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, - expectedDn, expectedActualItems, expectedCompensatingItems); - - // No operation here - verifyNoMoreInteractions(ldapOperationsMock); - - // Perform test - tested.commit(); - } - - @Test - public void testRollback() { - ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; - ModificationItem[] expectedActualItems = new ModificationItem[0]; - - Name expectedDn = LdapUtils.newLdapName("cn=john doe"); - - ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, - expectedDn, expectedActualItems, expectedCompensatingItems); - - // Perform test - tested.rollback(); - - verify(ldapOperationsMock).modifyAttributes(expectedDn, expectedCompensatingItems); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.Name; +import javax.naming.directory.ModificationItem; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +public class ModifyAttributesOperationExecutorTest { + private LdapOperations ldapOperationsMock; + + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + } + + @Test + public void testPerformOperation() { + ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; + ModificationItem[] expectedActualItems = new ModificationItem[0]; + + Name expectedDn = LdapUtils.newLdapName("cn=john doe"); + + ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, + expectedDn, expectedActualItems, expectedCompensatingItems); + + // Perform test + tested.performOperation(); + + verify(ldapOperationsMock).modifyAttributes(expectedDn, expectedActualItems); + } + + @Test + public void testCommit() { + ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; + ModificationItem[] expectedActualItems = new ModificationItem[0]; + + Name expectedDn = LdapUtils.newLdapName("cn=john doe"); + + ModifyAttributesOperationExecutor tested = new ModifyAttributesOperationExecutor(ldapOperationsMock, + expectedDn, expectedActualItems, expectedCompensatingItems); + + // No operation here + verifyNoMoreInteractions(ldapOperationsMock); + + // Perform test + tested.commit(); + } + + @Test + public void testRollback() { + ModificationItem[] expectedCompensatingItems = new ModificationItem[0]; + ModificationItem[] expectedActualItems = new ModificationItem[0]; + + Name expectedDn = LdapUtils.newLdapName("cn=john doe"); + + 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 30a4d412..c6ccbe67 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 @@ -1,256 +1,256 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.IncrementalAttributesMapper; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; - -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.BasicAttribute; -import javax.naming.directory.BasicAttributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.ModificationItem; -import javax.naming.ldap.LdapName; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ModifyAttributesOperationRecorderTest { - private LdapOperations ldapOperationsMock; - - private IncrementalAttributesMapper attributesMapperMock; - - private ModifyAttributesOperationRecorder tested; - - @Before - public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class); - attributesMapperMock = mock(IncrementalAttributesMapper.class); - - tested = new ModifyAttributesOperationRecorder(ldapOperationsMock); - } - - @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 Attributes expectedAttributes = new BasicAttributes(); - - tested = new ModifyAttributesOperationRecorder(ldapOperationsMock) { - IncrementalAttributesMapper getAttributesMapper(String[] attributeNames) { - return attributesMapperMock; - } - - protected ModificationItem getCompensatingModificationItem( - Attributes originalAttributes, - ModificationItem modificationItem) { - assertThat(originalAttributes).isSameAs(expectedAttributes); - assertThat(modificationItem).isSameAs(incomingItem); - return compensatingItem; - } - }; - - 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()) - .thenReturn(expectedAttributes); - - // Perform test - CompensatingTransactionOperationExecutor operation = tested - .recordOperation(new Object[]{expectedName, incomingMods}); - - // Verify outcome - assertThat(operation instanceof ModifyAttributesOperationExecutor).isTrue(); - ModifyAttributesOperationExecutor rollbackOperation = (ModifyAttributesOperationExecutor) operation; - assertThat(rollbackOperation.getDn()).isSameAs(expectedName); - assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); - ModificationItem[] actualModifications = rollbackOperation.getActualModifications(); - assertThat(actualModifications.length).isEqualTo(incomingMods.length); - assertThat(actualModifications[0]).isEqualTo(incomingMods[0]); - assertThat(rollbackOperation.getCompensatingModifications().length).isEqualTo(1); - assertThat(rollbackOperation.getCompensatingModifications()[0]).isSameAs(compensatingItem); - } - - @Test - 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")); - - // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); - - // Verify result - assertThat(result.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE); - Attribute resultAttribute = result.getAttribute(); - assertThat(resultAttribute.getID()).isEqualTo("someattr"); - Object object = resultAttribute.get(0); - assertThat(object).isEqualTo("value1"); - assertThat(resultAttribute.get(1)).isEqualTo("value2"); - } - - @Test - public void testGetCompensatingModificationItem_RemoveTwoAttributeValues() - throws NamingException { - BasicAttribute attribute = new BasicAttribute("someattr"); - attribute.add("value1"); - attribute.add("value2"); - attribute.add("value3"); - Attributes attributes = new BasicAttributes(); - attributes.put(attribute); - - BasicAttribute modificationAttribute = new BasicAttribute("someattr"); - modificationAttribute.add("value1"); - modificationAttribute.add("value2"); - ModificationItem originalItem = new ModificationItem( - DirContext.REMOVE_ATTRIBUTE, modificationAttribute); - - // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); - - // Verify result - assertThat(result.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE); - Attribute resultAttribute = result.getAttribute(); - assertThat(resultAttribute.getID()).isEqualTo("someattr"); - Object object = resultAttribute.get(0); - assertThat(object).isEqualTo("value1"); - assertThat(resultAttribute.get(1)).isEqualTo("value2"); - } - - @Test - public void testGetCompensatingModificationItem_ReplaceExistingAttribute() - throws NamingException { - BasicAttribute attribute = new BasicAttribute("someattr"); - attribute.add("value1"); - attribute.add("value2"); - Attributes attributes = new BasicAttributes(); - attributes.put(attribute); - - BasicAttribute modificationAttribute = new BasicAttribute("someattr"); - modificationAttribute.add("newvalue1"); - modificationAttribute.add("newvalue2"); - ModificationItem originalItem = new ModificationItem( - DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("someattr")); - - // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); - - // Verify result - assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE); - Attribute resultAttribute = result.getAttribute(); - assertThat(resultAttribute.getID()).isEqualTo("someattr"); - Object object = resultAttribute.get(0); - assertThat(object).isEqualTo("value1"); - assertThat(resultAttribute.get(1)).isEqualTo("value2"); - } - - @Test - 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); - - // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); - - // Verify result - assertThat(result.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE); - Attribute resultAttribute = result.getAttribute(); - assertThat(resultAttribute.getID()).isEqualTo("someattr"); - assertThat(resultAttribute.size()).isEqualTo(0); - } - - @Test - 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); - - // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); - - // Verify result - assertThat(result.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE); - Attribute resultAttribute = result.getAttribute(); - assertThat(resultAttribute.getID()).isEqualTo("someattr"); - assertThat(resultAttribute.size()).isEqualTo(0); - } - - @Test - public void testGetCompensatingModificationItem_AddExistingAttribute() - throws NamingException { - BasicAttribute attribute = new BasicAttribute("someattr"); - attribute.add("value1"); - attribute.add("value2"); - Attributes attributes = new BasicAttributes(); - attributes.put(attribute); - - BasicAttribute modificationAttribute = new BasicAttribute("someattr"); - modificationAttribute.add("newvalue1"); - modificationAttribute.add("newvalue2"); - ModificationItem originalItem = new ModificationItem( - DirContext.ADD_ATTRIBUTE, new BasicAttribute("someattr")); - - // Perform test - ModificationItem result = tested.getCompensatingModificationItem( - attributes, originalItem); - - // Verify result - assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE); - Attribute resultAttribute = result.getAttribute(); - assertThat(resultAttribute.getID()).isEqualTo("someattr"); - assertThat(result.getAttribute().get(0)).isEqualTo("value1"); - assertThat(result.getAttribute().get(1)).isEqualTo("value2"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.IncrementalAttributesMapper; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; + +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttribute; +import javax.naming.directory.BasicAttributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.ModificationItem; +import javax.naming.ldap.LdapName; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ModifyAttributesOperationRecorderTest { + private LdapOperations ldapOperationsMock; + + private IncrementalAttributesMapper attributesMapperMock; + + private ModifyAttributesOperationRecorder tested; + + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + attributesMapperMock = mock(IncrementalAttributesMapper.class); + + tested = new ModifyAttributesOperationRecorder(ldapOperationsMock); + } + + @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 Attributes expectedAttributes = new BasicAttributes(); + + tested = new ModifyAttributesOperationRecorder(ldapOperationsMock) { + IncrementalAttributesMapper getAttributesMapper(String[] attributeNames) { + return attributesMapperMock; + } + + protected ModificationItem getCompensatingModificationItem( + Attributes originalAttributes, + ModificationItem modificationItem) { + assertThat(originalAttributes).isSameAs(expectedAttributes); + assertThat(modificationItem).isSameAs(incomingItem); + return compensatingItem; + } + }; + + 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()) + .thenReturn(expectedAttributes); + + // Perform test + CompensatingTransactionOperationExecutor operation = tested + .recordOperation(new Object[]{expectedName, incomingMods}); + + // Verify outcome + assertThat(operation instanceof ModifyAttributesOperationExecutor).isTrue(); + ModifyAttributesOperationExecutor rollbackOperation = (ModifyAttributesOperationExecutor) operation; + assertThat(rollbackOperation.getDn()).isSameAs(expectedName); + assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); + ModificationItem[] actualModifications = rollbackOperation.getActualModifications(); + assertThat(actualModifications.length).isEqualTo(incomingMods.length); + assertThat(actualModifications[0]).isEqualTo(incomingMods[0]); + assertThat(rollbackOperation.getCompensatingModifications().length).isEqualTo(1); + assertThat(rollbackOperation.getCompensatingModifications()[0]).isSameAs(compensatingItem); + } + + @Test + 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")); + + // Perform test + ModificationItem result = tested.getCompensatingModificationItem( + attributes, originalItem); + + // Verify result + assertThat(result.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE); + Attribute resultAttribute = result.getAttribute(); + assertThat(resultAttribute.getID()).isEqualTo("someattr"); + Object object = resultAttribute.get(0); + assertThat(object).isEqualTo("value1"); + assertThat(resultAttribute.get(1)).isEqualTo("value2"); + } + + @Test + public void testGetCompensatingModificationItem_RemoveTwoAttributeValues() + throws NamingException { + BasicAttribute attribute = new BasicAttribute("someattr"); + attribute.add("value1"); + attribute.add("value2"); + attribute.add("value3"); + Attributes attributes = new BasicAttributes(); + attributes.put(attribute); + + BasicAttribute modificationAttribute = new BasicAttribute("someattr"); + modificationAttribute.add("value1"); + modificationAttribute.add("value2"); + ModificationItem originalItem = new ModificationItem( + DirContext.REMOVE_ATTRIBUTE, modificationAttribute); + + // Perform test + ModificationItem result = tested.getCompensatingModificationItem( + attributes, originalItem); + + // Verify result + assertThat(result.getModificationOp()).isEqualTo(DirContext.ADD_ATTRIBUTE); + Attribute resultAttribute = result.getAttribute(); + assertThat(resultAttribute.getID()).isEqualTo("someattr"); + Object object = resultAttribute.get(0); + assertThat(object).isEqualTo("value1"); + assertThat(resultAttribute.get(1)).isEqualTo("value2"); + } + + @Test + public void testGetCompensatingModificationItem_ReplaceExistingAttribute() + throws NamingException { + BasicAttribute attribute = new BasicAttribute("someattr"); + attribute.add("value1"); + attribute.add("value2"); + Attributes attributes = new BasicAttributes(); + attributes.put(attribute); + + BasicAttribute modificationAttribute = new BasicAttribute("someattr"); + modificationAttribute.add("newvalue1"); + modificationAttribute.add("newvalue2"); + ModificationItem originalItem = new ModificationItem( + DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("someattr")); + + // Perform test + ModificationItem result = tested.getCompensatingModificationItem( + attributes, originalItem); + + // Verify result + assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE); + Attribute resultAttribute = result.getAttribute(); + assertThat(resultAttribute.getID()).isEqualTo("someattr"); + Object object = resultAttribute.get(0); + assertThat(object).isEqualTo("value1"); + assertThat(resultAttribute.get(1)).isEqualTo("value2"); + } + + @Test + 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); + + // Perform test + ModificationItem result = tested.getCompensatingModificationItem( + attributes, originalItem); + + // Verify result + assertThat(result.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE); + Attribute resultAttribute = result.getAttribute(); + assertThat(resultAttribute.getID()).isEqualTo("someattr"); + assertThat(resultAttribute.size()).isEqualTo(0); + } + + @Test + 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); + + // Perform test + ModificationItem result = tested.getCompensatingModificationItem( + attributes, originalItem); + + // Verify result + assertThat(result.getModificationOp()).isEqualTo(DirContext.REMOVE_ATTRIBUTE); + Attribute resultAttribute = result.getAttribute(); + assertThat(resultAttribute.getID()).isEqualTo("someattr"); + assertThat(resultAttribute.size()).isEqualTo(0); + } + + @Test + public void testGetCompensatingModificationItem_AddExistingAttribute() + throws NamingException { + BasicAttribute attribute = new BasicAttribute("someattr"); + attribute.add("value1"); + attribute.add("value2"); + Attributes attributes = new BasicAttributes(); + attributes.put(attribute); + + BasicAttribute modificationAttribute = new BasicAttribute("someattr"); + modificationAttribute.add("newvalue1"); + modificationAttribute.add("newvalue2"); + ModificationItem originalItem = new ModificationItem( + DirContext.ADD_ATTRIBUTE, new BasicAttribute("someattr")); + + // Perform test + ModificationItem result = tested.getCompensatingModificationItem( + attributes, originalItem); + + // Verify result + assertThat(result.getModificationOp()).isEqualTo(DirContext.REPLACE_ATTRIBUTE); + Attribute resultAttribute = result.getAttribute(); + assertThat(resultAttribute.getID()).isEqualTo("someattr"); + 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 3b3e9b39..fa154038 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 @@ -1,92 +1,92 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.directory.BasicAttributes; -import javax.naming.ldap.LdapName; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class RebindOperationExecutorTest { - - private LdapOperations ldapOperationsMock; - - @Before - public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class); - } - - @Test - public void testPerformOperation() { - 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); - - // perform test - tested.performOperation(); - verify(ldapOperationsMock).rename(expectedOriginalDn, expectedTempDn); - 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"); - Object expectedObject = new Object(); - BasicAttributes expectedAttributes = new BasicAttributes(); - RebindOperationExecutor tested = new RebindOperationExecutor( - ldapOperationsMock, expectedOriginalDn, expectedTempDn, - expectedObject, expectedAttributes); - - // perform test - tested.commit(); - verify(ldapOperationsMock).unbind(expectedTempDn); - } - - @Test - public void testRollback() { - 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); - - // perform test - tested.rollback(); - - verify(ldapOperationsMock).unbind(expectedOriginalDn); - verify(ldapOperationsMock).rename(expectedTempDn, expectedOriginalDn); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.directory.BasicAttributes; +import javax.naming.ldap.LdapName; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class RebindOperationExecutorTest { + + private LdapOperations ldapOperationsMock; + + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + } + + @Test + public void testPerformOperation() { + 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); + + // perform test + tested.performOperation(); + verify(ldapOperationsMock).rename(expectedOriginalDn, expectedTempDn); + 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"); + Object expectedObject = new Object(); + BasicAttributes expectedAttributes = new BasicAttributes(); + RebindOperationExecutor tested = new RebindOperationExecutor( + ldapOperationsMock, expectedOriginalDn, expectedTempDn, + expectedObject, expectedAttributes); + + // perform test + tested.commit(); + verify(ldapOperationsMock).unbind(expectedTempDn); + } + + @Test + public void testRollback() { + 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); + + // perform test + tested.rollback(); + + 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 2bad4549..be43a216 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 @@ -1,70 +1,70 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; - -import javax.naming.directory.BasicAttributes; -import javax.naming.ldap.LdapName; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class RebindOperationRecorderTest { - private LdapOperations ldapOperationsMock; - - private TempEntryRenamingStrategy renamingStrategyMock; - - @Before - public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class); - renamingStrategyMock = mock(TempEntryRenamingStrategy.class); - - } - - @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); - - 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 }); - assertThat(result instanceof RebindOperationExecutor).isTrue(); - RebindOperationExecutor rollbackOperation = (RebindOperationExecutor) result; - assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); - assertThat(rollbackOperation.getOriginalDn()).isSameAs(expectedDn); - assertThat(rollbackOperation.getTemporaryDn()).isSameAs(expectedTempDn); - assertThat(rollbackOperation.getOriginalObject()).isSameAs(expectedObject); - assertThat(rollbackOperation.getOriginalAttributes()).isSameAs(expectedAttributes); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; + +import javax.naming.directory.BasicAttributes; +import javax.naming.ldap.LdapName; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class RebindOperationRecorderTest { + private LdapOperations ldapOperationsMock; + + private TempEntryRenamingStrategy renamingStrategyMock; + + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class); + renamingStrategyMock = mock(TempEntryRenamingStrategy.class); + + } + + @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); + + 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 }); + assertThat(result instanceof RebindOperationExecutor).isTrue(); + RebindOperationExecutor rollbackOperation = (RebindOperationExecutor) result; + assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); + assertThat(rollbackOperation.getOriginalDn()).isSameAs(expectedDn); + assertThat(rollbackOperation.getTemporaryDn()).isSameAs(expectedTempDn); + 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 dfa57b8a..117ccbba 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 @@ -1,80 +1,80 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.ldap.LdapName; - -import static org.mockito.Mockito.mock; -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);; - } - - - - @Test - public void testPerformOperation() { - LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); - LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); - RenameOperationExecutor tested = new RenameOperationExecutor( - ldapOperationsMock, expectedOldName, expectedNewName); - - // Perform test. - tested.performOperation(); - - verify(ldapOperationsMock).rename(expectedOldName, expectedNewName); - } - - @Test - public void testCommit() { - LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); - LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); - RenameOperationExecutor tested = new RenameOperationExecutor( - ldapOperationsMock, expectedOldName, expectedNewName); - - // Nothing to do for this operation. - verifyNoMoreInteractions(ldapOperationsMock); - - // Perform test. - tested.commit(); - } - - @Test - public void testRollback() { - LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); - LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); - RenameOperationExecutor tested = new RenameOperationExecutor( - ldapOperationsMock, expectedOldName, expectedNewName); - - // Perform test. - tested.rollback(); - - verify(ldapOperationsMock).rename(expectedNewName, expectedOldName); - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.ldap.LdapName; + +import static org.mockito.Mockito.mock; +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);; + } + + + + @Test + public void testPerformOperation() { + LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); + LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); + RenameOperationExecutor tested = new RenameOperationExecutor( + ldapOperationsMock, expectedOldName, expectedNewName); + + // Perform test. + tested.performOperation(); + + verify(ldapOperationsMock).rename(expectedOldName, expectedNewName); + } + + @Test + public void testCommit() { + LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); + LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); + RenameOperationExecutor tested = new RenameOperationExecutor( + ldapOperationsMock, expectedOldName, expectedNewName); + + // Nothing to do for this operation. + verifyNoMoreInteractions(ldapOperationsMock); + + // Perform test. + tested.commit(); + } + + @Test + public void testRollback() { + LdapName expectedNewName = LdapUtils.newLdapName("ou=newOu"); + LdapName expectedOldName = LdapUtils.newLdapName("ou=someou"); + RenameOperationExecutor tested = new RenameOperationExecutor( + ldapOperationsMock, expectedOldName, expectedNewName); + + // Perform test. + tested.rollback(); + + verify(ldapOperationsMock).rename(expectedNewName, expectedOldName); + } + +} 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 64af3ba4..d8523a1e 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 @@ -1,50 +1,50 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class RenameOperationRecorderTest { - - private LdapOperations ldapOperationsMock; - - @Before - public void setUp() throws Exception { - ldapOperationsMock = mock(LdapOperations.class);; - } - - @Test - public void testRecordOperation() { - RenameOperationRecorder tested = new RenameOperationRecorder( - ldapOperationsMock); - - // Perform test - CompensatingTransactionOperationExecutor operation = tested - .recordOperation(new Object[] { "ou=someou", "ou=newou" }); - - assertThat(operation instanceof RenameOperationExecutor).isTrue(); - RenameOperationExecutor rollbackOperation = (RenameOperationExecutor) operation; - assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); - assertThat(rollbackOperation.getNewDn().toString()).isEqualTo("ou=newou"); - assertThat(rollbackOperation.getOriginalDn().toString()).isEqualTo("ou=someou"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +public class RenameOperationRecorderTest { + + private LdapOperations ldapOperationsMock; + + @Before + public void setUp() throws Exception { + ldapOperationsMock = mock(LdapOperations.class);; + } + + @Test + public void testRecordOperation() { + RenameOperationRecorder tested = new RenameOperationRecorder( + ldapOperationsMock); + + // Perform test + CompensatingTransactionOperationExecutor operation = tested + .recordOperation(new Object[] { "ou=someou", "ou=newou" }); + + assertThat(operation instanceof RenameOperationExecutor).isTrue(); + RenameOperationExecutor rollbackOperation = (RenameOperationExecutor) operation; + assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); + 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 cf89b1e0..304d500a 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 @@ -1,74 +1,74 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.ldap.LdapName; - -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);; - } - - @Test - public void testPerformOperation() { - LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); - LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); - UnbindOperationExecutor tested = new UnbindOperationExecutor( - ldapOperationsMock, expectedOldName, expectedTempName); - - // Perform test - tested.performOperation(); - - verify(ldapOperationsMock).rename(expectedOldName, expectedTempName); - } - - @Test - public void testCommit() { - LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); - LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); - UnbindOperationExecutor tested = new UnbindOperationExecutor( - ldapOperationsMock, expectedOldName, expectedTempName); - - // Perform test - tested.commit(); - verify(ldapOperationsMock).unbind(expectedTempName); - } - - @Test - public void testRollback() { - LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); - LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); - UnbindOperationExecutor tested = new UnbindOperationExecutor( - ldapOperationsMock, expectedOldName, expectedTempName); - - - - // Perform test - tested.rollback(); - verify(ldapOperationsMock).rename(expectedTempName, expectedOldName); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.ldap.LdapName; + +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);; + } + + @Test + public void testPerformOperation() { + LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); + LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); + UnbindOperationExecutor tested = new UnbindOperationExecutor( + ldapOperationsMock, expectedOldName, expectedTempName); + + // Perform test + tested.performOperation(); + + verify(ldapOperationsMock).rename(expectedOldName, expectedTempName); + } + + @Test + public void testCommit() { + LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); + LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); + UnbindOperationExecutor tested = new UnbindOperationExecutor( + ldapOperationsMock, expectedOldName, expectedTempName); + + // Perform test + tested.commit(); + verify(ldapOperationsMock).unbind(expectedTempName); + } + + @Test + public void testRollback() { + LdapName expectedOldName = LdapUtils.newLdapName("cn=oldDn"); + LdapName expectedTempName = LdapUtils.newLdapName("cn=newDn"); + 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 cfa10d83..bc939d81 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 @@ -1,66 +1,66 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; - -import javax.naming.ldap.LdapName; - -import static org.assertj.core.api.Assertions.assertThat; -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);; - - 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); - - when(renamingStrategyMock.getTemporaryName(expectedDn)) - .thenReturn(expectedTempName); - - // Perform test - CompensatingTransactionOperationExecutor operation = tested - .recordOperation(new Object[] { expectedDn }); - - // Verify result - assertThat(operation instanceof UnbindOperationExecutor).isTrue(); - UnbindOperationExecutor rollbackOperation = (UnbindOperationExecutor) operation; - assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); - assertThat(rollbackOperation.getOriginalDn()).isSameAs(expectedDn); - assertThat(rollbackOperation.getTemporaryDn()).isSameAs(expectedTempName); - } - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; + +import javax.naming.ldap.LdapName; + +import static org.assertj.core.api.Assertions.assertThat; +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);; + + 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); + + when(renamingStrategyMock.getTemporaryName(expectedDn)) + .thenReturn(expectedTempName); + + // Perform test + CompensatingTransactionOperationExecutor operation = tested + .recordOperation(new Object[] { expectedDn }); + + // Verify result + assertThat(operation instanceof UnbindOperationExecutor).isTrue(); + UnbindOperationExecutor rollbackOperation = (UnbindOperationExecutor) operation; + assertThat(rollbackOperation.getLdapOperations()).isSameAs(ldapOperationsMock); + assertThat(rollbackOperation.getOriginalDn()).isSameAs(expectedDn); + assertThat(rollbackOperation.getTemporaryDn()).isSameAs(expectedTempName); + } + +} 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 e539325b..0edf271e 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 @@ -1,86 +1,86 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.manager; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.ContextSource; -import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; -import org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport; -import org.springframework.transaction.compensating.support.CompensatingTransactionUtils; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -import javax.naming.directory.DirContext; -import java.lang.reflect.Method; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class CompensatingTransactionUtilsTest { - - private DirContext dirContextMock; - - private ContextSource contextSourceMock; - - private CompensatingTransactionOperationManager operationManagerMock; - - @Before - public void setUp() throws Exception { - dirContextMock = mock(DirContext.class); - contextSourceMock = mock(ContextSource.class); - operationManagerMock = mock(CompensatingTransactionOperationManager.class); - - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.clearSynchronization(); - } - } - - @Test - public void testPerformOperation() throws Throwable { - CompensatingTransactionHolderSupport holder = new DirContextHolder( - null, dirContextMock); - holder.setTransactionOperationManager(operationManagerMock); - - TransactionSynchronizationManager.bindResource(contextSourceMock, - holder); - - Object[] expectedArgs = new Object[] { "someDn" }; - - 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); - verify(dirContextMock).unbind("someDn"); - } - - private Method getUnbindMethod() throws NoSuchMethodException { - return DirContext.class.getMethod("unbind", - new Class[] { String.class }); - } - - public void dummyMethod() { - - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.manager; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.ContextSource; +import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; +import org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport; +import org.springframework.transaction.compensating.support.CompensatingTransactionUtils; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import javax.naming.directory.DirContext; +import java.lang.reflect.Method; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +public class CompensatingTransactionUtilsTest { + + private DirContext dirContextMock; + + private ContextSource contextSourceMock; + + private CompensatingTransactionOperationManager operationManagerMock; + + @Before + public void setUp() throws Exception { + dirContextMock = mock(DirContext.class); + contextSourceMock = mock(ContextSource.class); + operationManagerMock = mock(CompensatingTransactionOperationManager.class); + + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + public void testPerformOperation() throws Throwable { + CompensatingTransactionHolderSupport holder = new DirContextHolder( + null, dirContextMock); + holder.setTransactionOperationManager(operationManagerMock); + + TransactionSynchronizationManager.bindResource(contextSourceMock, + holder); + + Object[] expectedArgs = new Object[] { "someDn" }; + + 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); + verify(dirContextMock).unbind("someDn"); + } + + private Method getUnbindMethod() throws NoSuchMethodException { + 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 1d2617e3..d8785254 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 @@ -1,196 +1,196 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.manager; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.jdbc.datasource.DataSourceTransactionManager; -import org.springframework.ldap.UncategorizedLdapException; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; -import org.springframework.transaction.CannotCreateTransactionException; -import org.springframework.transaction.PlatformTransactionManager; -import org.springframework.transaction.TransactionDefinition; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; -import org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport; -import org.springframework.transaction.compensating.support.CompensatingTransactionObject; -import org.springframework.transaction.support.DefaultTransactionDefinition; -import org.springframework.transaction.support.DefaultTransactionStatus; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -import javax.naming.directory.DirContext; -import javax.sql.DataSource; -import java.sql.Connection; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class ContextSourceTransactionManagerTest { - - private ContextSource contextSourceMock; - private DirContext contextMock; - - private ContextSourceTransactionManager tested; - private CompensatingTransactionOperationManager transactionDataManagerMock; - - private TransactionDefinition transactionDefinitionMock; - - private TempEntryRenamingStrategy renamingStrategyMock; - - @Before - public void setUp() throws Exception { - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.clearSynchronization(); - } - - contextSourceMock = mock(ContextSource.class); - contextMock = mock(DirContext.class); - transactionDefinitionMock = mock(TransactionDefinition.class); - transactionDataManagerMock = mock(CompensatingTransactionOperationManager.class); - renamingStrategyMock = mock(TempEntryRenamingStrategy.class); - - tested = new ContextSourceTransactionManager(); - tested.setContextSource(contextSourceMock); - tested.setRenamingStrategy(renamingStrategyMock); - } - - @Test - public void testDoGetTransaction() { - Object result = tested.doGetTransaction(); - - assertThat(result).isNotNull(); - assertThat(result instanceof CompensatingTransactionObject).isTrue(); - CompensatingTransactionObject transactionObject = (CompensatingTransactionObject) result; - assertThat(transactionObject.getHolder()).isNull(); - } - - @Test - public void testDoGetTransactionTransactionActive() { - CompensatingTransactionHolderSupport expectedContextHolder = new DirContextHolder(null, null); - TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); - Object result = tested.doGetTransaction(); - assertThat(((CompensatingTransactionObject) result).getHolder()).isSameAs(expectedContextHolder); - } - - @Test - public void testDoBegin() { - when(contextSourceMock.getReadWriteContext()).thenReturn(contextMock); - - CompensatingTransactionObject expectedTransactionObject = new CompensatingTransactionObject(null); - tested.doBegin(expectedTransactionObject, transactionDefinitionMock); - - DirContextHolder foundContextHolder = (DirContextHolder) TransactionSynchronizationManager - .getResource(contextSourceMock); - assertThat(foundContextHolder.getCtx()).isSameAs(contextMock); - } - - @Test - public void testDoRollback() { - DirContextHolder expectedContextHolder = new DirContextHolder(null, contextMock); - expectedContextHolder.setTransactionOperationManager(transactionDataManagerMock); - TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); - - CompensatingTransactionObject transactionObject = new CompensatingTransactionObject(null); - transactionObject.setHolder(expectedContextHolder); - tested.doRollback(new DefaultTransactionStatus(transactionObject, false, false, false, false, null)); - - verify(transactionDataManagerMock).rollback(); - } - - @Test - public void testDoCleanupAfterCompletion() throws Exception { - DirContextHolder expectedContextHolder = new DirContextHolder(null, contextMock); - TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); - - tested.doCleanupAfterCompletion(new CompensatingTransactionObject(expectedContextHolder)); - - assertThat(TransactionSynchronizationManager.getResource(contextSourceMock)).isNull(); - assertThat(expectedContextHolder.getTransactionOperationManager()).isNull(); - verify(contextMock).close(); - } - - @Test - public void testSetContextSource_Proxy() { - TransactionAwareContextSourceProxy proxy = new TransactionAwareContextSourceProxy(contextSourceMock); - - // Perform test - tested.setContextSource(proxy); - ContextSource result = tested.getContextSource(); - - // Verify result - assertThat(result).isSameAs(contextSourceMock); - } - - @Test - public void testTransactionSuspension_UnconnectableDataSource() throws Exception { - Connection connectionMock = mock(Connection.class); - DataSource dataSourceMock = mock(DataSource.class); - - when(dataSourceMock.getConnection()).thenReturn(connectionMock); - when(connectionMock.getAutoCommit()).thenReturn(false); - - ContextSource unconnectableContextSourceMock = mock(ContextSource.class); - - UncategorizedLdapException connectException = new UncategorizedLdapException("dummy"); - when(unconnectableContextSourceMock.getReadWriteContext()).thenThrow(connectException); - - try { - // Create an outer transaction - final PlatformTransactionManager txMgrOuter = new DataSourceTransactionManager(dataSourceMock); - - final TransactionStatus txOuter = txMgrOuter.getTransaction(new DefaultTransactionDefinition()); - - try { - // Create inner transaction (not nested, though: unrelated data - // source) - final ContextSourceTransactionManager txMgrInner = new ContextSourceTransactionManager(); - txMgrInner.setContextSource(unconnectableContextSourceMock); - - final TransactionStatus txInner = txMgrInner.getTransaction(new DefaultTransactionDefinition( - TransactionDefinition.PROPAGATION_REQUIRES_NEW)); - - try { - // Do something with the connection that succeeds or fails - // (but we dont get this far) - // etc, etc... - - txMgrInner.commit(txInner); - } - catch (Exception e) { - txMgrInner.rollback(txInner); - throw e; - } - - txMgrOuter.commit(txOuter); - } - catch (Exception e) { - txMgrOuter.rollback(txOuter); - throw e; - } - - fail("Exception should be thrown"); - } - catch (CannotCreateTransactionException expected) { - assertThat(expected.getCause()).as("Should be thrown exception").isSameAs(connectException); - } - - verify(connectionMock).rollback(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.manager; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.ldap.UncategorizedLdapException; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.transaction.compensating.TempEntryRenamingStrategy; +import org.springframework.transaction.CannotCreateTransactionException; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.compensating.CompensatingTransactionOperationManager; +import org.springframework.transaction.compensating.support.CompensatingTransactionHolderSupport; +import org.springframework.transaction.compensating.support.CompensatingTransactionObject; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import javax.naming.directory.DirContext; +import javax.sql.DataSource; +import java.sql.Connection; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class ContextSourceTransactionManagerTest { + + private ContextSource contextSourceMock; + private DirContext contextMock; + + private ContextSourceTransactionManager tested; + private CompensatingTransactionOperationManager transactionDataManagerMock; + + private TransactionDefinition transactionDefinitionMock; + + private TempEntryRenamingStrategy renamingStrategyMock; + + @Before + public void setUp() throws Exception { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + + contextSourceMock = mock(ContextSource.class); + contextMock = mock(DirContext.class); + transactionDefinitionMock = mock(TransactionDefinition.class); + transactionDataManagerMock = mock(CompensatingTransactionOperationManager.class); + renamingStrategyMock = mock(TempEntryRenamingStrategy.class); + + tested = new ContextSourceTransactionManager(); + tested.setContextSource(contextSourceMock); + tested.setRenamingStrategy(renamingStrategyMock); + } + + @Test + public void testDoGetTransaction() { + Object result = tested.doGetTransaction(); + + assertThat(result).isNotNull(); + assertThat(result instanceof CompensatingTransactionObject).isTrue(); + CompensatingTransactionObject transactionObject = (CompensatingTransactionObject) result; + assertThat(transactionObject.getHolder()).isNull(); + } + + @Test + public void testDoGetTransactionTransactionActive() { + CompensatingTransactionHolderSupport expectedContextHolder = new DirContextHolder(null, null); + TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); + Object result = tested.doGetTransaction(); + assertThat(((CompensatingTransactionObject) result).getHolder()).isSameAs(expectedContextHolder); + } + + @Test + public void testDoBegin() { + when(contextSourceMock.getReadWriteContext()).thenReturn(contextMock); + + CompensatingTransactionObject expectedTransactionObject = new CompensatingTransactionObject(null); + tested.doBegin(expectedTransactionObject, transactionDefinitionMock); + + DirContextHolder foundContextHolder = (DirContextHolder) TransactionSynchronizationManager + .getResource(contextSourceMock); + assertThat(foundContextHolder.getCtx()).isSameAs(contextMock); + } + + @Test + public void testDoRollback() { + DirContextHolder expectedContextHolder = new DirContextHolder(null, contextMock); + expectedContextHolder.setTransactionOperationManager(transactionDataManagerMock); + TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); + + CompensatingTransactionObject transactionObject = new CompensatingTransactionObject(null); + transactionObject.setHolder(expectedContextHolder); + tested.doRollback(new DefaultTransactionStatus(transactionObject, false, false, false, false, null)); + + verify(transactionDataManagerMock).rollback(); + } + + @Test + public void testDoCleanupAfterCompletion() throws Exception { + DirContextHolder expectedContextHolder = new DirContextHolder(null, contextMock); + TransactionSynchronizationManager.bindResource(contextSourceMock, expectedContextHolder); + + tested.doCleanupAfterCompletion(new CompensatingTransactionObject(expectedContextHolder)); + + assertThat(TransactionSynchronizationManager.getResource(contextSourceMock)).isNull(); + assertThat(expectedContextHolder.getTransactionOperationManager()).isNull(); + verify(contextMock).close(); + } + + @Test + public void testSetContextSource_Proxy() { + TransactionAwareContextSourceProxy proxy = new TransactionAwareContextSourceProxy(contextSourceMock); + + // Perform test + tested.setContextSource(proxy); + ContextSource result = tested.getContextSource(); + + // Verify result + assertThat(result).isSameAs(contextSourceMock); + } + + @Test + public void testTransactionSuspension_UnconnectableDataSource() throws Exception { + Connection connectionMock = mock(Connection.class); + DataSource dataSourceMock = mock(DataSource.class); + + when(dataSourceMock.getConnection()).thenReturn(connectionMock); + when(connectionMock.getAutoCommit()).thenReturn(false); + + ContextSource unconnectableContextSourceMock = mock(ContextSource.class); + + UncategorizedLdapException connectException = new UncategorizedLdapException("dummy"); + when(unconnectableContextSourceMock.getReadWriteContext()).thenThrow(connectException); + + try { + // Create an outer transaction + final PlatformTransactionManager txMgrOuter = new DataSourceTransactionManager(dataSourceMock); + + final TransactionStatus txOuter = txMgrOuter.getTransaction(new DefaultTransactionDefinition()); + + try { + // Create inner transaction (not nested, though: unrelated data + // source) + final ContextSourceTransactionManager txMgrInner = new ContextSourceTransactionManager(); + txMgrInner.setContextSource(unconnectableContextSourceMock); + + final TransactionStatus txInner = txMgrInner.getTransaction(new DefaultTransactionDefinition( + TransactionDefinition.PROPAGATION_REQUIRES_NEW)); + + try { + // Do something with the connection that succeeds or fails + // (but we dont get this far) + // etc, etc... + + txMgrInner.commit(txInner); + } + catch (Exception e) { + txMgrInner.rollback(txInner); + throw e; + } + + txMgrOuter.commit(txOuter); + } + catch (Exception e) { + txMgrOuter.rollback(txOuter); + throw e; + } + + fail("Exception should be thrown"); + } + catch (CannotCreateTransactionException expected) { + assertThat(expected.getCause()).as("Should be thrown exception").isSameAs(connectException); + } + + 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 dfe7fb46..255c147c 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 @@ -1,83 +1,83 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.manager; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.core.DirContextProxy; - -import javax.naming.directory.DirContext; -import javax.naming.ldap.LdapContext; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -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 - public void setUp() throws Exception { - contextSourceMock = mock(ContextSource.class); - ldapContextMock = mock(LdapContext.class); - dirContextMock = mock(DirContext.class); - - tested = new TransactionAwareContextSourceProxy(contextSourceMock); - } - - @Test - public void testGetReadWriteContext_LdapContext() { - when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); - - DirContext result = tested.getReadWriteContext(); - - assertThat(result).isNotNull(); - assertThat(result instanceof LdapContext).isTrue(); - assertThat(result instanceof DirContextProxy).isTrue(); - } - - @Test - public void testGetReadWriteContext_DirContext() { - when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); - - DirContext result = tested.getReadWriteContext(); - - assertThat(result).as("Result should not be null").isNotNull(); - assertThat(result instanceof DirContext).isTrue(); - assertThat(result instanceof LdapContext).isFalse(); - assertThat(result instanceof DirContextProxy).isTrue(); - } - - @Test - public void testGetReadOnlyContext_LdapContext() { - when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); - - DirContext result = tested.getReadOnlyContext(); - - assertThat(result).as("Result should not be null").isNotNull(); - assertThat(result instanceof LdapContext).isTrue(); - assertThat(result instanceof DirContextProxy).isTrue(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.manager; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextProxy; + +import javax.naming.directory.DirContext; +import javax.naming.ldap.LdapContext; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +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 + public void setUp() throws Exception { + contextSourceMock = mock(ContextSource.class); + ldapContextMock = mock(LdapContext.class); + dirContextMock = mock(DirContext.class); + + tested = new TransactionAwareContextSourceProxy(contextSourceMock); + } + + @Test + public void testGetReadWriteContext_LdapContext() { + when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); + + DirContext result = tested.getReadWriteContext(); + + assertThat(result).isNotNull(); + assertThat(result instanceof LdapContext).isTrue(); + assertThat(result instanceof DirContextProxy).isTrue(); + } + + @Test + public void testGetReadWriteContext_DirContext() { + when(contextSourceMock.getReadWriteContext()).thenReturn(dirContextMock); + + DirContext result = tested.getReadWriteContext(); + + assertThat(result).as("Result should not be null").isNotNull(); + assertThat(result instanceof DirContext).isTrue(); + assertThat(result instanceof LdapContext).isFalse(); + assertThat(result instanceof DirContextProxy).isTrue(); + } + + @Test + public void testGetReadOnlyContext_LdapContext() { + when(contextSourceMock.getReadWriteContext()).thenReturn(ldapContextMock); + + DirContext result = tested.getReadOnlyContext(); + + assertThat(result).as("Result should not be null").isNotNull(); + 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 2e5b07d0..4c0cbc8e 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 @@ -1,77 +1,77 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.manager; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.core.ContextSource; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class TransactionAwareDirContextInvocationHandlerTest { - - private ContextSource contextSourceMock; - private DirContext dirContextMock; - private TransactionAwareDirContextInvocationHandler tested; - private DirContextHolder holder; - - @Before - public void setUp() throws Exception { - dirContextMock = mock(DirContext.class); - contextSourceMock = mock(ContextSource.class); - - holder = new DirContextHolder(null, dirContextMock); - tested = new TransactionAwareDirContextInvocationHandler(null, null); - } - - @Test - public void testDoCloseConnection_NoTransaction() throws NamingException { - tested.doCloseConnection(dirContextMock, contextSourceMock); - - verify(dirContextMock).close(); - } - - @Test - public void testDoCloseConnection_ActiveTransaction() - throws NamingException { - TransactionSynchronizationManager.bindResource(contextSourceMock, - holder); - - // Context should not be closed. - verifyNoMoreInteractions(dirContextMock); - - tested.doCloseConnection(dirContextMock, contextSourceMock); - } - - @Test - public void testDoCloseConnection_NotTransactionalContext() - throws NamingException { - TransactionSynchronizationManager.bindResource(contextSourceMock, - holder); - - DirContext dirContextMock2 = mock(DirContext.class); - - tested.doCloseConnection(dirContextMock2, contextSourceMock); - verify(dirContextMock2).close(); - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.manager; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.core.ContextSource; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +public class TransactionAwareDirContextInvocationHandlerTest { + + private ContextSource contextSourceMock; + private DirContext dirContextMock; + private TransactionAwareDirContextInvocationHandler tested; + private DirContextHolder holder; + + @Before + public void setUp() throws Exception { + dirContextMock = mock(DirContext.class); + contextSourceMock = mock(ContextSource.class); + + holder = new DirContextHolder(null, dirContextMock); + tested = new TransactionAwareDirContextInvocationHandler(null, null); + } + + @Test + public void testDoCloseConnection_NoTransaction() throws NamingException { + tested.doCloseConnection(dirContextMock, contextSourceMock); + + verify(dirContextMock).close(); + } + + @Test + public void testDoCloseConnection_ActiveTransaction() + throws NamingException { + TransactionSynchronizationManager.bindResource(contextSourceMock, + holder); + + // Context should not be closed. + verifyNoMoreInteractions(dirContextMock); + + tested.doCloseConnection(dirContextMock, contextSourceMock); + } + + @Test + public void testDoCloseConnection_NotTransactionalContext() + throws NamingException { + TransactionSynchronizationManager.bindResource(contextSourceMock, + holder); + + DirContext dirContextMock2 = mock(DirContext.class); + + tested.doCloseConnection(dirContextMock2, contextSourceMock); + verify(dirContextMock2).close(); + } + +} 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 fdfdc8bd..a3269db7 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 @@ -1,50 +1,50 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.support; - -import org.junit.Test; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.Name; -import javax.naming.ldap.LdapName; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DefaultTempEntryRenamingStrategyTest { - - @Test - public void testGetTemporaryName() { - LdapName expectedOriginalName = LdapUtils.newLdapName( - "cn=john doe, ou=somecompany, c=SE"); - DefaultTempEntryRenamingStrategy tested = new DefaultTempEntryRenamingStrategy(); - - Name result = tested.getTemporaryName(expectedOriginalName); - assertThat(result.toString()).isEqualTo("cn=john doe_temp,ou=somecompany,c=SE"); - assertThat(result).isNotSameAs(expectedOriginalName); - } - - @Test - public void testGetTemporaryDN_MultivalueDN() { - 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"); - } - - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.support; + +import org.junit.Test; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.Name; +import javax.naming.ldap.LdapName; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DefaultTempEntryRenamingStrategyTest { + + @Test + public void testGetTemporaryName() { + LdapName expectedOriginalName = LdapUtils.newLdapName( + "cn=john doe, ou=somecompany, c=SE"); + DefaultTempEntryRenamingStrategy tested = new DefaultTempEntryRenamingStrategy(); + + Name result = tested.getTemporaryName(expectedOriginalName); + assertThat(result.toString()).isEqualTo("cn=john doe_temp,ou=somecompany,c=SE"); + assertThat(result).isNotSameAs(expectedOriginalName); + } + + @Test + public void testGetTemporaryDN_MultivalueDN() { + 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 8bd9f805..97da30fd 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 @@ -1,43 +1,43 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.transaction.compensating.support; - -import org.junit.Test; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.Name; -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"); - DifferentSubtreeTempEntryRenamingStrategy tested = new DifferentSubtreeTempEntryRenamingStrategy( - LdapUtils.newLdapName("ou=tempEntries")); - - int nextSequenceNo = tested.getNextSequenceNo(); - - // Perform test - Name result = tested.getTemporaryName(originalName); - - // Verify result - assertThat(result.toString()).isEqualTo("cn=john doe" + nextSequenceNo + ",ou=tempEntries"); - } - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.transaction.compensating.support; + +import org.junit.Test; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.Name; +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"); + DifferentSubtreeTempEntryRenamingStrategy tested = new DifferentSubtreeTempEntryRenamingStrategy( + LdapUtils.newLdapName("ou=tempEntries")); + + int nextSequenceNo = tested.getNextSequenceNo(); + + // Perform test + Name result = tested.getTemporaryName(originalName); + + // Verify result + assertThat(result.toString()).isEqualTo("cn=john doe" + nextSequenceNo + ",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 93c87a83..9b870635 100644 --- a/core/src/test/java/org/springframework/ldap/util/ListComparatorTest.java +++ b/core/src/test/java/org/springframework/ldap/util/ListComparatorTest.java @@ -1,85 +1,85 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.util; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.support.ListComparator; - -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for ListComparator. - * - * @author Mattias Hellborg Arthursson - */ -public class ListComparatorTest { - - private ListComparator tested; - - @Before - public void setUp() throws Exception { - tested = new ListComparator(); - } - - @Test - public void testCompare_Equals() { - List list1 = Arrays.asList(0, 0); - List list2 = Arrays.asList(0, 0); - - int result = tested.compare(list1, list2); - assertThat(result).isEqualTo(0); - } - - @Test - public void testCompare_Less() { - List list1 = Arrays.asList(0, 0); - List list2 = Arrays.asList(0, 1); - - int result = tested.compare(list1, list2); - assertThat(result < 0).isTrue(); - } - - @Test - public void testCompare_Greater() { - List list1 = Arrays.asList(0, 1); - List list2 = Arrays.asList(0, 0); - - int result = tested.compare(list1, list2); - assertThat(result > 0).isTrue(); - } - - @Test - public void testCompare_Longer() { - List list1 = Arrays.asList(0, 0, 0); - List list2 = Arrays.asList(0, 0); - - int result = tested.compare(list1, list2); - assertThat(result > 0).isTrue(); - } - - @Test - public void testCompare_Shorter() { - List list1 = Arrays.asList(0, 0); - List list2 = Arrays.asList(0, 0, 0); - - int result = tested.compare(list1, list2); - assertThat(result < 0).isTrue(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.util; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.support.ListComparator; + +import java.util.Arrays; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for ListComparator. + * + * @author Mattias Hellborg Arthursson + */ +public class ListComparatorTest { + + private ListComparator tested; + + @Before + public void setUp() throws Exception { + tested = new ListComparator(); + } + + @Test + public void testCompare_Equals() { + List list1 = Arrays.asList(0, 0); + List list2 = Arrays.asList(0, 0); + + int result = tested.compare(list1, list2); + assertThat(result).isEqualTo(0); + } + + @Test + public void testCompare_Less() { + List list1 = Arrays.asList(0, 0); + List list2 = Arrays.asList(0, 1); + + int result = tested.compare(list1, list2); + assertThat(result < 0).isTrue(); + } + + @Test + public void testCompare_Greater() { + List list1 = Arrays.asList(0, 1); + List list2 = Arrays.asList(0, 0); + + int result = tested.compare(list1, list2); + assertThat(result > 0).isTrue(); + } + + @Test + public void testCompare_Longer() { + List list1 = Arrays.asList(0, 0, 0); + List list2 = Arrays.asList(0, 0); + + int result = tested.compare(list1, list2); + assertThat(result > 0).isTrue(); + } + + @Test + public void testCompare_Shorter() { + List list1 = Arrays.asList(0, 0); + List list2 = Arrays.asList(0, 0, 0); + + 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 13269f78..68575384 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 @@ -1,107 +1,107 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.transaction.compensating.support; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.transaction.TransactionSystemException; -import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; -import org.springframework.transaction.compensating.CompensatingTransactionOperationFactory; -import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; - -import java.util.Stack; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class DefaultCompensatingTransactionOperationManagerTest { - - private CompensatingTransactionOperationExecutor operationExecutorMock; - private CompensatingTransactionOperationFactory operationFactoryMock; - private CompensatingTransactionOperationRecorder operationRecorderMock; - - @Before - public void setUp() throws Exception { - operationExecutorMock = mock(CompensatingTransactionOperationExecutor.class); - operationFactoryMock = mock(CompensatingTransactionOperationFactory.class); - operationRecorderMock = mock(CompensatingTransactionOperationRecorder.class); - - } - - @Test - public void testPerformOperation() { - Object[] expectedArgs = new Object[0]; - Object expectedResource = new Object(); - - when(operationFactoryMock.createRecordingOperation(expectedResource, "some method")) - .thenReturn(operationRecorderMock); - when(operationRecorderMock.recordOperation(expectedArgs)).thenReturn(operationExecutorMock); - - DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( - operationFactoryMock); - tested.performOperation(expectedResource, "some method", expectedArgs); - verify(operationExecutorMock).performOperation(); - - Stack result = tested.getOperationExecutors(); - assertThat(result.isEmpty()).isFalse(); - assertThat(result.peek()).isSameAs(operationExecutorMock); - } - - @Test - public void testRollback() { - DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( - operationFactoryMock); - tested.getOperationExecutors().push(operationExecutorMock); - - tested.rollback(); - verify(operationExecutorMock).rollback(); - } - - @Test(expected = TransactionSystemException.class) - public void testRollback_Exception() { - DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( - operationFactoryMock); - tested.getOperationExecutors().push(operationExecutorMock); - - doThrow(new RuntimeException()).when(operationExecutorMock).rollback(); - - tested.rollback(); - } - - @Test - public void testCommit() { - DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( - operationFactoryMock); - tested.getOperationExecutors().push(operationExecutorMock); - - tested.commit(); - verify(operationExecutorMock).commit(); - } - - @Test(expected = TransactionSystemException.class) - public void testCommit_Exception() { - DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( - operationFactoryMock); - tested.getOperationExecutors().push(operationExecutorMock); - - doThrow(new RuntimeException()).when(operationExecutorMock).commit(); - - tested.commit(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.transaction.compensating.support; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.transaction.TransactionSystemException; +import org.springframework.transaction.compensating.CompensatingTransactionOperationExecutor; +import org.springframework.transaction.compensating.CompensatingTransactionOperationFactory; +import org.springframework.transaction.compensating.CompensatingTransactionOperationRecorder; + +import java.util.Stack; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class DefaultCompensatingTransactionOperationManagerTest { + + private CompensatingTransactionOperationExecutor operationExecutorMock; + private CompensatingTransactionOperationFactory operationFactoryMock; + private CompensatingTransactionOperationRecorder operationRecorderMock; + + @Before + public void setUp() throws Exception { + operationExecutorMock = mock(CompensatingTransactionOperationExecutor.class); + operationFactoryMock = mock(CompensatingTransactionOperationFactory.class); + operationRecorderMock = mock(CompensatingTransactionOperationRecorder.class); + + } + + @Test + public void testPerformOperation() { + Object[] expectedArgs = new Object[0]; + Object expectedResource = new Object(); + + when(operationFactoryMock.createRecordingOperation(expectedResource, "some method")) + .thenReturn(operationRecorderMock); + when(operationRecorderMock.recordOperation(expectedArgs)).thenReturn(operationExecutorMock); + + DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( + operationFactoryMock); + tested.performOperation(expectedResource, "some method", expectedArgs); + verify(operationExecutorMock).performOperation(); + + Stack result = tested.getOperationExecutors(); + assertThat(result.isEmpty()).isFalse(); + assertThat(result.peek()).isSameAs(operationExecutorMock); + } + + @Test + public void testRollback() { + DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( + operationFactoryMock); + tested.getOperationExecutors().push(operationExecutorMock); + + tested.rollback(); + verify(operationExecutorMock).rollback(); + } + + @Test(expected = TransactionSystemException.class) + public void testRollback_Exception() { + DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( + operationFactoryMock); + tested.getOperationExecutors().push(operationExecutorMock); + + doThrow(new RuntimeException()).when(operationExecutorMock).rollback(); + + tested.rollback(); + } + + @Test + public void testCommit() { + DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( + operationFactoryMock); + tested.getOperationExecutors().push(operationExecutorMock); + + tested.commit(); + verify(operationExecutorMock).commit(); + } + + @Test(expected = TransactionSystemException.class) + public void testCommit_Exception() { + DefaultCompensatingTransactionOperationManager tested = new DefaultCompensatingTransactionOperationManager( + operationFactoryMock); + tested.getOperationExecutors().push(operationExecutorMock); + + doThrow(new RuntimeException()).when(operationExecutorMock).commit(); + + 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 9c0bbc68..55956d54 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 @@ -1,52 +1,52 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.ldif; - -import org.springframework.ldap.NamingException; - -/** - * Thrown whenever a parsed attribute does not conform to LDAP specifications. - * - * @author Keith Barlow - * - */ -public class InvalidAttributeFormatException extends NamingException { - - private static final long serialVersionUID = -4529380160785322985L; - - /** - * @param msg - */ - public InvalidAttributeFormatException(String msg) { - super(msg); - } - - /** - * @param cause - */ - public InvalidAttributeFormatException(Throwable cause) { - super(cause); - } - - /** - * @param msg - * @param cause - */ - public InvalidAttributeFormatException(String msg, Throwable cause) { - super(msg, cause); - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.ldif; + +import org.springframework.ldap.NamingException; + +/** + * Thrown whenever a parsed attribute does not conform to LDAP specifications. + * + * @author Keith Barlow + * + */ +public class InvalidAttributeFormatException extends NamingException { + + private static final long serialVersionUID = -4529380160785322985L; + + /** + * @param msg + */ + public InvalidAttributeFormatException(String msg) { + super(msg); + } + + /** + * @param cause + */ + public InvalidAttributeFormatException(Throwable cause) { + super(cause); + } + + /** + * @param msg + * @param cause + */ + public InvalidAttributeFormatException(String msg, Throwable cause) { + super(msg, cause); + } + +} 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 a62bfa1b..5004df25 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 @@ -1,52 +1,52 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.ldif; - -import org.springframework.ldap.NamingException; - -/** - * Thrown whenever a parsed record does not conform to LDAP specifications. - * - * @author Keith Barlow - * - */ -public class InvalidRecordFormatException extends NamingException { - - private static final long serialVersionUID = -5047874723621065139L; - - /** - * @param msg - */ - public InvalidRecordFormatException(String msg) { - super(msg); - } - - /** - * @param cause - */ - public InvalidRecordFormatException(Throwable cause) { - super(cause); - } - - /** - * @param msg - * @param cause - */ - public InvalidRecordFormatException(String msg, Throwable cause) { - super(msg, cause); - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.ldif; + +import org.springframework.ldap.NamingException; + +/** + * Thrown whenever a parsed record does not conform to LDAP specifications. + * + * @author Keith Barlow + * + */ +public class InvalidRecordFormatException extends NamingException { + + private static final long serialVersionUID = -5047874723621065139L; + + /** + * @param msg + */ + public InvalidRecordFormatException(String msg) { + super(msg); + } + + /** + * @param cause + */ + public InvalidRecordFormatException(Throwable cause) { + super(cause); + } + + /** + * @param msg + * @param cause + */ + public InvalidRecordFormatException(String msg, Throwable cause) { + super(msg, cause); + } + +} 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 1dfb6439..c2cca318 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 @@ -1,89 +1,89 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.ldif.parser; - -import org.springframework.core.io.Resource; - -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. - * - * @author Keith Barlow - */ -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. - * - * @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. - */ - 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. - */ - 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; -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.ldif.parser; + +import org.springframework.core.io.Resource; + +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. + * + * @author Keith Barlow + */ +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. + * + * @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. + */ + 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. + */ + 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 dcc2f183..1958444b 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 @@ -1,36 +1,36 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.ldif.support; - -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); - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.ldif.support; + +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/LineIdentifier.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/ldif/support/LineIdentifier.java index 6a681bb9..881a1f71 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 @@ -1,69 +1,69 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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'. - */ - 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 -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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'. + */ + 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/schema/BasicSchemaSpecification.java b/ldif/ldif-core/src/main/java/org/springframework/ldap/schema/BasicSchemaSpecification.java index b35bff5c..cc11571c 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 @@ -1,64 +1,64 @@ -package org.springframework.ldap.schema; - -import org.springframework.ldap.core.LdapAttributes; -import org.springframework.ldap.support.LdapEncoder; - -import javax.naming.NamingException; -import javax.naming.ldap.LdapName; -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: - *

    - *
  • 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 - * - */ -public class BasicSchemaSpecification implements Specification { - - /** - * Determines if the policy is satisfied by the supplied LdapAttributes object. - * - * @throws NamingException - */ - public boolean isSatisfiedBy(LdapAttributes record) throws NamingException { - if (record != null) { - - //DN is required. - LdapName dn = record.getName(); - if (dn != null) { - - //objectClass definition is required. - if (record.get("objectClass") != null) { - - //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)) { - return true; - } - } 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; - } - } - } - } - } - - return false; - } - -} +package org.springframework.ldap.schema; + +import org.springframework.ldap.core.LdapAttributes; +import org.springframework.ldap.support.LdapEncoder; + +import javax.naming.NamingException; +import javax.naming.ldap.LdapName; +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: + *

    + *
  • 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 + * + */ +public class BasicSchemaSpecification implements Specification { + + /** + * Determines if the policy is satisfied by the supplied LdapAttributes object. + * + * @throws NamingException + */ + public boolean isSatisfiedBy(LdapAttributes record) throws NamingException { + if (record != null) { + + //DN is required. + LdapName dn = record.getName(); + if (dn != null) { + + //objectClass definition is required. + if (record.get("objectClass") != null) { + + //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)) { + return true; + } + } 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; + } + } + } + } + } + + 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 1dac42d7..ba617504 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 @@ -1,42 +1,42 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.schema; - -import javax.naming.NamingException; - -import org.springframework.ldap.core.LdapAttributes; - -/** - * DefaultSchemaSpecification does not validate objects at all - it simply returns true. - *

- * This specification is intended for cases where validation of the parsed entries is not - * required. - * - * @author Keith Barlow - * - */ -public class DefaultSchemaSpecification implements Specification { - - /** - * Determines if the policy is satisfied by the supplied LdapAttributes object. - * - * @throws NamingException - */ - public boolean isSatisfiedBy(LdapAttributes record) throws NamingException { - return true; - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.schema; + +import javax.naming.NamingException; + +import org.springframework.ldap.core.LdapAttributes; + +/** + * DefaultSchemaSpecification does not validate objects at all - it simply returns true. + *

+ * This specification is intended for cases where validation of the parsed entries is not + * required. + * + * @author Keith Barlow + * + */ +public class DefaultSchemaSpecification implements Specification { + + /** + * Determines if the policy is satisfied by the supplied LdapAttributes object. + * + * @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 af558b5e..e71a29b7 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 @@ -1,33 +1,33 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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 - * - * @param - */ -public interface Specification { - - boolean isSatisfiedBy(T record) throws NamingException; - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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 + * + * @param + */ +public interface Specification { + + boolean isSatisfiedBy(T record) throws NamingException; + +} 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 97461f53..f2c6e172 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 @@ -1,132 +1,132 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.core; - -import org.springframework.ldap.query.LdapQuery; - -import javax.naming.Name; -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. - *

- * Each managed Java class must be appropriately annotated using - * {@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 - */ -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. - * - * @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 - * - * @throws org.springframework.ldap.NamingException on error. - */ - List findAll(Class clazz, Name base, SearchControls searchControls); - - /** - * 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 - * - * @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 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. - */ - 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. - * - * @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); -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.core; + +import org.springframework.ldap.query.LdapQuery; + +import javax.naming.Name; +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. + *

+ * Each managed Java class must be appropriately annotated using + * {@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 + */ +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. + * + * @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 + * + * @throws org.springframework.ldap.NamingException on error. + */ + List findAll(Class clazz, Name base, SearchControls searchControls); + + /** + * 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 + * + * @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 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. + */ + 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. + * + * @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 2897d5da..80a626e2 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 @@ -1,145 +1,145 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.core.impl; - -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.filter.Filter; -import org.springframework.ldap.filter.HardcodedFilter; -import org.springframework.ldap.odm.core.OdmManager; -import org.springframework.ldap.odm.typeconversion.ConverterManager; -import org.springframework.ldap.query.LdapQuery; -import org.springframework.util.StringUtils; - -import javax.naming.Name; -import javax.naming.directory.SearchControls; -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. - * - * @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 - */ -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; - objectDirectoryMapper = new DefaultObjectDirectoryMapper(); - - if(converterManager != null) { - objectDirectoryMapper.setConverterManager(converterManager); - } - - if (managedClasses!=null) { - for (Class managedClass: managedClasses) { - addManagedClass(managedClass); - } - } - - this.ldapTemplate.setObjectDirectoryMapper(objectDirectoryMapper); - } - - public OdmManagerImpl(ConverterManager converterManager, - ContextSource contextSource, - Set> managedClasses) { - this(converterManager, new LdapTemplate(contextSource), managedClasses); - } - - 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) { - objectDirectoryMapper.manageClass(managedClass); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.ldap.odm.core.OdmManager#create(java.lang.Object) - */ - public T read(Class clazz, Name dn) { - return ldapTemplate.findByDn(dn, clazz); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.ldap.odm.core.OdmManager#create(java.lang.Object) - */ - public void create(Object entry) { - ldapTemplate.create(entry); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.ldap.odm.core.OdmManager#update(java.lang.Object, boolean) - */ - public void update(Object entry) { - ldapTemplate.update(entry); - } - - /* - * (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) - */ - public List search(Class managedClass, Name base, String filter, SearchControls scope) { - Filter searchFilter = null; - if(StringUtils.hasText(filter)) { - searchFilter = new HardcodedFilter(filter); - } - - return ldapTemplate.find(base, searchFilter, scope, managedClass); - } - - @Override - public List search(Class clazz, LdapQuery query) { - return ldapTemplate.find(query, clazz); - } - - public List findAll(Class managedClass, Name base, SearchControls scope) { - return ldapTemplate.findAll(base, scope, managedClass); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.core.impl; + +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.filter.Filter; +import org.springframework.ldap.filter.HardcodedFilter; +import org.springframework.ldap.odm.core.OdmManager; +import org.springframework.ldap.odm.typeconversion.ConverterManager; +import org.springframework.ldap.query.LdapQuery; +import org.springframework.util.StringUtils; + +import javax.naming.Name; +import javax.naming.directory.SearchControls; +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. + * + * @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 + */ +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; + objectDirectoryMapper = new DefaultObjectDirectoryMapper(); + + if(converterManager != null) { + objectDirectoryMapper.setConverterManager(converterManager); + } + + if (managedClasses!=null) { + for (Class managedClass: managedClasses) { + addManagedClass(managedClass); + } + } + + this.ldapTemplate.setObjectDirectoryMapper(objectDirectoryMapper); + } + + public OdmManagerImpl(ConverterManager converterManager, + ContextSource contextSource, + Set> managedClasses) { + this(converterManager, new LdapTemplate(contextSource), managedClasses); + } + + 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) { + objectDirectoryMapper.manageClass(managedClass); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.odm.core.OdmManager#create(java.lang.Object) + */ + public T read(Class clazz, Name dn) { + return ldapTemplate.findByDn(dn, clazz); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.odm.core.OdmManager#create(java.lang.Object) + */ + public void create(Object entry) { + ldapTemplate.create(entry); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.odm.core.OdmManager#update(java.lang.Object, boolean) + */ + public void update(Object entry) { + ldapTemplate.update(entry); + } + + /* + * (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) + */ + public List search(Class managedClass, Name base, String filter, SearchControls scope) { + Filter searchFilter = null; + if(StringUtils.hasText(filter)) { + searchFilter = new HardcodedFilter(filter); + } + + return ldapTemplate.find(base, searchFilter, scope, managedClass); + } + + @Override + public List search(Class clazz, LdapQuery query) { + return ldapTemplate.find(query, clazz); + } + + 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 41a773a5..1a2f41f2 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 @@ -1,118 +1,118 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.core.impl; - -import org.springframework.beans.factory.FactoryBean; -import org.springframework.beans.factory.FactoryBeanNotInitializedException; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.core.LdapOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.odm.typeconversion.ConverterManager; - -import java.util.Set; - -/** - * A Spring Factory bean which creates {@link OdmManagerImpl} instances. - *

- * 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" />
- *       <property name="managedClasses">
- *           <set>
- *               <value>org.myorg.myldapentries.Person</value>
- *               <value>org.myorg.myldapentries.OrganizationalUnit</value>
- *           </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 - */ -public final class OdmManagerImplFactoryBean implements FactoryBean { - private LdapOperations ldapOperations = 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) { - this.ldapOperations = ldapOperations; - } - - /** - * Set the ContextSource to use to interact with the LDAP directory. - * @param contextSource The ContextSource to use. - */ - 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. - * @param managedClasses The list of classes to manage. - */ - public void setManagedClasses(Set> managedClasses) { - this.managedClasses=managedClasses; - } - - /** - * 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; - } - - /* (non-Javadoc) - * @see org.springframework.beans.factory.FactoryBean#getObject() - */ - public Object getObject() throws Exception { - if (ldapOperations==null) { - throw new FactoryBeanNotInitializedException("contextSource ldapOperations property has not been set"); - } - if (managedClasses==null) { - throw new FactoryBeanNotInitializedException("managedClasses property has not been set"); - } - if (converterManager==null) { - throw new FactoryBeanNotInitializedException("converterManager property has not been set"); - } - - return new OdmManagerImpl(converterManager, ldapOperations, managedClasses); - } - - /* (non-Javadoc) - * @see org.springframework.beans.factory.FactoryBean#getObjectType() - */ - public Class getObjectType() { - return OdmManagerImpl.class; - } - - /* (non-Javadoc) - * @see org.springframework.beans.factory.FactoryBean#isSingleton() - */ - public boolean isSingleton() { - return true; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.core.impl; + +import org.springframework.beans.factory.FactoryBean; +import org.springframework.beans.factory.FactoryBeanNotInitializedException; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.LdapOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.odm.typeconversion.ConverterManager; + +import java.util.Set; + +/** + * A Spring Factory bean which creates {@link OdmManagerImpl} instances. + *

+ * 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" />
+ *       <property name="managedClasses">
+ *           <set>
+ *               <value>org.myorg.myldapentries.Person</value>
+ *               <value>org.myorg.myldapentries.OrganizationalUnit</value>
+ *           </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 + */ +public final class OdmManagerImplFactoryBean implements FactoryBean { + private LdapOperations ldapOperations = 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) { + this.ldapOperations = ldapOperations; + } + + /** + * Set the ContextSource to use to interact with the LDAP directory. + * @param contextSource The ContextSource to use. + */ + 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. + * @param managedClasses The list of classes to manage. + */ + public void setManagedClasses(Set> managedClasses) { + this.managedClasses=managedClasses; + } + + /** + * 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; + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObject() + */ + public Object getObject() throws Exception { + if (ldapOperations==null) { + throw new FactoryBeanNotInitializedException("contextSource ldapOperations property has not been set"); + } + if (managedClasses==null) { + throw new FactoryBeanNotInitializedException("managedClasses property has not been set"); + } + if (converterManager==null) { + throw new FactoryBeanNotInitializedException("converterManager property has not been set"); + } + + return new OdmManagerImpl(converterManager, ldapOperations, managedClasses); + } + + /* (non-Javadoc) + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ + public Class getObjectType() { + return OdmManagerImpl.class; + } + + /* (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 ec85a128..8a84ec8b 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 @@ -1,149 +1,149 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.tools; - -import org.springframework.util.StringUtils; - -/** - * 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; - - private final boolean isMultiValued; - - private final boolean isPrimitive; - - private final String scalarType; - - private final boolean isBinary; - - private final boolean isArray; - - public AttributeSchema(final String name, final String syntax, final boolean isMultiValued, - final boolean isPrimitive, final boolean isBinary, final boolean isArray, final String scalarType) { - this.name = name; - this.syntax = syntax; - this.isMultiValued = isMultiValued; - this.isPrimitive = isPrimitive; - this.scalarType = scalarType; - this.isBinary = isBinary; - this.isArray = isArray; - } - - public boolean getIsArray() { - return isArray; - } - - public boolean getIsBinary() { - return isBinary; - } - - public boolean getIsPrimitive() { - return isPrimitive; - } - - public String getScalarType() { - return scalarType; - } - - public String getName() { - return name; - } - - public String getJavaName() { - return StringUtils.replace(name, "-", ""); - } - - public String getSyntax() { - return syntax; - } - - public boolean getIsMultiValued() { - return isMultiValued; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - - return String.format( - "{ 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; - int result = 1; - result = prime * result + (isArray ? 1231 : 1237); - result = prime * result + (isBinary ? 1231 : 1237); - result = prime * result + (isMultiValued ? 1231 : 1237); - result = prime * result + (isPrimitive ? 1231 : 1237); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((scalarType == null) ? 0 : scalarType.hashCode()); - result = prime * result + ((syntax == null) ? 0 : syntax.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AttributeSchema other = (AttributeSchema) obj; - if (isArray != other.isArray) - return false; - if (isBinary != other.isBinary) - return false; - if (isMultiValued != other.isMultiValued) - return false; - if (isPrimitive != other.isPrimitive) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (scalarType == null) { - if (other.scalarType != null) - return false; - } else if (!scalarType.equals(other.scalarType)) - return false; - if (syntax == null) { - if (other.syntax != null) - return false; - } else if (!syntax.equals(other.syntax)) - return false; - return true; - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.tools; + +import org.springframework.util.StringUtils; + +/** + * 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; + + private final boolean isMultiValued; + + private final boolean isPrimitive; + + private final String scalarType; + + private final boolean isBinary; + + private final boolean isArray; + + public AttributeSchema(final String name, final String syntax, final boolean isMultiValued, + final boolean isPrimitive, final boolean isBinary, final boolean isArray, final String scalarType) { + this.name = name; + this.syntax = syntax; + this.isMultiValued = isMultiValued; + this.isPrimitive = isPrimitive; + this.scalarType = scalarType; + this.isBinary = isBinary; + this.isArray = isArray; + } + + public boolean getIsArray() { + return isArray; + } + + public boolean getIsBinary() { + return isBinary; + } + + public boolean getIsPrimitive() { + return isPrimitive; + } + + public String getScalarType() { + return scalarType; + } + + public String getName() { + return name; + } + + public String getJavaName() { + return StringUtils.replace(name, "-", ""); + } + + public String getSyntax() { + return syntax; + } + + public boolean getIsMultiValued() { + return isMultiValued; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + + return String.format( + "{ 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; + int result = 1; + result = prime * result + (isArray ? 1231 : 1237); + result = prime * result + (isBinary ? 1231 : 1237); + result = prime * result + (isMultiValued ? 1231 : 1237); + result = prime * result + (isPrimitive ? 1231 : 1237); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + ((scalarType == null) ? 0 : scalarType.hashCode()); + result = prime * result + ((syntax == null) ? 0 : syntax.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + AttributeSchema other = (AttributeSchema) obj; + if (isArray != other.isArray) + return false; + if (isBinary != other.isBinary) + return false; + if (isMultiValued != other.isMultiValued) + return false; + if (isPrimitive != other.isPrimitive) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (scalarType == null) { + if (other.scalarType != null) + return false; + } else if (!scalarType.equals(other.scalarType)) + return false; + if (syntax == null) { + if (other.syntax != null) + return false; + } 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 40b27045..0a56d859 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 @@ -1,114 +1,114 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.tools; - -import java.util.Collections; -import java.util.HashSet; -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(); - - private final Set objectClass = new HashSet(); - - public void addMust(AttributeSchema must) { - // if may attributes contain must attribute, remove from may and add to must - if (this.may.contains(must)) { - this.may.remove(must); - } - this.must.add(must); - } - - public void addMay(AttributeSchema may) { - // only add may if not in must - if (!this.must.contains(may)) { - this.may.add(may); - } - } - - public void addObjectClass(String objectClass) { - this.objectClass.add(objectClass); - } - - public Set getMust() { - return Collections.unmodifiableSet(must); - } - - public Set getMay() { - return Collections.unmodifiableSet(may); - } - - public Set getObjectClass() { - return Collections.unmodifiableSet(objectClass); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return String.format("objectClass=%1$s | must=%2$s | may=%3$s", objectClass, must, may); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((may == null) ? 0 : may.hashCode()); - result = prime * result + ((must == null) ? 0 : must.hashCode()); - result = prime * result + ((objectClass == null) ? 0 : objectClass.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ObjectSchema other = (ObjectSchema) obj; - if (may == null) { - if (other.may != null) - return false; - } else if (!may.equals(other.may)) - return false; - if (must == null) { - if (other.must != null) - return false; - } else if (!must.equals(other.must)) - return false; - if (objectClass == null) { - if (other.objectClass != null) - return false; - } else if (!objectClass.equals(other.objectClass)) - return false; - return true; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.tools; + +import java.util.Collections; +import java.util.HashSet; +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(); + + private final Set objectClass = new HashSet(); + + public void addMust(AttributeSchema must) { + // if may attributes contain must attribute, remove from may and add to must + if (this.may.contains(must)) { + this.may.remove(must); + } + this.must.add(must); + } + + public void addMay(AttributeSchema may) { + // only add may if not in must + if (!this.must.contains(may)) { + this.may.add(may); + } + } + + public void addObjectClass(String objectClass) { + this.objectClass.add(objectClass); + } + + public Set getMust() { + return Collections.unmodifiableSet(must); + } + + public Set getMay() { + return Collections.unmodifiableSet(may); + } + + public Set getObjectClass() { + return Collections.unmodifiableSet(objectClass); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format("objectClass=%1$s | must=%2$s | may=%3$s", objectClass, must, may); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((may == null) ? 0 : may.hashCode()); + result = prime * result + ((must == null) ? 0 : must.hashCode()); + result = prime * result + ((objectClass == null) ? 0 : objectClass.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ObjectSchema other = (ObjectSchema) obj; + if (may == null) { + if (other.may != null) + return false; + } else if (!may.equals(other.may)) + return false; + if (must == null) { + if (other.must != null) + return false; + } else if (!must.equals(other.must)) + return false; + if (objectClass == null) { + if (other.objectClass != null) + return false; + } 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 eb4ed7e9..6ab45f7c 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 @@ -1,186 +1,186 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.tools; - -import org.springframework.ldap.odm.tools.SyntaxToJavaClass.ClassInfo; - -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import java.util.HashSet; -import java.util.Set; - -// Processes LDAP Schema -/* package */ final class SchemaReader { - private final DirContext schemaContext; - - private final SyntaxToJavaClass syntaxToJavaClass; - - private final Set binarySet; - - public SchemaReader(DirContext schemaContext, SyntaxToJavaClass syntaxToJavaClass, Set binarySet) { - this.schemaContext = schemaContext; - this.syntaxToJavaClass = syntaxToJavaClass; - this.binarySet = binarySet; - } - - // Get the object schema for the given object classes - 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) { - SchemaAttributeType result = SchemaAttributeType.UNKNOWN; - - if (type.equals("SUP")) { - result = SchemaAttributeType.SUP; - } else { - if (type.equals("MUST")) { - result = SchemaAttributeType.MUST; - } else { - if (type.equals("MAY")) { - result = SchemaAttributeType.MAY; - } - } - } - return result; - } - - private AttributeSchema createAttributeSchema(String name, DirContext schemaContext) - throws NamingException, ClassNotFoundException { - - // Get the schema definition - Attributes attributeSchema = schemaContext.getAttributes("AttributeDefinition/" + name); - - String syntax = null; - while(syntax == null) { - Attribute syntaxAttribute = attributeSchema.get("SYNTAX"); - 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) { - // Well, at least we tried - throw new IllegalArgumentException("Unable to get syntax definition for attribute " + name); - } else { - attributeSchema = schemaContext.getAttributes("AttributeDefinition/" + supAttribute.get()); - } - } - } - - // Is it binary? - boolean isBinary=binarySet.contains(syntax); - - // Use it to look up the required Java class - ClassInfo classInfo = syntaxToJavaClass.getClassInfo(syntax); - - // Now we can set the java class - 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 (isBinary) { - 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); - } - - // Recursively extract schema from the directory and process it - private void createObjectClass(Set objectClasses, DirContext schemaContext, ObjectSchema schema) - throws NamingException, ClassNotFoundException { - - // Super classes - Set supList = new HashSet(); - - // For each of the given object classes - 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(); - - // Loop through each of the attributes - while (valuesEnumeration.hasMoreElements()) { - Attribute currentAttribute = valuesEnumeration.nextElement(); - - // 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(); - 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 - } - } - } - - // Recurse for super classes - createObjectClass(supList, schemaContext, schema); - } - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.tools; + +import org.springframework.ldap.odm.tools.SyntaxToJavaClass.ClassInfo; + +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import java.util.HashSet; +import java.util.Set; + +// Processes LDAP Schema +/* package */ final class SchemaReader { + private final DirContext schemaContext; + + private final SyntaxToJavaClass syntaxToJavaClass; + + private final Set binarySet; + + public SchemaReader(DirContext schemaContext, SyntaxToJavaClass syntaxToJavaClass, Set binarySet) { + this.schemaContext = schemaContext; + this.syntaxToJavaClass = syntaxToJavaClass; + this.binarySet = binarySet; + } + + // Get the object schema for the given object classes + 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) { + SchemaAttributeType result = SchemaAttributeType.UNKNOWN; + + if (type.equals("SUP")) { + result = SchemaAttributeType.SUP; + } else { + if (type.equals("MUST")) { + result = SchemaAttributeType.MUST; + } else { + if (type.equals("MAY")) { + result = SchemaAttributeType.MAY; + } + } + } + return result; + } + + private AttributeSchema createAttributeSchema(String name, DirContext schemaContext) + throws NamingException, ClassNotFoundException { + + // Get the schema definition + Attributes attributeSchema = schemaContext.getAttributes("AttributeDefinition/" + name); + + String syntax = null; + while(syntax == null) { + Attribute syntaxAttribute = attributeSchema.get("SYNTAX"); + 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) { + // Well, at least we tried + throw new IllegalArgumentException("Unable to get syntax definition for attribute " + name); + } else { + attributeSchema = schemaContext.getAttributes("AttributeDefinition/" + supAttribute.get()); + } + } + } + + // Is it binary? + boolean isBinary=binarySet.contains(syntax); + + // Use it to look up the required Java class + ClassInfo classInfo = syntaxToJavaClass.getClassInfo(syntax); + + // Now we can set the java class + 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 (isBinary) { + 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); + } + + // Recursively extract schema from the directory and process it + private void createObjectClass(Set objectClasses, DirContext schemaContext, ObjectSchema schema) + throws NamingException, ClassNotFoundException { + + // Super classes + Set supList = new HashSet(); + + // For each of the given object classes + 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(); + + // Loop through each of the attributes + while (valuesEnumeration.hasMoreElements()) { + Attribute currentAttribute = valuesEnumeration.nextElement(); + + // 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(); + 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 + } + } + } + + // Recurse for super classes + createObjectClass(supList, schemaContext, schema); + } + } +} 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 82a14800..ddba297b 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 @@ -1,239 +1,239 @@ -package org.springframework.ldap.odm.tools; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.CommandLineParser; -import org.apache.commons.cli.HelpFormatter; -import org.apache.commons.cli.Options; -import org.apache.commons.cli.ParseException; -import org.apache.commons.cli.PosixParser; - -import javax.naming.AuthenticationException; -import javax.naming.CommunicationException; -import javax.naming.Context; -import javax.naming.NameClassPair; -import javax.naming.NameNotFoundException; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; -import java.io.PrintStream; -import java.util.Hashtable; - -/** - * A simple utility to list LDAP directory schema. - *

- * 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
  • - *
- * - * 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 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"); - - private String shortName; - - private String longName; - - private Flag(String shortName, String longName) { - this.shortName = shortName; - this.longName = longName; - } - - public String getShort() { - return shortName; - } - - public String getLong() { - return longName; - } - - @Override - 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; - - private SchemaContext(String value) { - this.value = value; - } - - public String getValue() { - return value; - } - - @Override - 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.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, - "Attribute name or ? for all. Print attribute schema"); - DEFAULT_OPTIONS.addOption(Flag.SYNTAX.getShort(), Flag.SYNTAX.getLong(), true, - "Syntax OID or ? for all. Print attribute syntax"); - DEFAULT_OPTIONS.addOption(Flag.HELP.getShort(), Flag.HELP.getLong(), false, "Print this help message"); - DEFAULT_OPTIONS.addOption(Flag.ERROR.getShort(), Flag.ERROR.getLong(), false, "Send output to standard error"); - } - - /** - * Not to be instantiated. - */ - private SchemaViewer() { - - } - - private static void printAttrs(Attributes attrs) throws NamingException { - NamingEnumeration attrsEnum = attrs.getAll(); - while (attrsEnum.hasMore()) { - Attribute currentAttr = attrsEnum.next(); - outstream.print(String.format("%1$s:", currentAttr.getID())); - NamingEnumeration valuesEnum = currentAttr.getAll(); - while (valuesEnum.hasMoreElements()) { - outstream.print(String.format("%1$s ", valuesEnum.nextElement().toString())); - } - outstream.println(); - } - } - - private static void printObject(String contextName, String schemaName, DirContext schemaContext) - throws NameNotFoundException, NamingException { - - 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 { - - outstream.println(); - - NamingEnumeration schemaList = schemaContext.list(contextName); - - while (schemaList.hasMore()) { - NameClassPair ncp = schemaList.nextElement(); - - printObject(contextName, ncp.getName(), schemaContext); - outstream.println(); - } - - outstream.println(); - } - - private static void print(String optionValue, String contextName, DirContext schemaContext) - throws NameNotFoundException, NamingException { - - if (optionValue.equals(WILDCARD)) { - printSchema(contextName, schemaContext); - } else { - printObject(contextName, optionValue, schemaContext); - } - } - - private static PrintStream outstream=System.out; - private final static String WILDCARD = "?"; - - public static void main(String[] argv) { - CommandLineParser parser = new PosixParser(); - CommandLine cmd = null; - - try { - cmd = parser.parse(DEFAULT_OPTIONS, argv); - } catch (ParseException e) { - System.out.println(e.getMessage()); - System.exit(1); - } - - if (cmd.hasOption(Flag.HELP.getShort())) { - HelpFormatter formatter = new HelpFormatter(); - - formatter.printHelp(120, SchemaViewer.class.getSimpleName(), null, DEFAULT_OPTIONS, null, true); - System.exit(0); - } - - if (cmd.hasOption(Flag.ERROR.getShort())) { - 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(), ""); - - Hashtable env = new Hashtable(); - env.put(Context.PROVIDER_URL, url); - env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); - if (user != null) { - env.put(Context.SECURITY_PRINCIPAL, user); - } - if (pass != null) { - env.put(Context.SECURITY_CREDENTIALS, pass); - if (user == null) { - System.err.println("You must specify a user if you specify a password"); - System.exit(1); - } - } - - try { - DirContext context = new InitialDirContext(env); - DirContext schemaContext = context.getSchema(""); - - if (cmd.hasOption(Flag.OBJECTCLASS.getShort())) { - print(cmd.getOptionValue(Flag.OBJECTCLASS.getShort()), SchemaContext.OBJECTCLASS.getValue(), - schemaContext); - } - - if (cmd.hasOption(Flag.ATTRIBUTE.getShort())) { - print(cmd.getOptionValue(Flag.ATTRIBUTE.getShort()), SchemaContext.ATTRIBUTE.getValue(), schemaContext); - } - - if (cmd.hasOption(Flag.SYNTAX.getShort())) { - print(cmd.getOptionValue(Flag.SYNTAX.getShort()), SchemaContext.SYNTAX.getValue(), schemaContext); - } - - } catch (AuthenticationException e) { - System.err.println(String.format("Failed to bind to ldap server at %1$s", url)); - } catch (CommunicationException e) { - System.err.println(String.format("Failed to contact ldap server at %1$s", url)); - } catch (NameNotFoundException e) { - System.err.println(String.format("Can't find object %1$s", e.getMessage())); - } catch (NamingException e) { - System.err.println(e.toString()); - } - } -} +package org.springframework.ldap.odm.tools; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.HelpFormatter; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; +import org.apache.commons.cli.PosixParser; + +import javax.naming.AuthenticationException; +import javax.naming.CommunicationException; +import javax.naming.Context; +import javax.naming.NameClassPair; +import javax.naming.NameNotFoundException; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.InitialDirContext; +import java.io.PrintStream; +import java.util.Hashtable; + +/** + * A simple utility to list LDAP directory schema. + *

+ * 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
  • + *
+ * + * 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 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"); + + private String shortName; + + private String longName; + + private Flag(String shortName, String longName) { + this.shortName = shortName; + this.longName = longName; + } + + public String getShort() { + return shortName; + } + + public String getLong() { + return longName; + } + + @Override + 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; + + private SchemaContext(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + 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.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, + "Attribute name or ? for all. Print attribute schema"); + DEFAULT_OPTIONS.addOption(Flag.SYNTAX.getShort(), Flag.SYNTAX.getLong(), true, + "Syntax OID or ? for all. Print attribute syntax"); + DEFAULT_OPTIONS.addOption(Flag.HELP.getShort(), Flag.HELP.getLong(), false, "Print this help message"); + DEFAULT_OPTIONS.addOption(Flag.ERROR.getShort(), Flag.ERROR.getLong(), false, "Send output to standard error"); + } + + /** + * Not to be instantiated. + */ + private SchemaViewer() { + + } + + private static void printAttrs(Attributes attrs) throws NamingException { + NamingEnumeration attrsEnum = attrs.getAll(); + while (attrsEnum.hasMore()) { + Attribute currentAttr = attrsEnum.next(); + outstream.print(String.format("%1$s:", currentAttr.getID())); + NamingEnumeration valuesEnum = currentAttr.getAll(); + while (valuesEnum.hasMoreElements()) { + outstream.print(String.format("%1$s ", valuesEnum.nextElement().toString())); + } + outstream.println(); + } + } + + private static void printObject(String contextName, String schemaName, DirContext schemaContext) + throws NameNotFoundException, NamingException { + + 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 { + + outstream.println(); + + NamingEnumeration schemaList = schemaContext.list(contextName); + + while (schemaList.hasMore()) { + NameClassPair ncp = schemaList.nextElement(); + + printObject(contextName, ncp.getName(), schemaContext); + outstream.println(); + } + + outstream.println(); + } + + private static void print(String optionValue, String contextName, DirContext schemaContext) + throws NameNotFoundException, NamingException { + + if (optionValue.equals(WILDCARD)) { + printSchema(contextName, schemaContext); + } else { + printObject(contextName, optionValue, schemaContext); + } + } + + private static PrintStream outstream=System.out; + private final static String WILDCARD = "?"; + + public static void main(String[] argv) { + CommandLineParser parser = new PosixParser(); + CommandLine cmd = null; + + try { + cmd = parser.parse(DEFAULT_OPTIONS, argv); + } catch (ParseException e) { + System.out.println(e.getMessage()); + System.exit(1); + } + + if (cmd.hasOption(Flag.HELP.getShort())) { + HelpFormatter formatter = new HelpFormatter(); + + formatter.printHelp(120, SchemaViewer.class.getSimpleName(), null, DEFAULT_OPTIONS, null, true); + System.exit(0); + } + + if (cmd.hasOption(Flag.ERROR.getShort())) { + 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(), ""); + + Hashtable env = new Hashtable(); + env.put(Context.PROVIDER_URL, url); + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); + if (user != null) { + env.put(Context.SECURITY_PRINCIPAL, user); + } + if (pass != null) { + env.put(Context.SECURITY_CREDENTIALS, pass); + if (user == null) { + System.err.println("You must specify a user if you specify a password"); + System.exit(1); + } + } + + try { + DirContext context = new InitialDirContext(env); + DirContext schemaContext = context.getSchema(""); + + if (cmd.hasOption(Flag.OBJECTCLASS.getShort())) { + print(cmd.getOptionValue(Flag.OBJECTCLASS.getShort()), SchemaContext.OBJECTCLASS.getValue(), + schemaContext); + } + + if (cmd.hasOption(Flag.ATTRIBUTE.getShort())) { + print(cmd.getOptionValue(Flag.ATTRIBUTE.getShort()), SchemaContext.ATTRIBUTE.getValue(), schemaContext); + } + + if (cmd.hasOption(Flag.SYNTAX.getShort())) { + print(cmd.getOptionValue(Flag.SYNTAX.getShort()), SchemaContext.SYNTAX.getValue(), schemaContext); + } + + } catch (AuthenticationException e) { + System.err.println(String.format("Failed to bind to ldap server at %1$s", url)); + } catch (CommunicationException e) { + System.err.println(String.format("Failed to contact ldap server at %1$s", url)); + } catch (NameNotFoundException e) { + System.err.println(String.format("Can't find object %1$s", e.getMessage())); + } 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 9b132c0a..3bbc16d1 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 @@ -1,63 +1,63 @@ -package org.springframework.ldap.odm.tools; - -import java.util.HashMap; -import java.util.Map; -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; - - private ClassInfo(String className, String packageName) { - this.className = className; - this.packageName = packageName; - } - - public String getClassName() { - return className; - } - - public String getPackageName() { - return packageName; - } - - public String getFullClassName() { - StringBuilder result=new StringBuilder(); - if (packageName!=null) { - result.append(packageName).append(".").append(className); - } else { - result.append(className); - } - return result.toString(); - } - } - - private final Map mapSyntaxToClassInfo = new HashMap(); - - public SyntaxToJavaClass(Map mapSyntaxToClass) { - for (Entry syntaxAndClass : mapSyntaxToClass.entrySet()) { - String fullClassName = syntaxAndClass.getValue().trim(); - String packageName = null; - String className = null; - int lastDotIndex = fullClassName.lastIndexOf('.'); - if (lastDotIndex != -1) { - className = fullClassName.substring(lastDotIndex + 1); - packageName = fullClassName.substring(0, lastDotIndex); - } else { - className = fullClassName; - } - mapSyntaxToClassInfo.put(syntaxAndClass.getKey(), new ClassInfo(className, packageName)); - } - } - - public ClassInfo getClassInfo(String syntax) { - return mapSyntaxToClassInfo.get(syntax); - } -} +package org.springframework.ldap.odm.tools; + +import java.util.HashMap; +import java.util.Map; +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; + + private ClassInfo(String className, String packageName) { + this.className = className; + this.packageName = packageName; + } + + public String getClassName() { + return className; + } + + public String getPackageName() { + return packageName; + } + + public String getFullClassName() { + StringBuilder result=new StringBuilder(); + if (packageName!=null) { + result.append(packageName).append(".").append(className); + } else { + result.append(className); + } + return result.toString(); + } + } + + private final Map mapSyntaxToClassInfo = new HashMap(); + + public SyntaxToJavaClass(Map mapSyntaxToClass) { + for (Entry syntaxAndClass : mapSyntaxToClass.entrySet()) { + String fullClassName = syntaxAndClass.getValue().trim(); + String packageName = null; + String className = null; + int lastDotIndex = fullClassName.lastIndexOf('.'); + if (lastDotIndex != -1) { + className = fullClassName.substring(lastDotIndex + 1); + packageName = fullClassName.substring(0, lastDotIndex); + } else { + className = fullClassName; + } + mapSyntaxToClassInfo.put(syntaxAndClass.getKey(), new ClassInfo(className, packageName)); + } + } + + 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 570127c9..e065dbb1 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,8 +1,8 @@ -/** - * 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> - */ - +/** + * 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> + */ + package org.springframework.ldap.odm.tools; \ No newline at end of file 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 0d65894c..cf24c499 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 @@ -1,156 +1,156 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.test; - -import org.springframework.ldap.odm.annotations.Attribute; -import org.springframework.ldap.odm.annotations.Entry; -import org.springframework.ldap.odm.annotations.Id; - -import javax.naming.Name; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; - -/** - * Automatically generated to represent the LDAP object classes - * "organizationalunit", "top". - */ -@Entry(objectClasses = { "organizationalUnit", "top" }) -public final class OrganizationalUnit { - - @Id - private Name dn; - - @Attribute(name = "objectClass", syntax = "1.3.6.1.4.1.1466.115.121.1.38") - private List objectClass = new ArrayList(); - - @Attribute(name = "ou", syntax = "1.3.6.1.4.1.1466.115.121.1.15") - private String ou; - - @Attribute(name = "street", syntax = "1.3.6.1.4.1.1466.115.121.1.15") - private String street; - - @Attribute(name = "description", syntax = "1.3.6.1.4.1.1466.115.121.1.15") - private String description; - - public OrganizationalUnit() { - } - - public OrganizationalUnit(Name dn, String street, String description) { - this.dn = dn; - this.street = street; - this.description = description; - - objectClass.add("top"); - objectClass.add("organizationalUnit"); - - - int size = dn.size(); - if (size > 1) { - ou = dn.get(size - 1).split("=")[1]; - } else { - ou = ""; - } - - } - - public Name getDn() { - return dn; - } - - public void setDn(Name dn) { - this.dn = dn; - } - - public List getObjectClasses() { - return Collections.unmodifiableList(objectClass); - } - - public String getOu() { - return ou; - } - - public String getStreet() { - return street; - } - - public void setStreet(String street) { - this.street = street; - } - - public String getDescription() { - return description; - } - - @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); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((dn == null) ? 0 : dn.hashCode()); - result = prime * result + ((objectClass == null) ? 0 : new HashSet(objectClass).hashCode()); - result = prime * result + ((ou == null) ? 0 : ou.hashCode()); - result = prime * result + ((street == null) ? 0 : street.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - OrganizationalUnit other = (OrganizationalUnit) obj; - if (description == null) { - if (other.description != null) - return false; - } else if (!description.equals(other.description)) - return false; - if (dn == null) { - if (other.dn != null) - return false; - } 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; - if (ou == null) { - if (other.ou != null) - return false; - } else if (!ou.equals(other.ou)) - return false; - if (street == null) { - if (other.street != null) - return false; - } else if (!street.equals(other.street)) - return false; - return true; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.test; + +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.Entry; +import org.springframework.ldap.odm.annotations.Id; + +import javax.naming.Name; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + +/** + * Automatically generated to represent the LDAP object classes + * "organizationalunit", "top". + */ +@Entry(objectClasses = { "organizationalUnit", "top" }) +public final class OrganizationalUnit { + + @Id + private Name dn; + + @Attribute(name = "objectClass", syntax = "1.3.6.1.4.1.1466.115.121.1.38") + private List objectClass = new ArrayList(); + + @Attribute(name = "ou", syntax = "1.3.6.1.4.1.1466.115.121.1.15") + private String ou; + + @Attribute(name = "street", syntax = "1.3.6.1.4.1.1466.115.121.1.15") + private String street; + + @Attribute(name = "description", syntax = "1.3.6.1.4.1.1466.115.121.1.15") + private String description; + + public OrganizationalUnit() { + } + + public OrganizationalUnit(Name dn, String street, String description) { + this.dn = dn; + this.street = street; + this.description = description; + + objectClass.add("top"); + objectClass.add("organizationalUnit"); + + + int size = dn.size(); + if (size > 1) { + ou = dn.get(size - 1).split("=")[1]; + } else { + ou = ""; + } + + } + + public Name getDn() { + return dn; + } + + public void setDn(Name dn) { + this.dn = dn; + } + + public List getObjectClasses() { + return Collections.unmodifiableList(objectClass); + } + + public String getOu() { + return ou; + } + + public String getStreet() { + return street; + } + + public void setStreet(String street) { + this.street = street; + } + + public String getDescription() { + return description; + } + + @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); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((dn == null) ? 0 : dn.hashCode()); + result = prime * result + ((objectClass == null) ? 0 : new HashSet(objectClass).hashCode()); + result = prime * result + ((ou == null) ? 0 : ou.hashCode()); + result = prime * result + ((street == null) ? 0 : street.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + OrganizationalUnit other = (OrganizationalUnit) obj; + if (description == null) { + if (other.description != null) + return false; + } else if (!description.equals(other.description)) + return false; + if (dn == null) { + if (other.dn != null) + return false; + } 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; + if (ou == null) { + if (other.ou != null) + return false; + } else if (!ou.equals(other.ou)) + return false; + if (street == null) { + if (other.street != null) + return false; + } 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 e37c2abd..6185d5e7 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 @@ -1,216 +1,216 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.test; - -import org.springframework.ldap.odm.annotations.Attribute; -import org.springframework.ldap.odm.annotations.Attribute.Type; -import org.springframework.ldap.odm.annotations.Entry; -import org.springframework.ldap.odm.annotations.Id; -import org.springframework.ldap.odm.annotations.Transient; - -import javax.naming.Name; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; - -// 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) { - this.dn = dn; - this.surname = surname; - this.desc = desc; - this.telephoneNumber = telephoneNumber; - this.jpegPhoto = jpegPhoto; - objectClasses = new ArrayList(); - objectClasses.add("inetOrgPerson"); - objectClasses.add("organizationalPerson"); - objectClasses.add("person"); - objectClasses.add("top"); - int size = dn.size(); - if (size > 1) { - cn = dn.get(size - 1).split("=")[1]; - } else { - cn = ""; - } - } - - @Transient - private String someRandomField = null; - - @Transient - private List someRandomList = new ArrayList(); - - @Attribute(name = "objectClass") - private List objectClasses; - - @Id - private Name dn; - - // No annotation on purpose! - private String cn; - - @Attribute(name = "sn") - private String surname; - - // Everything should be sets and in search operations also as results can be in any order - @Attribute(name = "description") - private List desc; - - @Attribute - private int telephoneNumber; - - @Attribute(type = Type.BINARY) - byte[] jpegPhoto; - - public Name getDn() { - return dn; - } - - public void setDn(Name dn) { - this.dn = dn; - } - - public String getCn() { - return cn; - } - - public void setCn(String cn) { - this.cn = cn; - } - - public String getSurname() { - return surname; - } - - public void setSurname(String surname) { - this.surname = surname; - } - - public List getDesc() { - return desc; - } - - public void setDesc(List desc) { - this.desc = desc; - } - - public int getTelephoneNumber() { - return telephoneNumber; - } - - public void setTelephoneNumber(int telephoneNumber) { - this.telephoneNumber = telephoneNumber; - } - - public byte[] getJpegPhoto() { - return jpegPhoto; - } - - public void setJpegPhoto(byte[] jpegPhoto) { - this.jpegPhoto = jpegPhoto; - } - - public List getObjectClasses() { - return objectClasses; - } - - @Override - public String toString() { - 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); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((cn == null) ? 0 : cn.hashCode()); - result = prime * result + ((desc == null) ? 0 : new HashSet(desc).hashCode()); - result = prime * result + ((dn == null) ? 0 : dn.hashCode()); - result = prime * result + Arrays.hashCode(jpegPhoto); - result = prime * result + ((objectClasses == null) ? 0 : new HashSet(objectClasses).hashCode()); - result = prime * result + ((someRandomField == null) ? 0 : someRandomField.hashCode()); - result = prime * result + ((someRandomList == null) ? 0 : someRandomList.hashCode()); - result = prime * result + ((surname == null) ? 0 : surname.hashCode()); - result = prime * result + telephoneNumber; - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Person other = (Person) obj; - if (cn == null) { - if (other.cn != null) - return false; - } 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))) - return false; - if (dn == null) { - if (other.dn != null) - return false; - } 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))) - return false; - if (someRandomField == null) { - if (other.someRandomField != null) - return false; - } else if (!someRandomField.equals(other.someRandomField)) - return false; - if (someRandomList == null) { - if (other.someRandomList != null) - return false; - } else if (!someRandomList.equals(other.someRandomList)) - return false; - if (surname == null) { - if (other.surname != null) - return false; - } else if (!surname.equals(other.surname)) - return false; - if (telephoneNumber != other.telephoneNumber) - return false; - return true; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.test; + +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.Attribute.Type; +import org.springframework.ldap.odm.annotations.Entry; +import org.springframework.ldap.odm.annotations.Id; +import org.springframework.ldap.odm.annotations.Transient; + +import javax.naming.Name; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +// 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) { + this.dn = dn; + this.surname = surname; + this.desc = desc; + this.telephoneNumber = telephoneNumber; + this.jpegPhoto = jpegPhoto; + objectClasses = new ArrayList(); + objectClasses.add("inetOrgPerson"); + objectClasses.add("organizationalPerson"); + objectClasses.add("person"); + objectClasses.add("top"); + int size = dn.size(); + if (size > 1) { + cn = dn.get(size - 1).split("=")[1]; + } else { + cn = ""; + } + } + + @Transient + private String someRandomField = null; + + @Transient + private List someRandomList = new ArrayList(); + + @Attribute(name = "objectClass") + private List objectClasses; + + @Id + private Name dn; + + // No annotation on purpose! + private String cn; + + @Attribute(name = "sn") + private String surname; + + // Everything should be sets and in search operations also as results can be in any order + @Attribute(name = "description") + private List desc; + + @Attribute + private int telephoneNumber; + + @Attribute(type = Type.BINARY) + byte[] jpegPhoto; + + public Name getDn() { + return dn; + } + + public void setDn(Name dn) { + this.dn = dn; + } + + public String getCn() { + return cn; + } + + public void setCn(String cn) { + this.cn = cn; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } + + public List getDesc() { + return desc; + } + + public void setDesc(List desc) { + this.desc = desc; + } + + public int getTelephoneNumber() { + return telephoneNumber; + } + + public void setTelephoneNumber(int telephoneNumber) { + this.telephoneNumber = telephoneNumber; + } + + public byte[] getJpegPhoto() { + return jpegPhoto; + } + + public void setJpegPhoto(byte[] jpegPhoto) { + this.jpegPhoto = jpegPhoto; + } + + public List getObjectClasses() { + return objectClasses; + } + + @Override + public String toString() { + 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); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((cn == null) ? 0 : cn.hashCode()); + result = prime * result + ((desc == null) ? 0 : new HashSet(desc).hashCode()); + result = prime * result + ((dn == null) ? 0 : dn.hashCode()); + result = prime * result + Arrays.hashCode(jpegPhoto); + result = prime * result + ((objectClasses == null) ? 0 : new HashSet(objectClasses).hashCode()); + result = prime * result + ((someRandomField == null) ? 0 : someRandomField.hashCode()); + result = prime * result + ((someRandomList == null) ? 0 : someRandomList.hashCode()); + result = prime * result + ((surname == null) ? 0 : surname.hashCode()); + result = prime * result + telephoneNumber; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Person other = (Person) obj; + if (cn == null) { + if (other.cn != null) + return false; + } 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))) + return false; + if (dn == null) { + if (other.dn != null) + return false; + } 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))) + return false; + if (someRandomField == null) { + if (other.someRandomField != null) + return false; + } else if (!someRandomField.equals(other.someRandomField)) + return false; + if (someRandomList == null) { + if (other.someRandomList != null) + return false; + } else if (!someRandomList.equals(other.someRandomList)) + return false; + if (surname == null) { + if (other.surname != null) + return false; + } 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 04ce502b..f17f8d07 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 @@ -1,102 +1,102 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.test; - -import org.springframework.ldap.odm.annotations.Attribute; -import org.springframework.ldap.odm.annotations.Entry; -import org.springframework.ldap.odm.annotations.Id; - -import javax.naming.Name; -import java.util.ArrayList; -import java.util.List; - -// Simple LDAP entry for testing -@Entry(objectClasses = { "person", "top" }) -public final class PlainPerson { - public PlainPerson() { - } - - public PlainPerson(Name dn, String commonName, String surname) { - this.dn = dn; - this.surname = surname; - objectClasses = new ArrayList(); - objectClasses.add("top"); - objectClasses.add("person"); - cn = commonName; - } - - @Attribute(name = "objectClass") - private List objectClasses; - - @Id - private Name dn; - - @Attribute(name = "cn") - private String cn; - - @Attribute(name = "sn") - private String surname; - - public Name getDn() { - return dn; - } - - public void setDn(Name dn) { - this.dn = dn; - } - - public String getCn() { - return cn; - } - - public void setCn(String cn) { - this.cn = cn; - } - - public String getSurname() { - return surname; - } - - public void setSurname(String surname) { - this.surname = surname; - } - - @Override - public boolean equals(Object o) { - 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 (objectClasses != null ? !objectClasses.equals(that.objectClasses) : that.objectClasses != null) - return false; - if (surname != null ? !surname.equals(that.surname) : that.surname != null) return false; - - return true; - } - - @Override - public int hashCode() { - int result = objectClasses != null ? objectClasses.hashCode() : 0; - result = 31 * result + (dn != null ? dn.hashCode() : 0); - result = 31 * result + (cn != null ? cn.hashCode() : 0); - result = 31 * result + (surname != null ? surname.hashCode() : 0); - return result; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.test; + +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.Entry; +import org.springframework.ldap.odm.annotations.Id; + +import javax.naming.Name; +import java.util.ArrayList; +import java.util.List; + +// Simple LDAP entry for testing +@Entry(objectClasses = { "person", "top" }) +public final class PlainPerson { + public PlainPerson() { + } + + public PlainPerson(Name dn, String commonName, String surname) { + this.dn = dn; + this.surname = surname; + objectClasses = new ArrayList(); + objectClasses.add("top"); + objectClasses.add("person"); + cn = commonName; + } + + @Attribute(name = "objectClass") + private List objectClasses; + + @Id + private Name dn; + + @Attribute(name = "cn") + private String cn; + + @Attribute(name = "sn") + private String surname; + + public Name getDn() { + return dn; + } + + public void setDn(Name dn) { + this.dn = dn; + } + + public String getCn() { + return cn; + } + + public void setCn(String cn) { + this.cn = cn; + } + + public String getSurname() { + return surname; + } + + public void setSurname(String surname) { + this.surname = surname; + } + + @Override + public boolean equals(Object o) { + 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 (objectClasses != null ? !objectClasses.equals(that.objectClasses) : that.objectClasses != null) + return false; + if (surname != null ? !surname.equals(that.surname) : that.surname != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = objectClasses != null ? objectClasses.hashCode() : 0; + result = 31 * result + (dn != null ? dn.hashCode() : 0); + result = 31 * result + (cn != null ? cn.hashCode() : 0); + 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 7f88c1a3..850bd6a9 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 @@ -1,207 +1,207 @@ -package org.springframework.ldap.odm.test; - -import static org.junit.Assert.assertEquals; - -import java.net.URI; -import java.util.BitSet; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.ldap.odm.test.utils.ExecuteRunnable; -import org.springframework.ldap.odm.test.utils.RunnableTest; -import org.springframework.ldap.odm.typeconversion.ConverterException; -import org.springframework.ldap.odm.typeconversion.impl.Converter; -import org.springframework.ldap.odm.typeconversion.impl.ConverterManagerImpl; -import org.springframework.ldap.odm.typeconversion.impl.converters.FromStringConverter; -import org.springframework.ldap.odm.typeconversion.impl.converters.ToStringConverter; - -public final class TestConverterManager { - private ConverterManagerImpl converterManager; - - @Before - public void setUp() { - converterManager = new ConverterManagerImpl(); - - Converter ptc = new FromStringConverter(); - converterManager.addConverter(String.class, "", Byte.class, ptc); - converterManager.addConverter(String.class, "", Short.class, ptc); - converterManager.addConverter(String.class, "", Integer.class, ptc); - converterManager.addConverter(String.class, "", Long.class, ptc); - converterManager.addConverter(String.class, "", Double.class, ptc); - converterManager.addConverter(String.class, "", Float.class, ptc); - converterManager.addConverter(String.class, "", Boolean.class, ptc); - - Converter tsc = new ToStringConverter(); - converterManager.addConverter(Byte.class, "", String.class, tsc); - converterManager.addConverter(Short.class, "", String.class, tsc); - converterManager.addConverter(Integer.class, "", String.class, tsc); - converterManager.addConverter(Long.class, "", String.class, tsc); - converterManager.addConverter(Double.class, "", String.class, tsc); - converterManager.addConverter(Float.class, "", String.class, tsc); - converterManager.addConverter(Boolean.class, "", String.class, tsc); - - Converter uric = new UriConverter(); - converterManager.addConverter(URI.class, "", String.class, uric); - converterManager.addConverter(String.class, "", URI.class, uric); - } - - @After - public void tearDown() { - converterManager = null; - } - - private static class ConverterTestData { - public final Class destClass; - - public final Object sourceData; - - public final T expectedValue; - - public final String syntax; - - public ConverterTestData(Object sourceData, Class destClass, T expectedValue) { - this(sourceData, "", destClass, expectedValue); - } - - public ConverterTestData(Object sourceData, String syntax, Class destClass, T expectedValue) { - this.destClass = destClass; - this.sourceData = sourceData; - this.expectedValue = expectedValue; - this.syntax = syntax; - } - - @Override - public String toString() { - 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("123", Integer.class, Integer.valueOf(123)), - new ConverterTestData("-500", Integer.class, Integer.valueOf(-500)), - new ConverterTestData("123456", Long.class, Long.valueOf(123456)), - new ConverterTestData("-654321", Long.class, Long.valueOf(-654321)), - new ConverterTestData("2", Double.class, Double.valueOf(2)), - new ConverterTestData("-0.4", Double.class, Double.valueOf(-0.4)), - new ConverterTestData("666", Float.class, Float.valueOf(666)), - new ConverterTestData("-0.75", Float.class, Float.valueOf(-0.75F)), - new ConverterTestData("false", Boolean.class, Boolean.FALSE), - 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("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(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)); - } - }, 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); - } - else { - if (source.getClass() == Integer.class) { - intSource = (Integer)source; - } - } - - Integer result = null; - if (intSource != null) { - result = intSource * intSource; - } - - 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); - } - else { - if (source.getClass() == Integer.class) { - intSource = (Integer)source; - } - } - - Integer result = null; - if (intSource != null) { - result = intSource * intSource * intSource; - } - - return toClass.cast(result); - } - } - - // Tests using syntaxes for "finer grained" mapping - @Test - public void syntaxBasedConversion() throws Exception { - Converter squaredConverter = new SquaredConverter(); - converterManager.addConverter(String.class, "1", Integer.class, squaredConverter); - converterManager.addConverter(Integer.class, "1", Integer.class, squaredConverter); - Converter cubedConverter = new CubedConverter(); - converterManager.addConverter(String.class, "2", Integer.class, cubedConverter); - converterManager.addConverter(Integer.class, "3", Integer.class, cubedConverter); - - final ConverterTestData[] syntaxTests = new ConverterTestData[] { - new ConverterTestData("3", "", Integer.class, Integer.valueOf(3)), - new ConverterTestData("4", "", Integer.class, Integer.valueOf(4)), - new ConverterTestData(5, "", Integer.class, Integer.valueOf(5)), - new ConverterTestData(6, "", Integer.class, Integer.valueOf(6)), - new ConverterTestData("3", "1", Integer.class, Integer.valueOf(9)), - new ConverterTestData("4", "1", Integer.class, Integer.valueOf(16)), - new ConverterTestData(5, "1", Integer.class, Integer.valueOf(25)), - new ConverterTestData(6, "1", Integer.class, Integer.valueOf(36)), - new ConverterTestData("3", "2", Integer.class, Integer.valueOf(27)), - new ConverterTestData("4", "2", Integer.class, Integer.valueOf(64)), - new ConverterTestData(5, "3", Integer.class, Integer.valueOf(125)), - new ConverterTestData(6, "3", Integer.class, Integer.valueOf(216)), }; - - new ExecuteRunnable>().runTests(new RunnableTest>() { - public void runTest(ConverterTestData testData) { - assertEquals(testData.expectedValue, converterManager.convert(testData.sourceData, testData.syntax, - testData.destClass)); - } - }, syntaxTests); - - } - - // No converter for classes - @Test(expected = ConverterException.class) - public void noClassConverter() throws Exception { - converterManager.convert(BitSet.class, "", Integer.class); - } - - // Invalid syntax so converter fails - @Test(expected = ConverterException.class) - public void invalidSyntax() throws Exception { - converterManager.convert(String.class, "not a uri", URI.class); - } -} +package org.springframework.ldap.odm.test; + +import static org.junit.Assert.assertEquals; + +import java.net.URI; +import java.util.BitSet; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.ldap.odm.test.utils.ExecuteRunnable; +import org.springframework.ldap.odm.test.utils.RunnableTest; +import org.springframework.ldap.odm.typeconversion.ConverterException; +import org.springframework.ldap.odm.typeconversion.impl.Converter; +import org.springframework.ldap.odm.typeconversion.impl.ConverterManagerImpl; +import org.springframework.ldap.odm.typeconversion.impl.converters.FromStringConverter; +import org.springframework.ldap.odm.typeconversion.impl.converters.ToStringConverter; + +public final class TestConverterManager { + private ConverterManagerImpl converterManager; + + @Before + public void setUp() { + converterManager = new ConverterManagerImpl(); + + Converter ptc = new FromStringConverter(); + converterManager.addConverter(String.class, "", Byte.class, ptc); + converterManager.addConverter(String.class, "", Short.class, ptc); + converterManager.addConverter(String.class, "", Integer.class, ptc); + converterManager.addConverter(String.class, "", Long.class, ptc); + converterManager.addConverter(String.class, "", Double.class, ptc); + converterManager.addConverter(String.class, "", Float.class, ptc); + converterManager.addConverter(String.class, "", Boolean.class, ptc); + + Converter tsc = new ToStringConverter(); + converterManager.addConverter(Byte.class, "", String.class, tsc); + converterManager.addConverter(Short.class, "", String.class, tsc); + converterManager.addConverter(Integer.class, "", String.class, tsc); + converterManager.addConverter(Long.class, "", String.class, tsc); + converterManager.addConverter(Double.class, "", String.class, tsc); + converterManager.addConverter(Float.class, "", String.class, tsc); + converterManager.addConverter(Boolean.class, "", String.class, tsc); + + Converter uric = new UriConverter(); + converterManager.addConverter(URI.class, "", String.class, uric); + converterManager.addConverter(String.class, "", URI.class, uric); + } + + @After + public void tearDown() { + converterManager = null; + } + + private static class ConverterTestData { + public final Class destClass; + + public final Object sourceData; + + public final T expectedValue; + + public final String syntax; + + public ConverterTestData(Object sourceData, Class destClass, T expectedValue) { + this(sourceData, "", destClass, expectedValue); + } + + public ConverterTestData(Object sourceData, String syntax, Class destClass, T expectedValue) { + this.destClass = destClass; + this.sourceData = sourceData; + this.expectedValue = expectedValue; + this.syntax = syntax; + } + + @Override + public String toString() { + 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("123", Integer.class, Integer.valueOf(123)), + new ConverterTestData("-500", Integer.class, Integer.valueOf(-500)), + new ConverterTestData("123456", Long.class, Long.valueOf(123456)), + new ConverterTestData("-654321", Long.class, Long.valueOf(-654321)), + new ConverterTestData("2", Double.class, Double.valueOf(2)), + new ConverterTestData("-0.4", Double.class, Double.valueOf(-0.4)), + new ConverterTestData("666", Float.class, Float.valueOf(666)), + new ConverterTestData("-0.75", Float.class, Float.valueOf(-0.75F)), + new ConverterTestData("false", Boolean.class, Boolean.FALSE), + 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("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(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)); + } + }, 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); + } + else { + if (source.getClass() == Integer.class) { + intSource = (Integer)source; + } + } + + Integer result = null; + if (intSource != null) { + result = intSource * intSource; + } + + 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); + } + else { + if (source.getClass() == Integer.class) { + intSource = (Integer)source; + } + } + + Integer result = null; + if (intSource != null) { + result = intSource * intSource * intSource; + } + + return toClass.cast(result); + } + } + + // Tests using syntaxes for "finer grained" mapping + @Test + public void syntaxBasedConversion() throws Exception { + Converter squaredConverter = new SquaredConverter(); + converterManager.addConverter(String.class, "1", Integer.class, squaredConverter); + converterManager.addConverter(Integer.class, "1", Integer.class, squaredConverter); + Converter cubedConverter = new CubedConverter(); + converterManager.addConverter(String.class, "2", Integer.class, cubedConverter); + converterManager.addConverter(Integer.class, "3", Integer.class, cubedConverter); + + final ConverterTestData[] syntaxTests = new ConverterTestData[] { + new ConverterTestData("3", "", Integer.class, Integer.valueOf(3)), + new ConverterTestData("4", "", Integer.class, Integer.valueOf(4)), + new ConverterTestData(5, "", Integer.class, Integer.valueOf(5)), + new ConverterTestData(6, "", Integer.class, Integer.valueOf(6)), + new ConverterTestData("3", "1", Integer.class, Integer.valueOf(9)), + new ConverterTestData("4", "1", Integer.class, Integer.valueOf(16)), + new ConverterTestData(5, "1", Integer.class, Integer.valueOf(25)), + new ConverterTestData(6, "1", Integer.class, Integer.valueOf(36)), + new ConverterTestData("3", "2", Integer.class, Integer.valueOf(27)), + new ConverterTestData("4", "2", Integer.class, Integer.valueOf(64)), + new ConverterTestData(5, "3", Integer.class, Integer.valueOf(125)), + new ConverterTestData(6, "3", Integer.class, Integer.valueOf(216)), }; + + new ExecuteRunnable>().runTests(new RunnableTest>() { + public void runTest(ConverterTestData testData) { + assertEquals(testData.expectedValue, converterManager.convert(testData.sourceData, testData.syntax, + testData.destClass)); + } + }, syntaxTests); + + } + + // No converter for classes + @Test(expected = ConverterException.class) + public void noClassConverter() throws Exception { + converterManager.convert(BitSet.class, "", Integer.class); + } + + // Invalid syntax so converter fails + @Test(expected = ConverterException.class) + 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/TestManagerConverterFactory.java b/odm/src/test/java/org/springframework/ldap/odm/test/TestManagerConverterFactory.java index e375d96f..8e9ee54e 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 @@ -1,87 +1,87 @@ -package org.springframework.ldap.odm.test; - -import static org.junit.Assert.assertEquals; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -import org.junit.Test; -import org.springframework.ldap.odm.test.utils.ExecuteRunnable; -import org.springframework.ldap.odm.test.utils.RunnableTest; -import org.springframework.ldap.odm.typeconversion.ConverterManager; -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 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; - } - } - - 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; - } - } - - 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) - }; - - @Test - public void testConverterFactory() throws Exception { - 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))); - converterConfig.setConverter(nullConverter); - configList.add(converterConfig); - } - converterManagerFactory.setConverterConfig(configList); - final ConverterManager converterManager=(ConverterManager)converterManagerFactory.getObject(); - - new ExecuteRunnable().runTests(new RunnableTest() { - public void runTest(ConverterTestData testData) { - assertEquals(testData.canConvert, - converterManager.canConvert(testData.fromClass, testData.syntax, testData.toClass)); - } - }, converterTestData); - } -} +package org.springframework.ldap.odm.test; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +import org.junit.Test; +import org.springframework.ldap.odm.test.utils.ExecuteRunnable; +import org.springframework.ldap.odm.test.utils.RunnableTest; +import org.springframework.ldap.odm.typeconversion.ConverterManager; +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 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; + } + } + + 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; + } + } + + 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) + }; + + @Test + public void testConverterFactory() throws Exception { + 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))); + converterConfig.setConverter(nullConverter); + configList.add(converterConfig); + } + converterManagerFactory.setConverterConfig(configList); + final ConverterManager converterManager=(ConverterManager)converterManagerFactory.getObject(); + + new ExecuteRunnable().runTests(new RunnableTest() { + public void runTest(ConverterTestData testData) { + assertEquals(testData.canConvert, + converterManager.canConvert(testData.fromClass, testData.syntax, testData.toClass)); + } + }, converterTestData); + } +} 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 d9f706ef..97c0e893 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 @@ -1,136 +1,136 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.test; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.ldap.odm.test.utils.ExecuteRunnable; -import org.springframework.ldap.odm.test.utils.GetFreePort; -import org.springframework.ldap.odm.test.utils.RunnableTest; -import org.springframework.ldap.odm.tools.SchemaViewer; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.test.LdapTestUtils; - -import javax.naming.ldap.LdapName; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Arrays; -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 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"}; - - // Start an in process LDAP server - LdapTestUtils.startEmbeddedServer(port, baseName.toString(), "odm-test"); - } - - @AfterClass - public static void tearDownClass() throws Exception { - LdapTestUtils.shutdownEmbeddedServer(); - } - - @Before - public void setUp() throws Exception { - } - - @After - public void tearDown() throws Exception { - } - - private static String runSchemaViewer(String... flags) { - String result=null; - PrintStream originalOut=System.out; - ByteArrayOutputStream output = new ByteArrayOutputStream(); - try { - System.setErr(new PrintStream(output)); - - 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 { - 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 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); - assertEquals(testData.result, result); - } - }, viewerTestData); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.test; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.ldap.odm.test.utils.ExecuteRunnable; +import org.springframework.ldap.odm.test.utils.GetFreePort; +import org.springframework.ldap.odm.test.utils.RunnableTest; +import org.springframework.ldap.odm.tools.SchemaViewer; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.test.LdapTestUtils; + +import javax.naming.ldap.LdapName; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.Arrays; +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 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"}; + + // Start an in process LDAP server + LdapTestUtils.startEmbeddedServer(port, baseName.toString(), "odm-test"); + } + + @AfterClass + public static void tearDownClass() throws Exception { + LdapTestUtils.shutdownEmbeddedServer(); + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + private static String runSchemaViewer(String... flags) { + String result=null; + PrintStream originalOut=System.out; + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try { + System.setErr(new PrintStream(output)); + + 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 { + 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 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); + 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 0f150114..44430161 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 @@ -1,42 +1,42 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.odm.test; - -import jdepend.framework.JDepend; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; - -public class TestsWithJdepend { - private JDepend jdepend; - - @Before - public void setUp() throws IOException { - jdepend = new JDepend(); - jdepend.addDirectory("build/classes/java/main"); - } - - @Test - public void testAllPackages() { - jdepend.analyze(); - assertEquals(false, jdepend.containsCycles()); - } - -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.odm.test; + +import jdepend.framework.JDepend; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; + +import static org.junit.Assert.assertEquals; + +public class TestsWithJdepend { + private JDepend jdepend; + + @Before + public void setUp() throws IOException { + jdepend = new JDepend(); + jdepend.addDirectory("build/classes/java/main"); + } + + @Test + public void testAllPackages() { + jdepend.analyze(); + assertEquals(false, jdepend.containsCycles()); + } + +} 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 2922989a..c7a5dfaf 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 @@ -1,29 +1,29 @@ -package org.springframework.ldap.odm.test; - -import java.net.URI; - -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) - */ - 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 { - if (URI.class.isAssignableFrom(source.getClass()) && toClass == String.class) { - result = toClass.cast(source.toString()); - } - } - - return result; - } -} +package org.springframework.ldap.odm.test; + +import java.net.URI; + +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) + */ + 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 { + if (URI.class.isAssignableFrom(source.getClass()) && toClass == String.class) { + result = toClass.cast(source.toString()); + } + } + + 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 afb27d2a..d836ed41 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 @@ -1,24 +1,24 @@ -package org.springframework.ldap.odm.test.utils; - -import java.io.File; -import java.util.Arrays; - -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; -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)); - compiler.getTask(null, fileManager, null, null, null, javaFileObjects).call(); - - fileManager.close(); - } -} +package org.springframework.ldap.odm.test.utils; + +import java.io.File; +import java.util.Arrays; + +import javax.tools.JavaCompiler; +import javax.tools.JavaFileObject; +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)); + compiler.getTask(null, fileManager, null, null, null, javaFileObjects).call(); + + fileManager.close(); + } +} 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 3e7c6130..0c5edec4 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 @@ -1,6 +1,6 @@ -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; -} +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/samples/odm/src/main/java/org/springframework/ldap/samples/odm/dao/OdmPersonDaoImpl.java b/samples/odm/src/main/java/org/springframework/ldap/samples/odm/dao/OdmPersonDaoImpl.java index ddf1f62a..a4d629bf 100644 --- a/samples/odm/src/main/java/org/springframework/ldap/samples/odm/dao/OdmPersonDaoImpl.java +++ b/samples/odm/src/main/java/org/springframework/ldap/samples/odm/dao/OdmPersonDaoImpl.java @@ -1,97 +1,97 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.samples.odm.dao; - -import org.springframework.ldap.core.AttributesMapper; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.samples.plain.dao.PersonDao; -import org.springframework.ldap.samples.plain.domain.Person; -import org.springframework.ldap.support.LdapNameBuilder; - -import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import javax.naming.ldap.LdapName; -import java.util.List; - -import static org.springframework.ldap.query.LdapQueryBuilder.query; - -/** - * Default implementation of PersonDao. This implementation uses the Object-Directory Mapping feature, - * which requires the entity classes to be annotated, but relieves the programmer from the tedious - * task of mapping to and from entity objects, using attribute or dn component values. - * - * @author Mattias Hellborg Arthursson - */ -public class OdmPersonDaoImpl implements PersonDao { - - private LdapTemplate ldapTemplate; - - @Override - public void create(Person person) { - ldapTemplate.create(person); - } - - @Override - public void update(Person person) { - ldapTemplate.update(person); - } - - @Override - public void delete(Person person) { - ldapTemplate.delete(ldapTemplate.findByDn(buildDn(person), Person.class)); - } - - @Override - public List getAllPersonNames() { - return ldapTemplate.search(query() - .attributes("cn") - .where("objectclass").is("person"), - new AttributesMapper() { - public String mapFromAttributes(Attributes attrs) throws NamingException { - return attrs.get("cn").get().toString(); - } - }); - } - - @Override - public List findAll() { - return ldapTemplate.findAll(Person.class); - } - - @Override - public Person findByPrimaryKey(String country, String company, String fullname) { - LdapName dn = buildDn(country, company, fullname); - Person person = ldapTemplate.findByDn(dn, Person.class); - - return person; - } - - private LdapName buildDn(Person person) { - return buildDn(person.getCountry(), person.getCompany(), person.getFullName()); - } - - private LdapName buildDn(String country, String company, String fullname) { - return LdapNameBuilder.newInstance() - .add("c", country) - .add("ou", company) - .add("cn", fullname) - .build(); - } - - public void setLdapTemplate(LdapTemplate ldapTemplate) { - this.ldapTemplate = ldapTemplate; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.samples.odm.dao; + +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.samples.plain.dao.PersonDao; +import org.springframework.ldap.samples.plain.domain.Person; +import org.springframework.ldap.support.LdapNameBuilder; + +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import javax.naming.ldap.LdapName; +import java.util.List; + +import static org.springframework.ldap.query.LdapQueryBuilder.query; + +/** + * Default implementation of PersonDao. This implementation uses the Object-Directory Mapping feature, + * which requires the entity classes to be annotated, but relieves the programmer from the tedious + * task of mapping to and from entity objects, using attribute or dn component values. + * + * @author Mattias Hellborg Arthursson + */ +public class OdmPersonDaoImpl implements PersonDao { + + private LdapTemplate ldapTemplate; + + @Override + public void create(Person person) { + ldapTemplate.create(person); + } + + @Override + public void update(Person person) { + ldapTemplate.update(person); + } + + @Override + public void delete(Person person) { + ldapTemplate.delete(ldapTemplate.findByDn(buildDn(person), Person.class)); + } + + @Override + public List getAllPersonNames() { + return ldapTemplate.search(query() + .attributes("cn") + .where("objectclass").is("person"), + new AttributesMapper() { + public String mapFromAttributes(Attributes attrs) throws NamingException { + return attrs.get("cn").get().toString(); + } + }); + } + + @Override + public List findAll() { + return ldapTemplate.findAll(Person.class); + } + + @Override + public Person findByPrimaryKey(String country, String company, String fullname) { + LdapName dn = buildDn(country, company, fullname); + Person person = ldapTemplate.findByDn(dn, Person.class); + + return person; + } + + private LdapName buildDn(Person person) { + return buildDn(person.getCountry(), person.getCompany(), person.getFullName()); + } + + private LdapName buildDn(String country, String company, String fullname) { + return LdapNameBuilder.newInstance() + .add("c", country) + .add("ou", company) + .add("cn", fullname) + .build(); + } + + public void setLdapTemplate(LdapTemplate ldapTemplate) { + this.ldapTemplate = ldapTemplate; + } +} diff --git a/samples/odm/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDao.java b/samples/odm/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDao.java index d1236b5a..ed637a57 100644 --- a/samples/odm/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDao.java +++ b/samples/odm/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDao.java @@ -1,41 +1,41 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.samples.plain.dao; - -import org.springframework.ldap.samples.plain.domain.Person; - -import java.util.List; - - -/** - * Data Access Object interface for the Person entity. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public interface PersonDao { - void create(Person person); - - void update(Person person); - - void delete(Person person); - - List getAllPersonNames(); - - List findAll(); - - Person findByPrimaryKey(String country, String company, String fullname); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.samples.plain.dao; + +import org.springframework.ldap.samples.plain.domain.Person; + +import java.util.List; + + +/** + * Data Access Object interface for the Person entity. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public interface PersonDao { + void create(Person person); + + void update(Person person); + + void delete(Person person); + + List getAllPersonNames(); + + List findAll(); + + Person findByPrimaryKey(String country, String company, String fullname); +} diff --git a/samples/odm/src/main/java/org/springframework/ldap/samples/plain/domain/Person.java b/samples/odm/src/main/java/org/springframework/ldap/samples/plain/domain/Person.java index 37c8ebc2..a9b3484d 100644 --- a/samples/odm/src/main/java/org/springframework/ldap/samples/plain/domain/Person.java +++ b/samples/odm/src/main/java/org/springframework/ldap/samples/plain/domain/Person.java @@ -1,132 +1,132 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.samples.plain.domain; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -import org.apache.commons.lang.builder.ToStringStyle; -import org.springframework.ldap.odm.annotations.Attribute; -import org.springframework.ldap.odm.annotations.DnAttribute; -import org.springframework.ldap.odm.annotations.Entry; -import org.springframework.ldap.odm.annotations.Id; -import org.springframework.ldap.odm.annotations.Transient; - -import javax.naming.Name; - -/** - * Simple class representing a single person. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -@Entry(objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top"}) -public class Person { - @Id - private Name dn; - - @Attribute(name = "cn") - @DnAttribute(value = "cn", index = 2) - private String fullName; - - @Attribute(name = "sn") - private String lastName; - - @Attribute(name = "description") - private String description; - - @Transient - @DnAttribute(value = "c", index = 0) - private String country; - - @Transient - @DnAttribute(value = "ou", index = 1) - private String company; - - @Attribute(name = "telephoneNumber") - private String phone; - - public Name getDn() { - return dn; - } - - public void setDn(Name dn) { - this.dn = dn; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getFullName() { - return fullName; - } - - public void setFullName(String fullName) { - this.fullName = fullName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getCompany() { - return company; - } - - public void setCompany(String company) { - this.company = company; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - 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); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.samples.plain.domain; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; +import org.apache.commons.lang.builder.ToStringStyle; +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.DnAttribute; +import org.springframework.ldap.odm.annotations.Entry; +import org.springframework.ldap.odm.annotations.Id; +import org.springframework.ldap.odm.annotations.Transient; + +import javax.naming.Name; + +/** + * Simple class representing a single person. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +@Entry(objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top"}) +public class Person { + @Id + private Name dn; + + @Attribute(name = "cn") + @DnAttribute(value = "cn", index = 2) + private String fullName; + + @Attribute(name = "sn") + private String lastName; + + @Attribute(name = "description") + private String description; + + @Transient + @DnAttribute(value = "c", index = 0) + private String country; + + @Transient + @DnAttribute(value = "ou", index = 1) + private String company; + + @Attribute(name = "telephoneNumber") + private String phone; + + public Name getDn() { + return dn; + } + + public void setDn(Name dn) { + this.dn = dn; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + 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); + } +} diff --git a/samples/plain/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDao.java b/samples/plain/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDao.java index d1236b5a..ed637a57 100644 --- a/samples/plain/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDao.java +++ b/samples/plain/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDao.java @@ -1,41 +1,41 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.samples.plain.dao; - -import org.springframework.ldap.samples.plain.domain.Person; - -import java.util.List; - - -/** - * Data Access Object interface for the Person entity. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public interface PersonDao { - void create(Person person); - - void update(Person person); - - void delete(Person person); - - List getAllPersonNames(); - - List findAll(); - - Person findByPrimaryKey(String country, String company, String fullname); -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.samples.plain.dao; + +import org.springframework.ldap.samples.plain.domain.Person; + +import java.util.List; + + +/** + * Data Access Object interface for the Person entity. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public interface PersonDao { + void create(Person person); + + void update(Person person); + + void delete(Person person); + + List getAllPersonNames(); + + List findAll(); + + Person findByPrimaryKey(String country, String company, String fullname); +} diff --git a/samples/plain/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDaoImpl.java b/samples/plain/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDaoImpl.java index 237ad967..96afb688 100644 --- a/samples/plain/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDaoImpl.java +++ b/samples/plain/src/main/java/org/springframework/ldap/samples/plain/dao/PersonDaoImpl.java @@ -1,147 +1,147 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.samples.plain.dao; - -import org.springframework.ldap.core.AttributesMapper; -import org.springframework.ldap.core.ContextMapper; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.support.AbstractContextMapper; -import org.springframework.ldap.samples.plain.domain.Person; -import org.springframework.ldap.support.LdapNameBuilder; -import org.springframework.ldap.support.LdapUtils; - -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import javax.naming.ldap.LdapName; -import java.util.List; - -import static org.springframework.ldap.query.LdapQueryBuilder.query; - -/** - * Default implementation of PersonDao. This implementation uses - * DirContextAdapter for managing attribute values. We use a ContextMapper - * to map from the found contexts to our domain objects. This is especially useful - * since we in this case have properties in our domain objects that depend on parts of the DN. - * - * We could have worked with Attributes and an AttributesMapper implementation - * instead, but working with Attributes is a bore and also, working with - * AttributesMapper objects (or, indeed Attributes) does not give us access to - * the distinguished name. However, we do use it in one method that only needs a - * single attribute: {@link #getAllPersonNames()}. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -public class PersonDaoImpl implements PersonDao { - - private LdapTemplate ldapTemplate; - - @Override - public void create(Person person) { - Name dn = buildDn(person); - DirContextAdapter context = new DirContextAdapter(dn); - mapToContext(person, context); - ldapTemplate.bind(dn, context, null); - } - - @Override - public void update(Person person) { - Name dn = buildDn(person); - DirContextAdapter context = (DirContextAdapter) ldapTemplate.lookup(dn); - mapToContext(person, context); - ldapTemplate.modifyAttributes(dn, context.getModificationItems()); - } - - @Override - public void delete(Person person) { - ldapTemplate.unbind(buildDn(person)); - } - - @Override - public List getAllPersonNames() { - return ldapTemplate.search(query() - .attributes("cn") - .where("objectclass").is("person"), - new AttributesMapper() { - public String mapFromAttributes(Attributes attrs) throws NamingException { - return attrs.get("cn").get().toString(); - } - }); - } - - @Override - public List findAll() { - return ldapTemplate.search(query() - .where("objectclass").is("person"), - PERSON_CONTEXT_MAPPER); - } - - @Override - public Person findByPrimaryKey(String country, String company, String fullname) { - LdapName dn = buildDn(country, company, fullname); - return ldapTemplate.lookup(dn, PERSON_CONTEXT_MAPPER); - } - - private LdapName buildDn(Person person) { - return buildDn(person.getCountry(), person.getCompany(), person.getFullName()); - } - - private LdapName buildDn(String country, String company, String fullname) { - return LdapNameBuilder.newInstance() - .add("c", country) - .add("ou", company) - .add("cn", fullname) - .build(); - } - - private void mapToContext(Person person, DirContextAdapter context) { - context.setAttributeValues("objectclass", new String[] { "top", "person" }); - context.setAttributeValue("cn", person.getFullName()); - context.setAttributeValue("sn", person.getLastName()); - context.setAttributeValue("description", person.getDescription()); - context.setAttributeValue("telephoneNumber", person.getPhone()); - } - - /** - * Maps from DirContextAdapter to Person objects. A DN for a person will be - * of the form cn=[fullname],ou=[company],c=[country], so - * the values of these attributes must be extracted from the DN. For this, - * we use the LdapName along with utility methods in LdapUtils. - */ - private final static ContextMapper PERSON_CONTEXT_MAPPER = new AbstractContextMapper() { - @Override - public Person doMapFromContext(DirContextOperations context) { - Person person = new Person(); - - LdapName dn = LdapUtils.newLdapName(context.getDn()); - person.setCountry(LdapUtils.getStringValue(dn, 0)); - person.setCompany(LdapUtils.getStringValue(dn, 1)); - person.setFullName(context.getStringAttribute("cn")); - person.setLastName(context.getStringAttribute("sn")); - person.setDescription(context.getStringAttribute("description")); - person.setPhone(context.getStringAttribute("telephoneNumber")); - - return person; - } - }; - - public void setLdapTemplate(LdapTemplate ldapTemplate) { - this.ldapTemplate = ldapTemplate; - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.samples.plain.dao; + +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.ContextMapper; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.support.AbstractContextMapper; +import org.springframework.ldap.samples.plain.domain.Person; +import org.springframework.ldap.support.LdapNameBuilder; +import org.springframework.ldap.support.LdapUtils; + +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import javax.naming.ldap.LdapName; +import java.util.List; + +import static org.springframework.ldap.query.LdapQueryBuilder.query; + +/** + * Default implementation of PersonDao. This implementation uses + * DirContextAdapter for managing attribute values. We use a ContextMapper + * to map from the found contexts to our domain objects. This is especially useful + * since we in this case have properties in our domain objects that depend on parts of the DN. + * + * We could have worked with Attributes and an AttributesMapper implementation + * instead, but working with Attributes is a bore and also, working with + * AttributesMapper objects (or, indeed Attributes) does not give us access to + * the distinguished name. However, we do use it in one method that only needs a + * single attribute: {@link #getAllPersonNames()}. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +public class PersonDaoImpl implements PersonDao { + + private LdapTemplate ldapTemplate; + + @Override + public void create(Person person) { + Name dn = buildDn(person); + DirContextAdapter context = new DirContextAdapter(dn); + mapToContext(person, context); + ldapTemplate.bind(dn, context, null); + } + + @Override + public void update(Person person) { + Name dn = buildDn(person); + DirContextAdapter context = (DirContextAdapter) ldapTemplate.lookup(dn); + mapToContext(person, context); + ldapTemplate.modifyAttributes(dn, context.getModificationItems()); + } + + @Override + public void delete(Person person) { + ldapTemplate.unbind(buildDn(person)); + } + + @Override + public List getAllPersonNames() { + return ldapTemplate.search(query() + .attributes("cn") + .where("objectclass").is("person"), + new AttributesMapper() { + public String mapFromAttributes(Attributes attrs) throws NamingException { + return attrs.get("cn").get().toString(); + } + }); + } + + @Override + public List findAll() { + return ldapTemplate.search(query() + .where("objectclass").is("person"), + PERSON_CONTEXT_MAPPER); + } + + @Override + public Person findByPrimaryKey(String country, String company, String fullname) { + LdapName dn = buildDn(country, company, fullname); + return ldapTemplate.lookup(dn, PERSON_CONTEXT_MAPPER); + } + + private LdapName buildDn(Person person) { + return buildDn(person.getCountry(), person.getCompany(), person.getFullName()); + } + + private LdapName buildDn(String country, String company, String fullname) { + return LdapNameBuilder.newInstance() + .add("c", country) + .add("ou", company) + .add("cn", fullname) + .build(); + } + + private void mapToContext(Person person, DirContextAdapter context) { + context.setAttributeValues("objectclass", new String[] { "top", "person" }); + context.setAttributeValue("cn", person.getFullName()); + context.setAttributeValue("sn", person.getLastName()); + context.setAttributeValue("description", person.getDescription()); + context.setAttributeValue("telephoneNumber", person.getPhone()); + } + + /** + * Maps from DirContextAdapter to Person objects. A DN for a person will be + * of the form cn=[fullname],ou=[company],c=[country], so + * the values of these attributes must be extracted from the DN. For this, + * we use the LdapName along with utility methods in LdapUtils. + */ + private final static ContextMapper PERSON_CONTEXT_MAPPER = new AbstractContextMapper() { + @Override + public Person doMapFromContext(DirContextOperations context) { + Person person = new Person(); + + LdapName dn = LdapUtils.newLdapName(context.getDn()); + person.setCountry(LdapUtils.getStringValue(dn, 0)); + person.setCompany(LdapUtils.getStringValue(dn, 1)); + person.setFullName(context.getStringAttribute("cn")); + person.setLastName(context.getStringAttribute("sn")); + person.setDescription(context.getStringAttribute("description")); + person.setPhone(context.getStringAttribute("telephoneNumber")); + + return person; + } + }; + + public void setLdapTemplate(LdapTemplate ldapTemplate) { + this.ldapTemplate = ldapTemplate; + } +} diff --git a/samples/plain/src/main/java/org/springframework/ldap/samples/plain/domain/Person.java b/samples/plain/src/main/java/org/springframework/ldap/samples/plain/domain/Person.java index 5d58e611..abb9fa13 100644 --- a/samples/plain/src/main/java/org/springframework/ldap/samples/plain/domain/Person.java +++ b/samples/plain/src/main/java/org/springframework/ldap/samples/plain/domain/Person.java @@ -1,104 +1,104 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.samples.plain.domain; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -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 description; - - private String country; - - private String company; - - private String phone; - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getFullName() { - return fullName; - } - - public void setFullName(String fullName) { - this.fullName = fullName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getCompany() { - return company; - } - - public void setCompany(String company) { - this.company = company; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - 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); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.samples.plain.domain; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; +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 description; + + private String country; + + private String company; + + private String phone; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + 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); + } +} 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 e7b7376f..11c62d3e 100644 --- a/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessor.java +++ b/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewControlDirContextProcessor.java @@ -1,223 +1,223 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.control; - -import org.springframework.ldap.support.LdapUtils; -import org.springframework.util.ReflectionUtils; - -import javax.naming.NamingException; -import javax.naming.ldap.Control; -import java.lang.reflect.Method; - -/** - * DirContextProcessor implementation for managing a virtual list view. - *

- * This is the request control syntax: - * - *

- * VirtualListViewRequest ::= SEQUENCE {
- *        beforeCount    INTEGER (0..maxInt),
- *        afterCount     INTEGER (0..maxInt),
- *        target       CHOICE {
- *                       byOffset        [0] SEQUENCE {
- *                            offset          INTEGER (1 .. maxInt),
- *                            contentCount    INTEGER (0 .. maxInt) },
- *                       greaterThanOrEqual [1] AssertionValue },
- *        contextID     OCTET STRING OPTIONAL }
- * 
- * - *

- * This is the response control syntax: - * - *

- * VirtualListViewResponse ::= SEQUENCE {
- *        targetPosition    INTEGER (0 .. maxInt),
- *        contentCount     INTEGER (0 .. maxInt),
- *        virtualListViewResult ENUMERATED {
- *             success (0),
- *             operationsError (1),
- *             protocolError (3),
- *             unwillingToPerform (53),
- *             insufficientAccessRights (50),
- *             timeLimitExceeded (3),
- *             adminLimitExceeded (11),
- *             innapropriateMatching (18),
- *             sortControlMissing (60),
- *             offsetRangeError (61),
- *             other(80),
- *             ... },
- *        contextID     OCTET STRING OPTIONAL }
- * 
- * - * @author Ulrik Sandberg - * @author Marius Scurtescu - * @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"; - private static final String DEFAULT_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.VirtualListViewResponseControl"; - - private static final boolean CRITICAL_CONTROL = true; - - private int pageSize; - - private VirtualListViewResultsCookie cookie; - - private int listSize; - - private int targetOffset; - - private NamingException exception; - - private boolean offsetPercentage; - - public VirtualListViewControlDirContextProcessor(int pageSize) { - this(pageSize, 1, 0, null); - } - - 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; - fallbackResponseControl = DEFAULT_RESPONSE_CONTROL; - - loadControlClasses(); - } - - public VirtualListViewResultsCookie getCookie() { - return cookie; - } - - public int getPageSize() { - return pageSize; - } - - public int getListSize() { - return listSize; - } - - public NamingException getException() { - return exception; - } - - public int getTargetOffset() { - return targetOffset; - } - - /** - * 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() - { - return offsetPercentage; - } - - /* - * @see org.springframework.ldap.control.AbstractRequestControlDirContextProcessor#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) - } - ); - } - 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) - } - ); - } - - 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); - - 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) - { - Method method = ReflectionUtils.findMethod(clazz, methodName, paramTypes); - - return ReflectionUtils.invokeMethod(method, control, paramValues); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.control; + +import org.springframework.ldap.support.LdapUtils; +import org.springframework.util.ReflectionUtils; + +import javax.naming.NamingException; +import javax.naming.ldap.Control; +import java.lang.reflect.Method; + +/** + * DirContextProcessor implementation for managing a virtual list view. + *

+ * This is the request control syntax: + * + *

+ * VirtualListViewRequest ::= SEQUENCE {
+ *        beforeCount    INTEGER (0..maxInt),
+ *        afterCount     INTEGER (0..maxInt),
+ *        target       CHOICE {
+ *                       byOffset        [0] SEQUENCE {
+ *                            offset          INTEGER (1 .. maxInt),
+ *                            contentCount    INTEGER (0 .. maxInt) },
+ *                       greaterThanOrEqual [1] AssertionValue },
+ *        contextID     OCTET STRING OPTIONAL }
+ * 
+ * + *

+ * This is the response control syntax: + * + *

+ * VirtualListViewResponse ::= SEQUENCE {
+ *        targetPosition    INTEGER (0 .. maxInt),
+ *        contentCount     INTEGER (0 .. maxInt),
+ *        virtualListViewResult ENUMERATED {
+ *             success (0),
+ *             operationsError (1),
+ *             protocolError (3),
+ *             unwillingToPerform (53),
+ *             insufficientAccessRights (50),
+ *             timeLimitExceeded (3),
+ *             adminLimitExceeded (11),
+ *             innapropriateMatching (18),
+ *             sortControlMissing (60),
+ *             offsetRangeError (61),
+ *             other(80),
+ *             ... },
+ *        contextID     OCTET STRING OPTIONAL }
+ * 
+ * + * @author Ulrik Sandberg + * @author Marius Scurtescu + * @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"; + private static final String DEFAULT_RESPONSE_CONTROL = "com.sun.jndi.ldap.ctl.VirtualListViewResponseControl"; + + private static final boolean CRITICAL_CONTROL = true; + + private int pageSize; + + private VirtualListViewResultsCookie cookie; + + private int listSize; + + private int targetOffset; + + private NamingException exception; + + private boolean offsetPercentage; + + public VirtualListViewControlDirContextProcessor(int pageSize) { + this(pageSize, 1, 0, null); + } + + 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; + fallbackResponseControl = DEFAULT_RESPONSE_CONTROL; + + loadControlClasses(); + } + + public VirtualListViewResultsCookie getCookie() { + return cookie; + } + + public int getPageSize() { + return pageSize; + } + + public int getListSize() { + return listSize; + } + + public NamingException getException() { + return exception; + } + + public int getTargetOffset() { + return targetOffset; + } + + /** + * 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() + { + return offsetPercentage; + } + + /* + * @see org.springframework.ldap.control.AbstractRequestControlDirContextProcessor#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) + } + ); + } + 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) + } + ); + } + + 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); + + 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) + { + 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 68519e7a..aac66fd5 100644 --- a/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewResultsCookie.java +++ b/sandbox/src/main/java/org/springframework/ldap/control/VirtualListViewResultsCookie.java @@ -1,63 +1,63 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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 { - - private byte[] cookie; - - private int contentCount; - - private int targetPosition; - - /** - * Constructor. - * - * @param cookie - * the cookie returned by a VirtualListViewResponseControl. - * @param targetPosition TODO - * @param contentCount TODO - */ - public VirtualListViewResultsCookie(byte[] cookie, int targetPosition, int contentCount) { - this.cookie = cookie; - this.targetPosition = targetPosition; - this.contentCount = contentCount; - } - - /** - * Get the cookie. - * - * @return the cookie. - */ - public byte[] getCookie() { - return cookie; - } - - public int getContentCount() { - return contentCount; - } - - public int getTargetPosition() { - return targetPosition; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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 { + + private byte[] cookie; + + private int contentCount; + + private int targetPosition; + + /** + * Constructor. + * + * @param cookie + * the cookie returned by a VirtualListViewResponseControl. + * @param targetPosition TODO + * @param contentCount TODO + */ + public VirtualListViewResultsCookie(byte[] cookie, int targetPosition, int contentCount) { + this.cookie = cookie; + this.targetPosition = targetPosition; + this.contentCount = contentCount; + } + + /** + * Get the cookie. + * + * @return the cookie. + */ + public byte[] getCookie() { + return cookie; + } + + public int getContentCount() { + return contentCount; + } + + public int getTargetPosition() { + return targetPosition; + } +} 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 647b7885..7137fc9e 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 @@ -1,68 +1,68 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.test; - -import junit.framework.Assert; -import org.springframework.ldap.core.AttributesMapper; - -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import java.util.Arrays; - -/** - * 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[] 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.assertEquals(expectedValues[i], attribute.get()); - } - - for (String absentAttribute : absentAttributes) { - Assert.assertNull(attributes.get(absentAttribute)); - } - - return null; - } - - public void setAbsentAttributes(String[] absentAttributes) { - this.absentAttributes = Arrays.copyOf(absentAttributes, absentAttributes.length); - } - - public void setExpectedAttributes(String[] expectedAttributes) { - this.expectedAttributes = Arrays.copyOf(expectedAttributes, expectedAttributes.length); - } - - public void setExpectedValues(String[] expectedValues) { - this.expectedValues = Arrays.copyOf(expectedValues, expectedValues.length); - } +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.test; + +import junit.framework.Assert; +import org.springframework.ldap.core.AttributesMapper; + +import javax.naming.NamingException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import java.util.Arrays; + +/** + * 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[] 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.assertEquals(expectedValues[i], attribute.get()); + } + + for (String absentAttribute : absentAttributes) { + Assert.assertNull(attributes.get(absentAttribute)); + } + + return null; + } + + public void setAbsentAttributes(String[] absentAttributes) { + this.absentAttributes = Arrays.copyOf(absentAttributes, absentAttributes.length); + } + + public void setExpectedAttributes(String[] expectedAttributes) { + this.expectedAttributes = Arrays.copyOf(expectedAttributes, expectedAttributes.length); + } + + 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 ed3ec376..298d0129 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 @@ -1,68 +1,68 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.test; - -import junit.framework.Assert; - -import org.springframework.ldap.core.ContextMapper; -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. - * - * @author Mattias Hellborg Arthursson - */ -public class AttributeCheckContextMapper implements ContextMapper { - private String[] expectedAttributes = new String[0]; - - private String[] expectedValues = new String[0]; - - private String[] absentAttributes = new String[0]; - - public DirContextAdapter mapFromContext(Object ctx) { - DirContextAdapter adapter = (DirContextAdapter) ctx; - Assert.assertEquals("Values and attributes need to have the same length ", - expectedAttributes.length, expectedValues.length); - for (int i = 0; i < expectedAttributes.length; i++) { - String attributeValue = adapter - .getStringAttribute(expectedAttributes[i]); - Assert.assertNotNull("Attribute " + expectedAttributes[i] - + " was not present", attributeValue); - Assert.assertEquals(expectedValues[i], attributeValue); - } - - for (String absentAttribute : absentAttributes) { - Assert.assertNull(adapter.getStringAttribute(absentAttribute)); - } - - return adapter; - } - - public void setAbsentAttributes(String[] absentAttributes) { - this.absentAttributes = Arrays.copyOf(absentAttributes, absentAttributes.length); - } - - public void setExpectedAttributes(String[] expectedAttributes) { - this.expectedAttributes = Arrays.copyOf(expectedAttributes, expectedAttributes.length); - } - - public void setExpectedValues(String[] expectedValues) { - this.expectedValues = Arrays.copyOf(expectedValues, expectedValues.length); - } +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.test; + +import junit.framework.Assert; + +import org.springframework.ldap.core.ContextMapper; +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. + * + * @author Mattias Hellborg Arthursson + */ +public class AttributeCheckContextMapper implements ContextMapper { + private String[] expectedAttributes = new String[0]; + + private String[] expectedValues = new String[0]; + + private String[] absentAttributes = new String[0]; + + public DirContextAdapter mapFromContext(Object ctx) { + DirContextAdapter adapter = (DirContextAdapter) ctx; + Assert.assertEquals("Values and attributes need to have the same length ", + expectedAttributes.length, expectedValues.length); + for (int i = 0; i < expectedAttributes.length; i++) { + String attributeValue = adapter + .getStringAttribute(expectedAttributes[i]); + Assert.assertNotNull("Attribute " + expectedAttributes[i] + + " was not present", attributeValue); + Assert.assertEquals(expectedValues[i], attributeValue); + } + + for (String absentAttribute : absentAttributes) { + Assert.assertNull(adapter.getStringAttribute(absentAttribute)); + } + + return adapter; + } + + public void setAbsentAttributes(String[] absentAttributes) { + this.absentAttributes = Arrays.copyOf(absentAttributes, absentAttributes.length); + } + + public void setExpectedAttributes(String[] expectedAttributes) { + this.expectedAttributes = Arrays.copyOf(expectedAttributes, expectedAttributes.length); + } + + public void setExpectedValues(String[] expectedValues) { + this.expectedValues = Arrays.copyOf(expectedValues, expectedValues.length); + } } \ No newline at end of file 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 4cf4cfba..7c8d1289 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 @@ -1,51 +1,51 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.ad; - -import java.io.File; -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 }); - - pb.redirectErrorStream(true); - Process proc = pb.start(); - InputStream is = proc.getInputStream(); - InputStreamReader isr = new InputStreamReader(is); - - char[] buf = new char[1024]; - int count; - StringBuilder builder = new StringBuilder(); - while ((count = isr.read(buf)) > 0) { - builder.append(buf, 0, count); - } - - boolean ok = proc.waitFor() == 0; - - if (!ok) { - throw new RuntimeException(builder.toString()); - } - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.ad; + +import java.io.File; +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 }); + + pb.redirectErrorStream(true); + Process proc = pb.start(); + InputStream is = proc.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + + char[] buf = new char[1024]; + int count; + StringBuilder builder = new StringBuilder(); + 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-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 99b8afc4..c5d94ae4 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 @@ -1,104 +1,104 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.control; - -import org.apache.commons.lang.builder.EqualsBuilder; -import org.apache.commons.lang.builder.HashCodeBuilder; -import org.apache.commons.lang.builder.ToStringBuilder; -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 description; - - private String country; - - private String company; - - private String phone; - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getFullName() { - return fullName; - } - - public void setFullName(String fullName) { - this.fullName = fullName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getCompany() { - return company; - } - - public void setCompany(String company) { - this.company = company; - } - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - 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); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.control; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; +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 description; + + private String country; + + private String company; + + private String phone; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getFullName() { + return fullName; + } + + public void setFullName(String fullName) { + this.fullName = fullName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + 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); + } +} 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 221c4de9..6fc74529 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 @@ -1,194 +1,194 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest.core; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.ClassPathResource; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.test.AttributeCheckAttributesMapper; -import org.springframework.ldap.test.AttributeCheckContextMapper; -import org.springframework.ldap.test.LdapTestUtils; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; - -import javax.naming.Name; -import javax.naming.directory.SearchControls; -import java.util.List; - -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" }) -public class LdapTemplateSearchResultITest extends AbstractJUnit4SpringContextTests { - - @Autowired - private LdapTemplate tested; - - @Autowired - private ContextSource contextSource; - - private AttributeCheckAttributesMapper attributesMapper; - - private AttributeCheckContextMapper contextMapper; - - private static final String[] ALL_ATTRIBUTES = { "cn", "sn", "description", "telephoneNumber" }; - - private static final String[] CN_SN_ATTRS = { "cn", "sn" }; - - private static final String[] ABSENT_ATTRIBUTES = { "description", "telephoneNumber" }; - - private static final String[] CN_SN_VALUES = { "Some Person2", "Person2" }; - - private static final String[] ALL_VALUES = { "Some Person2", "Person2", "Sweden, Company1, Some Person2", - "+46 555-123458" }; - - private static final String BASE_STRING = ""; - - private static final String FILTER_STRING = "(&(objectclass=person)(sn=Person2))"; - - private static final Name BASE_NAME = new DistinguishedName(BASE_STRING); - - @Before - public void prepareTestedInstance() throws Exception { - LdapTestUtils.cleanAndSetup( - contextSource, - LdapUtils.newLdapName("ou=People"), - new ClassPathResource("/setup_data.ldif")); - - attributesMapper = new AttributeCheckAttributesMapper(); - contextMapper = new AttributeCheckContextMapper(); - } - - @After - public void cleanup() throws Exception { - LdapTestUtils.clearSubContexts(contextSource, LdapUtils.newLdapName("ou=People")); - attributesMapper = null; - contextMapper = null; - } - - @Test - public void testSearch_AttributesMapper() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_AttributesMapper() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_AttributesMapper() { - attributesMapper.setExpectedAttributes(CN_SN_ATTRS); - attributesMapper.setExpectedValues(CN_SN_VALUES); - attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, - attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_AttributesMapper_Name() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_AttributesMapper_Name() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_AttributesMapper_Name() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_ContextMapper() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, contextMapper); - assertThat(list).hasSize(1); - } - - @Test - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_ContextMapper() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_ContextMapper_Name() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, contextMapper); - assertThat(list).hasSize(1); - } - - @Test - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_ContextMapper_Name() { - 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); - assertThat(list).hasSize(1); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest.core; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.test.AttributeCheckAttributesMapper; +import org.springframework.ldap.test.AttributeCheckContextMapper; +import org.springframework.ldap.test.LdapTestUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; + +import javax.naming.Name; +import javax.naming.directory.SearchControls; +import java.util.List; + +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" }) +public class LdapTemplateSearchResultITest extends AbstractJUnit4SpringContextTests { + + @Autowired + private LdapTemplate tested; + + @Autowired + private ContextSource contextSource; + + private AttributeCheckAttributesMapper attributesMapper; + + private AttributeCheckContextMapper contextMapper; + + private static final String[] ALL_ATTRIBUTES = { "cn", "sn", "description", "telephoneNumber" }; + + private static final String[] CN_SN_ATTRS = { "cn", "sn" }; + + private static final String[] ABSENT_ATTRIBUTES = { "description", "telephoneNumber" }; + + private static final String[] CN_SN_VALUES = { "Some Person2", "Person2" }; + + private static final String[] ALL_VALUES = { "Some Person2", "Person2", "Sweden, Company1, Some Person2", + "+46 555-123458" }; + + private static final String BASE_STRING = ""; + + private static final String FILTER_STRING = "(&(objectclass=person)(sn=Person2))"; + + private static final Name BASE_NAME = new DistinguishedName(BASE_STRING); + + @Before + public void prepareTestedInstance() throws Exception { + LdapTestUtils.cleanAndSetup( + contextSource, + LdapUtils.newLdapName("ou=People"), + new ClassPathResource("/setup_data.ldif")); + + attributesMapper = new AttributeCheckAttributesMapper(); + contextMapper = new AttributeCheckContextMapper(); + } + + @After + public void cleanup() throws Exception { + LdapTestUtils.clearSubContexts(contextSource, LdapUtils.newLdapName("ou=People")); + attributesMapper = null; + contextMapper = null; + } + + @Test + public void testSearch_AttributesMapper() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_AttributesMapper() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_AttributesMapper() { + attributesMapper.setExpectedAttributes(CN_SN_ATTRS); + attributesMapper.setExpectedValues(CN_SN_VALUES); + attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); + List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_AttributesMapper_Name() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_AttributesMapper_Name() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_AttributesMapper_Name() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_ContextMapper() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, contextMapper); + assertThat(list).hasSize(1); + } + + @Test + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_ContextMapper() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_ContextMapper_Name() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, contextMapper); + assertThat(list).hasSize(1); + } + + @Test + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_ContextMapper_Name() { + 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); + assertThat(list).hasSize(1); + } +} 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 108954f9..c4de4f48 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 @@ -1,272 +1,272 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest.core; - -import java.util.List; - -import javax.naming.directory.SearchControls; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.control.VirtualListViewControlDirContextProcessor; -import org.springframework.ldap.control.VirtualListViewResultsCookie; -import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler; -import org.springframework.ldap.core.ContextMapperCallbackHandler; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.itest.Person; -import org.springframework.ldap.itest.PersonContextMapper; -import org.springframework.test.context.ContextConfiguration; -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 - * 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. - *

- * 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). - *

- * 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. - *

- * 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.

- * - * @author Ulrik Sandberg - */ -@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) -public class LdapTemplateVirtualListViewSearchITest extends - AbstractJUnit4SpringContextTests { - - @Autowired - private LdapTemplate tested; - - private static final String BASE_STRING = ""; - - private static final String FILTER_STRING = "(objectClass=person)"; - - private SearchControls searchControls; - - private CollectingNameClassPairCallbackHandler callbackHandler; - - @Before - public void prepareTestedInstance() throws Exception { - searchControls = new SearchControls(); - searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); - } - - @After - public void cleanup() throws Exception { - searchControls = null; - } - - @Test - public void testSearchUsingVirtualListView() { - List list; - Person person; - VirtualListViewResultsCookie cookie; - VirtualListViewControlDirContextProcessor requestControl; - PersonContextMapper contextMapper = new PersonContextMapper(); - int listSize; - int targetOffset; - - // - // Step 1: Prepare for getting the first 20 - // - - callbackHandler = new ContextMapperCallbackHandler(contextMapper); - requestControl = new VirtualListViewControlDirContextProcessor(20); - - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); - cookie = requestControl.getCookie(); - - // assert that total count is still 78564 - listSize = cookie.getContentCount(); - assertThat(listSize).isEqualTo(78564); - - // assert that we are now at 1 - targetOffset = cookie.getTargetPosition(); - assertThat(targetOffset).isEqualTo(1); - - // assert that we got the right 20 - list = callbackHandler.getList(); - assertThat(list).hasSize(20); - person = (Person) list.get(0); - assertThat(person.getFullname()).isEqualTo("Adam Ace"); - - // - // Step 2: Prepare for getting the last 20 - // - - callbackHandler = new ContextMapperCallbackHandler(contextMapper); - - // we need a constructor that takes a beforeCount and an afterCount - requestControl = new VirtualListViewControlDirContextProcessor(20, - 78564, listSize, cookie); - - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); - cookie = requestControl.getCookie(); - - // assert that total count is still 78564 - listSize = requestControl.getListSize(); - assertThat(listSize).isEqualTo(78564); - - // assert that we are now at 78564 - targetOffset = requestControl.getTargetOffset(); - assertThat(targetOffset).isEqualTo(78564); - - // assert that we got the right 20 - list = callbackHandler.getList(); - assertThat(list).hasSize(20); - person = (Person) list.get(19); - assertThat(person.getFullname()).isEqualTo("Xavier Zyxel"); - - // - // Step 3: Prepare for getting the next to last 20 - // - - callbackHandler = new ContextMapperCallbackHandler(contextMapper); - - // we need a constructor that takes a beforeCount and an afterCount - requestControl = new VirtualListViewControlDirContextProcessor(20, - 78564 - 19 - 20, listSize, cookie); - - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); - cookie = requestControl.getCookie(); - - // assert that total count is still 78564 - listSize = requestControl.getListSize(); - assertThat(listSize).isEqualTo(78564); - - // assert that we are now at 78525 - targetOffset = requestControl.getTargetOffset(); - assertThat(targetOffset).isEqualTo(78525); - - // assert that we got the right 20 - list = callbackHandler.getList(); - assertThat(list).hasSize(20); - person = (Person) list.get(0); - assertThat(person.getFullname()).isEqualTo("William Schnyder"); - - // - // Step 4: Prepare for getting the 20 entries around 68%, ie 53424 - // - - callbackHandler = new ContextMapperCallbackHandler(contextMapper); - - // we need a constructor that takes a beforeCount and an afterCount - requestControl = new VirtualListViewControlDirContextProcessor(20, - 68, listSize, cookie); - - requestControl.setOffsetPercentage(true); - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); - cookie = requestControl.getCookie(); - - // assert that total count is still 78564 - listSize = requestControl.getListSize(); - assertThat(listSize).isEqualTo(78564); - - // assert that we are now at 53424 - targetOffset = requestControl.getTargetOffset(); - assertThat(targetOffset).isEqualTo(53424); - - // assert that we got the right 20 - list = callbackHandler.getList(); - assertThat(list).hasSize(20); - person = (Person) list.get(9); - assertThat(person.getFullname()).isEqualTo("Peter Sellers"); - - // - // Step 5: Prepare for getting the 20 entries around the letter 'B', ie 5234 - // - - callbackHandler = new ContextMapperCallbackHandler(contextMapper); - - // we need a constructor that takes a String for 'greaterThanOrEqual' - // also beforeCount and afterCount - requestControl = new VirtualListViewControlDirContextProcessor(20, - 5234, listSize, cookie); - - requestControl.setOffsetPercentage(true); - tested.search(BASE_STRING, FILTER_STRING, searchControls, - callbackHandler, requestControl); - cookie = requestControl.getCookie(); - - // assert that total count is still 78564 - listSize = requestControl.getListSize(); - assertThat(listSize).isEqualTo(78564); - - // assert that we are now at 5234 - targetOffset = requestControl.getTargetOffset(); - assertThat(targetOffset).isEqualTo(5234); - - // assert that we got the right 20 - list = callbackHandler.getList(); - assertThat(list).hasSize(20); - person = (Person) list.get(9); - assertThat(person.getFullname()).isEqualTo("Babs Jensen"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest.core; + +import java.util.List; + +import javax.naming.directory.SearchControls; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.control.VirtualListViewControlDirContextProcessor; +import org.springframework.ldap.control.VirtualListViewResultsCookie; +import org.springframework.ldap.core.CollectingNameClassPairCallbackHandler; +import org.springframework.ldap.core.ContextMapperCallbackHandler; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.itest.Person; +import org.springframework.ldap.itest.PersonContextMapper; +import org.springframework.test.context.ContextConfiguration; +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 + * 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. + *

+ * 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). + *

+ * 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. + *

+ * 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.

+ * + * @author Ulrik Sandberg + */ +@ContextConfiguration(locations = { "/conf/ldapTemplateTestContext.xml" }) +public class LdapTemplateVirtualListViewSearchITest extends + AbstractJUnit4SpringContextTests { + + @Autowired + private LdapTemplate tested; + + private static final String BASE_STRING = ""; + + private static final String FILTER_STRING = "(objectClass=person)"; + + private SearchControls searchControls; + + private CollectingNameClassPairCallbackHandler callbackHandler; + + @Before + public void prepareTestedInstance() throws Exception { + searchControls = new SearchControls(); + searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); + } + + @After + public void cleanup() throws Exception { + searchControls = null; + } + + @Test + public void testSearchUsingVirtualListView() { + List list; + Person person; + VirtualListViewResultsCookie cookie; + VirtualListViewControlDirContextProcessor requestControl; + PersonContextMapper contextMapper = new PersonContextMapper(); + int listSize; + int targetOffset; + + // + // Step 1: Prepare for getting the first 20 + // + + callbackHandler = new ContextMapperCallbackHandler(contextMapper); + requestControl = new VirtualListViewControlDirContextProcessor(20); + + tested.search(BASE_STRING, FILTER_STRING, searchControls, + callbackHandler, requestControl); + cookie = requestControl.getCookie(); + + // assert that total count is still 78564 + listSize = cookie.getContentCount(); + assertThat(listSize).isEqualTo(78564); + + // assert that we are now at 1 + targetOffset = cookie.getTargetPosition(); + assertThat(targetOffset).isEqualTo(1); + + // assert that we got the right 20 + list = callbackHandler.getList(); + assertThat(list).hasSize(20); + person = (Person) list.get(0); + assertThat(person.getFullname()).isEqualTo("Adam Ace"); + + // + // Step 2: Prepare for getting the last 20 + // + + callbackHandler = new ContextMapperCallbackHandler(contextMapper); + + // we need a constructor that takes a beforeCount and an afterCount + requestControl = new VirtualListViewControlDirContextProcessor(20, + 78564, listSize, cookie); + + tested.search(BASE_STRING, FILTER_STRING, searchControls, + callbackHandler, requestControl); + cookie = requestControl.getCookie(); + + // assert that total count is still 78564 + listSize = requestControl.getListSize(); + assertThat(listSize).isEqualTo(78564); + + // assert that we are now at 78564 + targetOffset = requestControl.getTargetOffset(); + assertThat(targetOffset).isEqualTo(78564); + + // assert that we got the right 20 + list = callbackHandler.getList(); + assertThat(list).hasSize(20); + person = (Person) list.get(19); + assertThat(person.getFullname()).isEqualTo("Xavier Zyxel"); + + // + // Step 3: Prepare for getting the next to last 20 + // + + callbackHandler = new ContextMapperCallbackHandler(contextMapper); + + // we need a constructor that takes a beforeCount and an afterCount + requestControl = new VirtualListViewControlDirContextProcessor(20, + 78564 - 19 - 20, listSize, cookie); + + tested.search(BASE_STRING, FILTER_STRING, searchControls, + callbackHandler, requestControl); + cookie = requestControl.getCookie(); + + // assert that total count is still 78564 + listSize = requestControl.getListSize(); + assertThat(listSize).isEqualTo(78564); + + // assert that we are now at 78525 + targetOffset = requestControl.getTargetOffset(); + assertThat(targetOffset).isEqualTo(78525); + + // assert that we got the right 20 + list = callbackHandler.getList(); + assertThat(list).hasSize(20); + person = (Person) list.get(0); + assertThat(person.getFullname()).isEqualTo("William Schnyder"); + + // + // Step 4: Prepare for getting the 20 entries around 68%, ie 53424 + // + + callbackHandler = new ContextMapperCallbackHandler(contextMapper); + + // we need a constructor that takes a beforeCount and an afterCount + requestControl = new VirtualListViewControlDirContextProcessor(20, + 68, listSize, cookie); + + requestControl.setOffsetPercentage(true); + tested.search(BASE_STRING, FILTER_STRING, searchControls, + callbackHandler, requestControl); + cookie = requestControl.getCookie(); + + // assert that total count is still 78564 + listSize = requestControl.getListSize(); + assertThat(listSize).isEqualTo(78564); + + // assert that we are now at 53424 + targetOffset = requestControl.getTargetOffset(); + assertThat(targetOffset).isEqualTo(53424); + + // assert that we got the right 20 + list = callbackHandler.getList(); + assertThat(list).hasSize(20); + person = (Person) list.get(9); + assertThat(person.getFullname()).isEqualTo("Peter Sellers"); + + // + // Step 5: Prepare for getting the 20 entries around the letter 'B', ie 5234 + // + + callbackHandler = new ContextMapperCallbackHandler(contextMapper); + + // we need a constructor that takes a String for 'greaterThanOrEqual' + // also beforeCount and afterCount + requestControl = new VirtualListViewControlDirContextProcessor(20, + 5234, listSize, cookie); + + requestControl.setOffsetPercentage(true); + tested.search(BASE_STRING, FILTER_STRING, searchControls, + callbackHandler, requestControl); + cookie = requestControl.getCookie(); + + // assert that total count is still 78564 + listSize = requestControl.getListSize(); + assertThat(listSize).isEqualTo(78564); + + // assert that we are now at 5234 + targetOffset = requestControl.getTargetOffset(); + assertThat(targetOffset).isEqualTo(5234); + + // assert that we got the right 20 + list = callbackHandler.getList(); + assertThat(list).hasSize(20); + person = (Person) list.get(9); + assertThat(person.getFullname()).isEqualTo("Babs Jensen"); + } +} 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 6393fada..23ff5d28 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 @@ -1,72 +1,72 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.apache.commons.lang.builder.ToStringBuilder; -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; - - private String description; - - private String phone; - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getFullname() { - return fullname; - } - - public void setFullname(String fullname) { - this.fullname = fullname; - } - - public String getLastname() { - return lastname; - } - - public void setLastname(String lastname) { - this.lastname = lastname; - } - - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.apache.commons.lang.builder.ToStringBuilder; +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; + + private String description; + + private String phone; + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getFullname() { + return fullname; + } + + public void setFullname(String fullname) { + this.fullname = fullname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public String getPhone() { + return phone; + } + + 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 8de5cdda..5439742c 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 @@ -1,47 +1,47 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import javax.naming.NamingException; -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 Object mapFromAttributes(Attributes attributes) - throws NamingException { - Person person = new Person(); - person.setFullname((String) attributes.get("cn").get()); - person.setLastname((String) attributes.get("sn").get()); - person.setPhone((String) attributes.get("telephoneNumber").get()); - person.setDescription((String) attributes.get("description").get()); - return person; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import javax.naming.NamingException; +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 Object mapFromAttributes(Attributes attributes) + throws NamingException { + Person person = new Person(); + person.setFullname((String) attributes.get("cn").get()); + person.setLastname((String) attributes.get("sn").get()); + person.setPhone((String) attributes.get("telephoneNumber").get()); + 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 b7a6b08b..45904336 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 @@ -1,39 +1,39 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.springframework.ldap.core.DirContextOperations; -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 { - - protected Object doMapFromContext(DirContextOperations ctx) { - Person person = new Person(); - person.setFullname(ctx.getStringAttribute("cn")); - person.setLastname(ctx.getStringAttribute("sn")); - person.setPhone(ctx.getStringAttribute("telephoneNumber")); - person.setDescription(ctx.getStringAttribute("description")); - - return person; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.springframework.ldap.core.DirContextOperations; +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 { + + protected Object doMapFromContext(DirContextOperations ctx) { + Person person = new Person(); + person.setFullname(ctx.getStringAttribute("cn")); + person.setLastname(ctx.getStringAttribute("sn")); + person.setPhone(ctx.getStringAttribute("telephoneNumber")); + person.setDescription(ctx.getStringAttribute("description")); + + 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 71690d66..8505a3c2 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 @@ -1,36 +1,36 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.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. - * - * @author Mattias Hellborg Arthursson - */ -public class DummyDistinguishedNameConsumer { - private DistinguishedName distinguishedName; - - public DistinguishedName getDistinguishedName() { - return distinguishedName; - } - - public void setDistinguishedName(DistinguishedName distinguishedName) { - this.distinguishedName = distinguishedName; - } -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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. + * + * @author Mattias Hellborg Arthursson + */ +public class DummyDistinguishedNameConsumer { + private DistinguishedName distinguishedName; + + public DistinguishedName getDistinguishedName() { + return distinguishedName; + } + + public void setDistinguishedName(DistinguishedName distinguishedName) { + this.distinguishedName = distinguishedName; + } +} 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 5c48cb43..2ce073ea 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 @@ -1,38 +1,38 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest.core.support; - -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.support.BaseLdapPathAware; - -/** - * Dummy implementation of {@link BaseLdapPathAware}. - * - * @author Mattias Hellborg Arthursson - */ -public class DummyBaseLdapPathAware implements BaseLdapPathAware { - - private DistinguishedName base; - - public void setBaseLdapPath(DistinguishedName baseLdapPath) { - this.base = baseLdapPath; - } - - public DistinguishedName getBase() { - return base; - } - -} +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest.core.support; + +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.support.BaseLdapPathAware; + +/** + * Dummy implementation of {@link BaseLdapPathAware}. + * + * @author Mattias Hellborg Arthursson + */ +public class DummyBaseLdapPathAware implements BaseLdapPathAware { + + private DistinguishedName base; + + public void setBaseLdapPath(DistinguishedName baseLdapPath) { + this.base = baseLdapPath; + } + + public DistinguishedName getBase() { + return base; + } + +} 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 b85ef40c..d4bfc534 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 @@ -1,52 +1,52 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.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 update(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 modifyAttributes(String dn, String lastName, String description); - - void modifyAttributesWithException(String dn, String lastName, - String description); - - void unbind(String dn, String fullname); - - void unbindWithException(String dn, String fullname); - - void deleteRecursively(String dn); - - void deleteRecursivelyWithException(String dn); - - void createRecursivelyAndUnbindSubnode(); - - void createRecursivelyAndUnbindSubnodeWithException(); -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.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 update(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 modifyAttributes(String dn, String lastName, String description); + + void modifyAttributesWithException(String dn, String lastName, + String description); + + void unbind(String dn, String fullname); + + void unbindWithException(String dn, String fullname); + + void deleteRecursively(String dn); + + void deleteRecursivelyWithException(String dn); + + 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 bf7697a6..634cca58 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 @@ -1,22 +1,22 @@ -/* - * Copyright 2002-2007 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest.transaction.compensating.manager; - -public class DummyException extends RuntimeException { - public DummyException(String message) { - super(message); - } -} +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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 83dc1c28..1121ebe8 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 @@ -1,24 +1,24 @@ -/* - * Copyright 2002-2007 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest.transaction.compensating.manager; - -public class DummyServiceImpl { - private DummyDao dummyDaoImpl; - - public void setDummyDaoImpl(DummyDao dummyDaoImpl) { - this.dummyDaoImpl = dummyDaoImpl; - } -} +/* + * Copyright 2002-2007 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.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 d1b84286..6f1e360a 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 @@ -1,187 +1,187 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.transaction.compensating.manager; - -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.transaction.annotation.Transactional; - -@Transactional -public class LdapAndJdbcDummyDaoImpl implements DummyDao { - private LdapTemplate ldapTemplate; - - private JdbcTemplate jdbcTemplate; - - public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { - this.jdbcTemplate = jdbcTemplate; - } - - public void setLdapTemplate(LdapTemplate ldapTemplate) { - this.ldapTemplate = ldapTemplate; - } - - /* - * (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) - */ - 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) - */ - 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); - dn.add("cn", fullname); - - DirContextAdapter ctx = new DirContextAdapter(); - ctx.setAttributeValues("objectclass", new String[] { "top", "person" }); - ctx.setAttributeValue("cn", fullname); - ctx.setAttributeValue("sn", lastname); - ctx.setAttributeValue("description", description); - ldapTemplate.bind(dn, ctx, null); - jdbcTemplate.update("insert into PERSON values(?, ?, ?)", new Object[] { fullname, lastname, description }); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#update(java.lang.String, - * java.lang.String, java.lang.String) - */ - 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); - - ldapTemplate.modifyAttributes(ctx); - 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) - */ - 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) - */ - public void updateAndRename(String dn, String newDn, String description) { - DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); - ctx.setAttributeValue("description", description); - - ldapTemplate.modifyAttributes(ctx); - ldapTemplate.rename(dn, newDn); - } - - /* - * (non-Javadoc) - * - * @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); - 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) - */ - public void modifyAttributes(String dn, String lastName, String description) { - DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); - ctx.setAttributeValue("sn", lastName); - ctx.setAttributeValue("description", description); - - ldapTemplate.modifyAttributes(dn, ctx.getModificationItems()); - } - - /* - * (non-Javadoc) - * - * @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); - 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) { - ldapTemplate.unbind(dn); - jdbcTemplate.update("delete from PERSON where fullname=?", new Object[] { fullname }); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#unbindWithException(java.lang.String) - */ - public void unbindWithException(String dn, String fullname) { - unbind(dn, fullname); - throw new DummyException("This operation failed."); - } - - @Override - public void deleteRecursively(String dn) { - throw new UnsupportedOperationException(); - } - - @Override - public void deleteRecursivelyWithException(String dn) { - throw new UnsupportedOperationException(); - } - - @Override - public void createRecursivelyAndUnbindSubnode() { - throw new UnsupportedOperationException(); - } - - @Override - public void createRecursivelyAndUnbindSubnodeWithException() { - throw new UnsupportedOperationException(); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.transaction.compensating.manager; + +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.transaction.annotation.Transactional; + +@Transactional +public class LdapAndJdbcDummyDaoImpl implements DummyDao { + private LdapTemplate ldapTemplate; + + private JdbcTemplate jdbcTemplate; + + public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { + this.jdbcTemplate = jdbcTemplate; + } + + public void setLdapTemplate(LdapTemplate ldapTemplate) { + this.ldapTemplate = ldapTemplate; + } + + /* + * (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) + */ + 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) + */ + 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); + dn.add("cn", fullname); + + DirContextAdapter ctx = new DirContextAdapter(); + ctx.setAttributeValues("objectclass", new String[] { "top", "person" }); + ctx.setAttributeValue("cn", fullname); + ctx.setAttributeValue("sn", lastname); + ctx.setAttributeValue("description", description); + ldapTemplate.bind(dn, ctx, null); + jdbcTemplate.update("insert into PERSON values(?, ?, ?)", new Object[] { fullname, lastname, description }); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.transaction.support.DummyDao#update(java.lang.String, + * java.lang.String, java.lang.String) + */ + 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); + + ldapTemplate.modifyAttributes(ctx); + 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) + */ + 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) + */ + public void updateAndRename(String dn, String newDn, String description) { + DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); + ctx.setAttributeValue("description", description); + + ldapTemplate.modifyAttributes(ctx); + ldapTemplate.rename(dn, newDn); + } + + /* + * (non-Javadoc) + * + * @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); + 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) + */ + public void modifyAttributes(String dn, String lastName, String description) { + DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); + ctx.setAttributeValue("sn", lastName); + ctx.setAttributeValue("description", description); + + ldapTemplate.modifyAttributes(dn, ctx.getModificationItems()); + } + + /* + * (non-Javadoc) + * + * @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); + 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) { + ldapTemplate.unbind(dn); + jdbcTemplate.update("delete from PERSON where fullname=?", new Object[] { fullname }); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.transaction.support.DummyDao#unbindWithException(java.lang.String) + */ + public void unbindWithException(String dn, String fullname) { + unbind(dn, fullname); + throw new DummyException("This operation failed."); + } + + @Override + public void deleteRecursively(String dn) { + throw new UnsupportedOperationException(); + } + + @Override + public void deleteRecursivelyWithException(String dn) { + throw new UnsupportedOperationException(); + } + + @Override + public void createRecursivelyAndUnbindSubnode() { + throw new UnsupportedOperationException(); + } + + @Override + 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 fb7d3c47..07fb22cd 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 @@ -1,195 +1,195 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.transaction.compensating.manager; - -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapTemplate; -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) { - this.ldapTemplate = ldapTemplate; - } - - /* - * (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) - */ - 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) - */ - 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); - dn.add("cn", fullname); - - DirContextAdapter ctx = new DirContextAdapter(); - ctx.setAttributeValues("objectclass", new String[] { "top", "person" }); - ctx.setAttributeValue("cn", fullname); - ctx.setAttributeValue("sn", lastname); - ctx.setAttributeValue("description", description); - ldapTemplate.bind(dn, ctx, null); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#update(java.lang.String, - * java.lang.String, java.lang.String) - */ - 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); - - ldapTemplate.modifyAttributes(ctx); - } - - /* - * (non-Javadoc) - * - * @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); - 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) - */ - public void updateAndRename(String dn, String newDn, String description) { - DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); - ctx.setAttributeValue("description", description); - - ldapTemplate.modifyAttributes(ctx); - ldapTemplate.rename(dn, newDn); - } - - /* - * (non-Javadoc) - * - * @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); - 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) - */ - public void modifyAttributes(String dn, String lastName, String description) { - DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); - ctx.setAttributeValue("sn", lastName); - ctx.setAttributeValue("description", description); - - ldapTemplate.modifyAttributes(dn, ctx.getModificationItems()); - } - - /* - * (non-Javadoc) - * - * @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); - 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) { - ldapTemplate.unbind(dn); - } - - /* - * (non-Javadoc) - * - * @see org.springframework.ldap.transaction.support.DummyDao#unbindWithException(java.lang.String) - */ - public void unbindWithException(String dn, String fullname) { - unbind(dn, fullname); - throw new DummyException("This operation failed."); - } - - @Override - public void deleteRecursively(String dn) { - ldapTemplate.unbind(dn, RECURSIVE); - } - - @Override - public void deleteRecursivelyWithException(String dn) { - deleteRecursively(dn); - throw new DummyException("This method failed"); - } - - @Override - public void createRecursivelyAndUnbindSubnode() { - DirContextAdapter ctx = new DirContextAdapter(); - ctx.setAttributeValues("objectclass", new String[]{"top", "organizationalUnit"}); - ctx.setAttributeValue("ou", "dummy"); - ctx.setAttributeValue("description", "dummy description"); - - ldapTemplate.bind("ou=dummy", ctx, null); - ldapTemplate.bind("ou=dummy,ou=dummy", ctx, null); - ldapTemplate.unbind("ou=dummy,ou=dummy"); - ldapTemplate.unbind("ou=dummy"); - } - - @Override - public void createRecursivelyAndUnbindSubnodeWithException() { - createRecursivelyAndUnbindSubnode(); - throw new DummyException("This method failed"); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.transaction.compensating.manager; + +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.LdapTemplate; +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) { + this.ldapTemplate = ldapTemplate; + } + + /* + * (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) + */ + 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) + */ + 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); + dn.add("cn", fullname); + + DirContextAdapter ctx = new DirContextAdapter(); + ctx.setAttributeValues("objectclass", new String[] { "top", "person" }); + ctx.setAttributeValue("cn", fullname); + ctx.setAttributeValue("sn", lastname); + ctx.setAttributeValue("description", description); + ldapTemplate.bind(dn, ctx, null); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.transaction.support.DummyDao#update(java.lang.String, + * java.lang.String, java.lang.String) + */ + 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); + + ldapTemplate.modifyAttributes(ctx); + } + + /* + * (non-Javadoc) + * + * @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); + 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) + */ + public void updateAndRename(String dn, String newDn, String description) { + DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); + ctx.setAttributeValue("description", description); + + ldapTemplate.modifyAttributes(ctx); + ldapTemplate.rename(dn, newDn); + } + + /* + * (non-Javadoc) + * + * @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); + 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) + */ + public void modifyAttributes(String dn, String lastName, String description) { + DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); + ctx.setAttributeValue("sn", lastName); + ctx.setAttributeValue("description", description); + + ldapTemplate.modifyAttributes(dn, ctx.getModificationItems()); + } + + /* + * (non-Javadoc) + * + * @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); + 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) { + ldapTemplate.unbind(dn); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.ldap.transaction.support.DummyDao#unbindWithException(java.lang.String) + */ + public void unbindWithException(String dn, String fullname) { + unbind(dn, fullname); + throw new DummyException("This operation failed."); + } + + @Override + public void deleteRecursively(String dn) { + ldapTemplate.unbind(dn, RECURSIVE); + } + + @Override + public void deleteRecursivelyWithException(String dn) { + deleteRecursively(dn); + throw new DummyException("This method failed"); + } + + @Override + public void createRecursivelyAndUnbindSubnode() { + DirContextAdapter ctx = new DirContextAdapter(); + ctx.setAttributeValues("objectclass", new String[]{"top", "organizationalUnit"}); + ctx.setAttributeValue("ou", "dummy"); + ctx.setAttributeValue("description", "dummy description"); + + ldapTemplate.bind("ou=dummy", ctx, null); + ldapTemplate.bind("ou=dummy,ou=dummy", ctx, null); + ldapTemplate.unbind("ou=dummy,ou=dummy"); + ldapTemplate.unbind("ou=dummy"); + } + + @Override + public void createRecursivelyAndUnbindSubnodeWithException() { + 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 92ab6313..c21f3c7b 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 @@ -1,108 +1,108 @@ -package org.springframework.ldap.itest.transaction.compensating.manager.hibernate; - -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.itest.transaction.compensating.manager.DummyException; -import org.springframework.orm.hibernate5.support.HibernateDaoSupport; -import org.springframework.transaction.annotation.Transactional; - -/** - * @author Hans Westerbeek - */ -@Transactional -public class DummyDaoLdapAndHibernateImpl extends HibernateDaoSupport implements OrgPersonDao { - - private LdapTemplate ldapTemplate; - - public void create(OrgPerson person) { - DistinguishedName dn = new DistinguishedName(); - dn.add("ou", person.getCountry()); - dn.add("ou", person.getCompany()); - dn.add("cn", person.getFullname()); - - DirContextAdapter ctx = new DirContextAdapter(); - ctx.setAttributeValues("objectclass", new String[] { "top", "person" }); - ctx.setAttributeValue("cn", person.getFullname()); - ctx.setAttributeValue("sn", person.getLastname()); - ctx.setAttributeValue("description", person.getDescription()); - ldapTemplate.bind(dn, ctx, null); - this.getHibernateTemplate().saveOrUpdate(person); - - - } - - public void createWithException(OrgPerson person) { - this.create(person); - throw new DummyException("This method failed"); - - } - - public void modifyAttributes(String dn, String lastName, String description) { - DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); - ctx.setAttributeValue("sn", lastName); - ctx.setAttributeValue("description", description); - - ldapTemplate.modifyAttributes(dn, ctx.getModificationItems()); - } - - public void modifyAttributesWithException(String dn, String lastName, - String description) { - modifyAttributes(dn, lastName, description); - throw new DummyException("This method failed."); - } - - public void unbind(OrgPerson person) { - String dn = prepareDn(person); - ldapTemplate.unbind(dn); - this.getHibernateTemplate().delete(person); - - } - - public void unbindWithException(OrgPerson person) { - this.unbind(person); - throw new DummyException("This method failed"); - } - - public void update(OrgPerson person) { - String dn = prepareDn(person); - DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); - ctx.setAttributeValue("sn", person.getLastname()); - ctx.setAttributeValue("description", person.getDescription()); - - ldapTemplate.modifyAttributes(ctx); - this.getHibernateTemplate().saveOrUpdate(person); - - } - - public void updateWithException(OrgPerson person) { - this.update(person); - throw new DummyException("This method failed"); - } - - public void updateAndRename(String dn, String newDn, String updatedDescription) { - - DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); - ctx.setAttributeValue("description", updatedDescription); - - ldapTemplate.modifyAttributes(ctx); - ldapTemplate.rename(dn, newDn); - - } - - public void updateAndRenameWithException(String dn, String newDn, String updatedDescription) { - this.updateAndRename(dn, newDn, updatedDescription); - throw new DummyException("This method failed"); - } - - - - public void setLdapTemplate(LdapTemplate ldapTemplate) { - this.ldapTemplate = ldapTemplate; - } - - private String prepareDn(OrgPerson person){ - return "cn=" + person.getFullname() + ",ou=" + person.getCompany() + ",ou=" + person.getCountry(); - } - -} +package org.springframework.ldap.itest.transaction.compensating.manager.hibernate; + +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.itest.transaction.compensating.manager.DummyException; +import org.springframework.orm.hibernate5.support.HibernateDaoSupport; +import org.springframework.transaction.annotation.Transactional; + +/** + * @author Hans Westerbeek + */ +@Transactional +public class DummyDaoLdapAndHibernateImpl extends HibernateDaoSupport implements OrgPersonDao { + + private LdapTemplate ldapTemplate; + + public void create(OrgPerson person) { + DistinguishedName dn = new DistinguishedName(); + dn.add("ou", person.getCountry()); + dn.add("ou", person.getCompany()); + dn.add("cn", person.getFullname()); + + DirContextAdapter ctx = new DirContextAdapter(); + ctx.setAttributeValues("objectclass", new String[] { "top", "person" }); + ctx.setAttributeValue("cn", person.getFullname()); + ctx.setAttributeValue("sn", person.getLastname()); + ctx.setAttributeValue("description", person.getDescription()); + ldapTemplate.bind(dn, ctx, null); + this.getHibernateTemplate().saveOrUpdate(person); + + + } + + public void createWithException(OrgPerson person) { + this.create(person); + throw new DummyException("This method failed"); + + } + + public void modifyAttributes(String dn, String lastName, String description) { + DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); + ctx.setAttributeValue("sn", lastName); + ctx.setAttributeValue("description", description); + + ldapTemplate.modifyAttributes(dn, ctx.getModificationItems()); + } + + public void modifyAttributesWithException(String dn, String lastName, + String description) { + modifyAttributes(dn, lastName, description); + throw new DummyException("This method failed."); + } + + public void unbind(OrgPerson person) { + String dn = prepareDn(person); + ldapTemplate.unbind(dn); + this.getHibernateTemplate().delete(person); + + } + + public void unbindWithException(OrgPerson person) { + this.unbind(person); + throw new DummyException("This method failed"); + } + + public void update(OrgPerson person) { + String dn = prepareDn(person); + DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); + ctx.setAttributeValue("sn", person.getLastname()); + ctx.setAttributeValue("description", person.getDescription()); + + ldapTemplate.modifyAttributes(ctx); + this.getHibernateTemplate().saveOrUpdate(person); + + } + + public void updateWithException(OrgPerson person) { + this.update(person); + throw new DummyException("This method failed"); + } + + public void updateAndRename(String dn, String newDn, String updatedDescription) { + + DirContextAdapter ctx = (DirContextAdapter) ldapTemplate.lookup(dn); + ctx.setAttributeValue("description", updatedDescription); + + ldapTemplate.modifyAttributes(ctx); + ldapTemplate.rename(dn, newDn); + + } + + public void updateAndRenameWithException(String dn, String newDn, String updatedDescription) { + this.updateAndRename(dn, newDn, updatedDescription); + throw new DummyException("This method failed"); + } + + + + public void setLdapTemplate(LdapTemplate ldapTemplate) { + this.ldapTemplate = ldapTemplate; + } + + 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 debbf4cb..23fba099 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 @@ -1,123 +1,123 @@ -package org.springframework.ldap.itest.transaction.compensating.manager.hibernate; - -/** - * Pojo for use with the ContextSourceAndHibernateTransactionManager integration tests - * @author Hans Westerbeek - * - */ -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; - } - - public void setId(Integer id) { - this.id = id; - } - - public String getFullname() { - return fullname; - } - - public void setFullname(String fullname) { - this.fullname = fullname; - } - - public String getLastname() { - return lastname; - } - - public void setLastname(String lastname) { - this.lastname = lastname; - } - - - public String getCountry() { - return country; - } - - public void setCountry(String country) { - this.country = country; - } - - public String getCompany() { - return company; - } - - public void setCompany(String company) { - this.company = company; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((company == null) ? 0 : company.hashCode()); - result = prime * result + ((country == null) ? 0 : country.hashCode()); - result = prime * result + ((description == null) ? 0 : description.hashCode()); - result = prime * result + ((fullname == null) ? 0 : fullname.hashCode()); - result = prime * result + ((lastname == null) ? 0 : lastname.hashCode()); - return result; - } - - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final OrgPerson other = (OrgPerson) obj; - if (company == null) { - if (other.company != null) - return false; - } - else if (!company.equals(other.company)) - return false; - if (country == null) { - if (other.country != null) - return false; - } - else if (!country.equals(other.country)) - return false; - if (description == null) { - if (other.description != null) - return false; - } - else if (!description.equals(other.description)) - return false; - if (fullname == null) { - if (other.fullname != null) - return false; - } - else if (!fullname.equals(other.fullname)) - return false; - if (lastname == null) { - if (other.lastname != null) - return false; - } - else if (!lastname.equals(other.lastname)) - return false; - return true; - } - -} +package org.springframework.ldap.itest.transaction.compensating.manager.hibernate; + +/** + * Pojo for use with the ContextSourceAndHibernateTransactionManager integration tests + * @author Hans Westerbeek + * + */ +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; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getFullname() { + return fullname; + } + + public void setFullname(String fullname) { + this.fullname = fullname; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + + public String getCountry() { + return country; + } + + public void setCountry(String country) { + this.country = country; + } + + public String getCompany() { + return company; + } + + public void setCompany(String company) { + this.company = company; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((company == null) ? 0 : company.hashCode()); + result = prime * result + ((country == null) ? 0 : country.hashCode()); + result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((fullname == null) ? 0 : fullname.hashCode()); + result = prime * result + ((lastname == null) ? 0 : lastname.hashCode()); + return result; + } + + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + final OrgPerson other = (OrgPerson) obj; + if (company == null) { + if (other.company != null) + return false; + } + else if (!company.equals(other.company)) + return false; + if (country == null) { + if (other.country != null) + return false; + } + else if (!country.equals(other.country)) + return false; + if (description == null) { + if (other.description != null) + return false; + } + else if (!description.equals(other.description)) + return false; + if (fullname == null) { + if (other.fullname != null) + return false; + } + else if (!fullname.equals(other.fullname)) + return false; + if (lastname == null) { + if (other.lastname != null) + return false; + } + else if (!lastname.equals(other.lastname)) + 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 5b6cc4da..593c4c1e 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,23 +1,23 @@ -package org.springframework.ldap.itest.transaction.compensating.manager.hibernate; - -public interface OrgPersonDao { - void createWithException(OrgPerson person); - - void create(OrgPerson person); - - void update(OrgPerson person); - - void updateWithException(OrgPerson person); - - void updateAndRename(String dn, String newDn, String updatedDescription); - - void updateAndRenameWithException(String dn, String newDn, String updatedDescription); - - void modifyAttributes(String dn, String lastName, String description); - - void modifyAttributesWithException(String dn, String lastName, String description); - - void unbind(OrgPerson person); - - void unbindWithException(OrgPerson person); -} +package org.springframework.ldap.itest.transaction.compensating.manager.hibernate; + +public interface OrgPersonDao { + void createWithException(OrgPerson person); + + void create(OrgPerson person); + + void update(OrgPerson person); + + void updateWithException(OrgPerson person); + + void updateAndRename(String dn, String newDn, String updatedDescription); + + void updateAndRenameWithException(String dn, String newDn, String updatedDescription); + + void modifyAttributes(String dn, String lastName, String description); + + void modifyAttributesWithException(String dn, String lastName, String description); + + void unbind(OrgPerson person); + + void unbindWithException(OrgPerson person); +} 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 88500e53..07364859 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 @@ -1,85 +1,85 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.ldap.LdapConditionallyFilteredTestRunner; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.test.LdapTestUtils; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.TestExecutionListeners; -import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; -import org.springframework.test.context.support.DirtiesContextTestExecutionListener; - -import javax.naming.Name; -import javax.naming.NamingException; -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.List; - -@DirtiesContext -@RunWith(LdapConditionallyFilteredTestRunner.class) -@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) -public abstract class AbstractLdapTemplateIntegrationTest { - - private final static String DEFAULT_BASE = "dc=261consulting,dc=com"; - - @Autowired - @Qualifier("contextSource") - protected ContextSource contextSource; - - @Value("${base}") - protected String base; - - @Before - public void cleanAndSetup() throws NamingException, IOException { - Resource ldifResource = getLdifFileResource(); - if(!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(DEFAULT_BASE))) { - List lines = IOUtils.readLines(ldifResource.getInputStream()); - - StringWriter sw = new StringWriter(); - PrintWriter writer = new PrintWriter(sw); - for (String line : lines) { - writer.println(StringUtils.replace(line, DEFAULT_BASE, base)); - } - - writer.flush(); - ldifResource = new ByteArrayResource(sw.toString().getBytes("UTF8")); - } - - LdapTestUtils.cleanAndSetup(contextSource, getRoot(), ldifResource); - } - - protected Resource getLdifFileResource() { - return new ClassPathResource("/setup_data.ldif"); - } - - protected Name getRoot() { - return LdapUtils.emptyLdapName(); - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.junit.Before; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.ldap.LdapConditionallyFilteredTestRunner; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.test.LdapTestUtils; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; + +import javax.naming.Name; +import javax.naming.NamingException; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.List; + +@DirtiesContext +@RunWith(LdapConditionallyFilteredTestRunner.class) +@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class }) +public abstract class AbstractLdapTemplateIntegrationTest { + + private final static String DEFAULT_BASE = "dc=261consulting,dc=com"; + + @Autowired + @Qualifier("contextSource") + protected ContextSource contextSource; + + @Value("${base}") + protected String base; + + @Before + public void cleanAndSetup() throws NamingException, IOException { + Resource ldifResource = getLdifFileResource(); + if(!LdapUtils.newLdapName(base).equals(LdapUtils.newLdapName(DEFAULT_BASE))) { + List lines = IOUtils.readLines(ldifResource.getInputStream()); + + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + for (String line : lines) { + writer.println(StringUtils.replace(line, DEFAULT_BASE, base)); + } + + writer.flush(); + ldifResource = new ByteArrayResource(sw.toString().getBytes("UTF8")); + } + + LdapTestUtils.cleanAndSetup(contextSource, getRoot(), ldifResource); + } + + protected Resource getLdifFileResource() { + return new ClassPathResource("/setup_data.ldif"); + } + + protected Name getRoot() { + return LdapUtils.emptyLdapName(); + } +} 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 abd63744..37c607dc 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 @@ -1,110 +1,110 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.support.AbstractContextMapper; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.InvalidNameException; -import javax.naming.ldap.LdapName; -import javax.naming.ldap.Rdn; -import java.util.List; - -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"}) -public class InvalidBackslashITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - private static LdapName DN = LdapUtils.newLdapName("cn=Some\\\\Person6,ou=company1,ou=Sweden"); - - @Before - public void prepareTestedInstance() throws Exception { - DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "Some\\Person6"); - adapter.setAttributeValue("sn", "Person6"); - adapter.setAttributeValue("description", "Some description"); - - tested.unbind(DN); - tested.bind(DN, adapter, null); - } - - @After - public void cleanup() throws Exception { - tested.unbind(DN); - } - - /** - * 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 - * 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. - *

- *

- * 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. - *

- * @throws InvalidNameException - */ - @Test - @Category(NoAdTest.class) - public void testSearchForDnSpoiledByCompositeName() throws InvalidNameException { - List result = tested.search("", "(sn=Person6)", new AbstractContextMapper() { - @Override - protected Object doMapFromContext(DirContextOperations ctx) { - LdapName dn = (LdapName) ctx.getDn(); - Rdn rdn = LdapUtils.getRdn(dn, "cn"); - assertThat(dn.toString()).isEqualTo("cn=Some\\\\Person6,ou=company1,ou=Sweden"); - assertThat(rdn.getValue()).isEqualTo("Some\\Person6"); - return new Object(); - } - }); - - assertThat(result).hasSize(1); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.support.AbstractContextMapper; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.InvalidNameException; +import javax.naming.ldap.LdapName; +import javax.naming.ldap.Rdn; +import java.util.List; + +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"}) +public class InvalidBackslashITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + private static LdapName DN = LdapUtils.newLdapName("cn=Some\\\\Person6,ou=company1,ou=Sweden"); + + @Before + public void prepareTestedInstance() throws Exception { + DirContextAdapter adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "Some\\Person6"); + adapter.setAttributeValue("sn", "Person6"); + adapter.setAttributeValue("description", "Some description"); + + tested.unbind(DN); + tested.bind(DN, adapter, null); + } + + @After + public void cleanup() throws Exception { + tested.unbind(DN); + } + + /** + * 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 + * 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. + *

+ *

+ * 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. + *

+ * @throws InvalidNameException + */ + @Test + @Category(NoAdTest.class) + public void testSearchForDnSpoiledByCompositeName() throws InvalidNameException { + List result = tested.search("", "(sn=Person6)", new AbstractContextMapper() { + @Override + protected Object doMapFromContext(DirContextOperations ctx) { + LdapName dn = (LdapName) ctx.getDn(); + Rdn rdn = LdapUtils.getRdn(dn, "cn"); + assertThat(dn.toString()).isEqualTo("cn=Some\\\\Person6,ou=company1,ou=Sweden"); + assertThat(rdn.getValue()).isEqualTo("Some\\Person6"); + return new Object(); + } + }); + + 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 dff1dfb0..79404e6b 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 @@ -1,80 +1,80 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.AttributesMapper; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import java.util.LinkedList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests the attributes mapper search method. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -public class LdapTemplateAttributesMapperITest extends AbstractLdapTemplateIntegrationTest { - @Autowired - private LdapTemplate tested; - - @Test - public void testSearch_AttributeMapper() throws Exception { - AttributesMapper mapper = new PersonAttributesMapper(); - List result = tested.search("ou=company1,ou=Sweden", "(&(objectclass=person)(sn=Person2))", mapper); - - assertThat(result).hasSize(1); - Person person = (Person) result.get(0); - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).isEqualTo("Person2"); - assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); - } - - /** - * Demonstrates how to retrieve all values of a multi-value attribute. - * - * @see LdapTemplateContextMapperITest#testSearch_ContextMapper_MultiValue() - */ - @Test - public void testSearch_AttributesMapper_MultiValue() throws Exception { - AttributesMapper mapper = new AttributesMapper() { - public Object mapFromAttributes(Attributes attributes) throws NamingException { - LinkedList list = new LinkedList(); - NamingEnumeration enumeration = attributes.get("uniqueMember").getAll(); - while (enumeration.hasMoreElements()) { - String value = (String) enumeration.nextElement(); - list.add(value); - } - String[] members = (String[]) list.toArray(new String[0]); - return members; - } - }; - List result = tested.search("ou=groups", "(&(objectclass=groupOfUniqueNames)(cn=ROLE_USER))", mapper); - - assertThat(result).hasSize(1); - - assertThat(((String[]) result.get(0)).length).isEqualTo(4); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import java.util.LinkedList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests the attributes mapper search method. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +public class LdapTemplateAttributesMapperITest extends AbstractLdapTemplateIntegrationTest { + @Autowired + private LdapTemplate tested; + + @Test + public void testSearch_AttributeMapper() throws Exception { + AttributesMapper mapper = new PersonAttributesMapper(); + List result = tested.search("ou=company1,ou=Sweden", "(&(objectclass=person)(sn=Person2))", mapper); + + assertThat(result).hasSize(1); + Person person = (Person) result.get(0); + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).isEqualTo("Person2"); + assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); + } + + /** + * Demonstrates how to retrieve all values of a multi-value attribute. + * + * @see LdapTemplateContextMapperITest#testSearch_ContextMapper_MultiValue() + */ + @Test + public void testSearch_AttributesMapper_MultiValue() throws Exception { + AttributesMapper mapper = new AttributesMapper() { + public Object mapFromAttributes(Attributes attributes) throws NamingException { + LinkedList list = new LinkedList(); + NamingEnumeration enumeration = attributes.get("uniqueMember").getAll(); + while (enumeration.hasMoreElements()) { + String value = (String) enumeration.nextElement(); + list.add(value); + } + String[] members = (String[]) list.toArray(new String[0]); + return members; + } + }; + List result = tested.search("ou=groups", "(&(objectclass=groupOfUniqueNames)(cn=ROLE_USER))", mapper); + + 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/LdapTemplateAuthenticationITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/LdapTemplateAuthenticationITest.java index 95b9aa49..0eafeb9e 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 @@ -1,171 +1,171 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.ldap.AuthenticationException; -import org.springframework.ldap.core.AuthenticatedLdapEntryContextCallback; -import org.springframework.ldap.core.CollectingAuthenticationErrorCallback; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.LdapEntryIdentification; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.support.LookupAttemptingCallback; -import org.springframework.ldap.filter.AndFilter; -import org.springframework.ldap.filter.EqualsFilter; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; - -import static org.assertj.core.api.Assertions.assertThat; -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"}) -public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - @Test - @Category(NoAdTest.class) - public void testAuthenticate() { - AndFilter filter = new AndFilter(); - filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - assertThat(tested.authenticate("", filter.toString(), "password")).isTrue(); - } - - @Test - @Category(NoAdTest.class) - 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"); - } - - @Test - @Category(NoAdTest.class) - public void testAuthenticateWithInvalidPassword() { - AndFilter filter = new AndFilter(); - filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - assertThat(tested.authenticate("", filter.toString(), "invalidpassword")).isFalse(); - } - - @Test(expected = AuthenticationException.class) - @Category(NoAdTest.class) - 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"); - } - - @Test - @Category(NoAdTest.class) - public void testAuthenticateWithLookupOperationPerformedOnAuthenticatedContext() { - AndFilter filter = new AndFilter(); - filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - AuthenticatedLdapEntryContextCallback contextCallback = new AuthenticatedLdapEntryContextCallback() { - public void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { - try { - DirContextAdapter adapter = (DirContextAdapter) ctx.lookup(ldapEntryIdentification.getRelativeDn()); - assertThat(adapter.getStringAttribute("cn")).isEqualTo("Some Person3"); - } - catch (NamingException e) { - throw new RuntimeException("Failed to lookup " + ldapEntryIdentification.getRelativeDn(), e); - } - } - }; - assertThat(tested.authenticate("", filter.toString(), "password", contextCallback)).isTrue(); - } - - @Test - @Category(NoAdTest.class) - public void testAuthenticateWithLdapQueryAndMapper() { - DirContextOperations ctx = tested.authenticate(query() - .where("objectclass").is("person") - .and("uid").is("some.person3"), - "password", - new LookupAttemptingCallback()); - - assertThat(ctx).isNotNull(); - assertThat(ctx.getStringAttribute("uid")).isEqualTo("some.person3"); - } - - @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", - new LookupAttemptingCallback()); - } - - @Test - @Category(NoAdTest.class) - public void testAuthenticateWithInvalidPasswordAndCollectedException() { - AndFilter filter = new AndFilter(); - filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - final CollectingAuthenticationErrorCallback errorCallback = new CollectingAuthenticationErrorCallback(); - 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(); - } - - @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")); - assertThat(tested.authenticate("", filter.toString(), "password")).isFalse(); - } - - @Test(expected=IncorrectResultSizeDataAccessException.class) - @Category(NoAdTest.class) - public void testAuthenticateWithFilterThatMatchesSeveralEntries() { - AndFilter filter = new AndFilter(); - filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", "Some Person")); - tested.authenticate("", filter.toString(), "password"); - } - - @Test - @Category(NoAdTest.class) - public void testLookupAttemptingCallback() { - AndFilter filter = new AndFilter(); - filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); - LookupAttemptingCallback callback = new LookupAttemptingCallback(); - assertThat(tested.authenticate("", filter.encode(), "password", callback)).isTrue(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.ldap.AuthenticationException; +import org.springframework.ldap.core.AuthenticatedLdapEntryContextCallback; +import org.springframework.ldap.core.CollectingAuthenticationErrorCallback; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapEntryIdentification; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.support.LookupAttemptingCallback; +import org.springframework.ldap.filter.AndFilter; +import org.springframework.ldap.filter.EqualsFilter; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; + +import static org.assertj.core.api.Assertions.assertThat; +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"}) +public class LdapTemplateAuthenticationITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + @Test + @Category(NoAdTest.class) + public void testAuthenticate() { + AndFilter filter = new AndFilter(); + filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); + assertThat(tested.authenticate("", filter.toString(), "password")).isTrue(); + } + + @Test + @Category(NoAdTest.class) + 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"); + } + + @Test + @Category(NoAdTest.class) + public void testAuthenticateWithInvalidPassword() { + AndFilter filter = new AndFilter(); + filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); + assertThat(tested.authenticate("", filter.toString(), "invalidpassword")).isFalse(); + } + + @Test(expected = AuthenticationException.class) + @Category(NoAdTest.class) + 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"); + } + + @Test + @Category(NoAdTest.class) + public void testAuthenticateWithLookupOperationPerformedOnAuthenticatedContext() { + AndFilter filter = new AndFilter(); + filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); + AuthenticatedLdapEntryContextCallback contextCallback = new AuthenticatedLdapEntryContextCallback() { + public void executeWithContext(DirContext ctx, LdapEntryIdentification ldapEntryIdentification) { + try { + DirContextAdapter adapter = (DirContextAdapter) ctx.lookup(ldapEntryIdentification.getRelativeDn()); + assertThat(adapter.getStringAttribute("cn")).isEqualTo("Some Person3"); + } + catch (NamingException e) { + throw new RuntimeException("Failed to lookup " + ldapEntryIdentification.getRelativeDn(), e); + } + } + }; + assertThat(tested.authenticate("", filter.toString(), "password", contextCallback)).isTrue(); + } + + @Test + @Category(NoAdTest.class) + public void testAuthenticateWithLdapQueryAndMapper() { + DirContextOperations ctx = tested.authenticate(query() + .where("objectclass").is("person") + .and("uid").is("some.person3"), + "password", + new LookupAttemptingCallback()); + + assertThat(ctx).isNotNull(); + assertThat(ctx.getStringAttribute("uid")).isEqualTo("some.person3"); + } + + @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", + new LookupAttemptingCallback()); + } + + @Test + @Category(NoAdTest.class) + public void testAuthenticateWithInvalidPasswordAndCollectedException() { + AndFilter filter = new AndFilter(); + filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); + final CollectingAuthenticationErrorCallback errorCallback = new CollectingAuthenticationErrorCallback(); + 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(); + } + + @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")); + assertThat(tested.authenticate("", filter.toString(), "password")).isFalse(); + } + + @Test(expected=IncorrectResultSizeDataAccessException.class) + @Category(NoAdTest.class) + public void testAuthenticateWithFilterThatMatchesSeveralEntries() { + AndFilter filter = new AndFilter(); + filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("cn", "Some Person")); + tested.authenticate("", filter.toString(), "password"); + } + + @Test + @Category(NoAdTest.class) + public void testLookupAttemptingCallback() { + AndFilter filter = new AndFilter(); + filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("uid", "some.person3")); + 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 f6026849..5a507e4d 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 @@ -1,170 +1,170 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.directory.Attributes; -import javax.naming.directory.BasicAttribute; -import javax.naming.directory.BasicAttributes; - -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. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -public class LdapTemplateBindUnbindITest extends - AbstractLdapTemplateIntegrationTest { - @Autowired - private LdapTemplate tested; - - private static String DN = "cn=Some Person4,ou=company1,ou=Sweden"; - - @Test - public void testBindAndUnbindWithAttributes() { - Attributes attributes = setupAttributes(); - tested.bind(DN, null, attributes); - verifyBoundCorrectData(); - tested.unbind(DN); - verifyCleanup(); - } - - @Test - public void testBindGroupOfUniqueNamesWithNameValues() { - DirContextAdapter ctx = new DirContextAdapter(LdapUtils.newLdapName("cn=TEST,ou=groups")); - ctx.addAttributeValue("cn", "TEST"); - ctx.addAttributeValue("objectclass", "top"); - ctx.addAttributeValue("objectclass", "groupOfUniqueNames"); - ctx.addAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=Some Person,ou=company1,ou=Sweden," + base)); - tested.bind(ctx); - } - - @Test - public void testBindAndUnbindWithAttributesUsingLdapName() { - Attributes attributes = setupAttributes(); - tested.bind(LdapUtils.newLdapName(DN), null, attributes); - verifyBoundCorrectData(); - tested.unbind(LdapUtils.newLdapName(DN)); - verifyCleanup(); - } - - @Test - public void testBindAndUnbindWithDirContextAdapter() { - DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); - adapter.setAttributeValue("cn", "Some Person4"); - adapter.setAttributeValue("sn", "Person4"); - - tested.bind(DN, adapter, null); - verifyBoundCorrectData(); - tested.unbind(DN); - verifyCleanup(); - } - - @Test - public void testBindAndUnbindWithDirContextAdapterUsingLdapName() { - DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); - adapter.setAttributeValue("cn", "Some Person4"); - adapter.setAttributeValue("sn", "Person4"); - - tested.bind(LdapUtils.newLdapName(DN), adapter, null); - verifyBoundCorrectData(); - tested.unbind(LdapUtils.newLdapName(DN)); - verifyCleanup(); - } - - @Test - public void testBindAndUnbindWithDirContextAdapterOnly() { - DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN)); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); - adapter.setAttributeValue("cn", "Some Person4"); - adapter.setAttributeValue("sn", "Person4"); - - tested.bind(adapter); - verifyBoundCorrectData(); - tested.unbind(DN); - verifyCleanup(); - } - - @Test - public void testBindAndRebindWithDirContextAdapterOnly() { - DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN)); - adapter.setAttributeValues("objectclass", new String[] { "top", - "person" }); - adapter.setAttributeValue("cn", "Some Person4"); - adapter.setAttributeValue("sn", "Person4"); - - tested.bind(adapter); - verifyBoundCorrectData(); - adapter.setAttributeValue("sn", "Person4.Changed"); - tested.rebind(adapter); - verifyReboundCorrectData(); - tested.unbind(DN); - verifyCleanup(); - } - - private Attributes setupAttributes() { - Attributes attributes = new BasicAttributes(); - BasicAttribute ocattr = new BasicAttribute("objectclass"); - ocattr.add("top"); - ocattr.add("person"); - attributes.put(ocattr); - attributes.put("cn", "Some Person4"); - attributes.put("sn", "Person4"); - return attributes; - } - - private void verifyBoundCorrectData() { - DirContextAdapter result = (DirContextAdapter) tested.lookup(DN); - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person4"); - } - - private void verifyReboundCorrectData() { - DirContextAdapter result = (DirContextAdapter) tested.lookup(DN); - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person4.Changed"); - } - - private void verifyCleanup() { - try { - tested.lookup(DN); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttribute; +import javax.naming.directory.BasicAttributes; + +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. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +public class LdapTemplateBindUnbindITest extends + AbstractLdapTemplateIntegrationTest { + @Autowired + private LdapTemplate tested; + + private static String DN = "cn=Some Person4,ou=company1,ou=Sweden"; + + @Test + public void testBindAndUnbindWithAttributes() { + Attributes attributes = setupAttributes(); + tested.bind(DN, null, attributes); + verifyBoundCorrectData(); + tested.unbind(DN); + verifyCleanup(); + } + + @Test + public void testBindGroupOfUniqueNamesWithNameValues() { + DirContextAdapter ctx = new DirContextAdapter(LdapUtils.newLdapName("cn=TEST,ou=groups")); + ctx.addAttributeValue("cn", "TEST"); + ctx.addAttributeValue("objectclass", "top"); + ctx.addAttributeValue("objectclass", "groupOfUniqueNames"); + ctx.addAttributeValue("uniqueMember", LdapUtils.newLdapName("cn=Some Person,ou=company1,ou=Sweden," + base)); + tested.bind(ctx); + } + + @Test + public void testBindAndUnbindWithAttributesUsingLdapName() { + Attributes attributes = setupAttributes(); + tested.bind(LdapUtils.newLdapName(DN), null, attributes); + verifyBoundCorrectData(); + tested.unbind(LdapUtils.newLdapName(DN)); + verifyCleanup(); + } + + @Test + public void testBindAndUnbindWithDirContextAdapter() { + DirContextAdapter adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", + "person" }); + adapter.setAttributeValue("cn", "Some Person4"); + adapter.setAttributeValue("sn", "Person4"); + + tested.bind(DN, adapter, null); + verifyBoundCorrectData(); + tested.unbind(DN); + verifyCleanup(); + } + + @Test + public void testBindAndUnbindWithDirContextAdapterUsingLdapName() { + DirContextAdapter adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", + "person" }); + adapter.setAttributeValue("cn", "Some Person4"); + adapter.setAttributeValue("sn", "Person4"); + + tested.bind(LdapUtils.newLdapName(DN), adapter, null); + verifyBoundCorrectData(); + tested.unbind(LdapUtils.newLdapName(DN)); + verifyCleanup(); + } + + @Test + public void testBindAndUnbindWithDirContextAdapterOnly() { + DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN)); + adapter.setAttributeValues("objectclass", new String[] { "top", + "person" }); + adapter.setAttributeValue("cn", "Some Person4"); + adapter.setAttributeValue("sn", "Person4"); + + tested.bind(adapter); + verifyBoundCorrectData(); + tested.unbind(DN); + verifyCleanup(); + } + + @Test + public void testBindAndRebindWithDirContextAdapterOnly() { + DirContextAdapter adapter = new DirContextAdapter(LdapUtils.newLdapName(DN)); + adapter.setAttributeValues("objectclass", new String[] { "top", + "person" }); + adapter.setAttributeValue("cn", "Some Person4"); + adapter.setAttributeValue("sn", "Person4"); + + tested.bind(adapter); + verifyBoundCorrectData(); + adapter.setAttributeValue("sn", "Person4.Changed"); + tested.rebind(adapter); + verifyReboundCorrectData(); + tested.unbind(DN); + verifyCleanup(); + } + + private Attributes setupAttributes() { + Attributes attributes = new BasicAttributes(); + BasicAttribute ocattr = new BasicAttribute("objectclass"); + ocattr.add("top"); + ocattr.add("person"); + attributes.put(ocattr); + attributes.put("cn", "Some Person4"); + attributes.put("sn", "Person4"); + return attributes; + } + + private void verifyBoundCorrectData() { + DirContextAdapter result = (DirContextAdapter) tested.lookup(DN); + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person4"); + } + + private void verifyReboundCorrectData() { + DirContextAdapter result = (DirContextAdapter) tested.lookup(DN); + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person4.Changed"); + } + + private void verifyCleanup() { + try { + tested.lookup(DN); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + 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 776ab85a..b719c830 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 @@ -1,52 +1,52 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest; - -import javax.naming.NamingException; -import javax.naming.directory.DirContext; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.ContextExecutor; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.test.context.ContextConfiguration; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for LdapTemplate's context executor methods. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -public class LdapTemplateContextExecutorTest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - @Test - public void testLookupLink() { - ContextExecutor executor = new ContextExecutor() { - public Object executeWithContext(DirContext ctx) throws NamingException { - return ctx.lookupLink("cn=Some Person,ou=company1,ou=Sweden"); - } - }; - - Object object = tested.executeReadOnly(executor); - assertThat(object instanceof DirContextAdapter).as("Should be a DirContextAdapter").isTrue(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest; + +import javax.naming.NamingException; +import javax.naming.directory.DirContext; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.ContextExecutor; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.test.context.ContextConfiguration; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for LdapTemplate's context executor methods. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +public class LdapTemplateContextExecutorTest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + @Test + public void testLookupLink() { + ContextExecutor executor = new ContextExecutor() { + public Object executeWithContext(DirContext ctx) throws NamingException { + return ctx.lookupLink("cn=Some Person,ou=company1,ou=Sweden"); + } + }; + + 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 5ada023d..312e002a 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 @@ -1,77 +1,77 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.ContextMapper; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.test.context.ContextConfiguration; - -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. - * - * @author Mattias Hellborg Arthursson - */ -@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. - */ - @Test - public void testSearch_ContextMapper() { - ContextMapper mapper = new PersonContextMapper(); - List result = tested.search("ou=company1,ou=Sweden", "(&(objectclass=person)(sn=Person2))", mapper); - - assertThat(result).hasSize(1); - Person person = (Person) result.get(0); - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).isEqualTo("Person2"); - assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); - } - - /** - * Demonstrates how to retrieve all values of a multi-value attribute. - * - * @see LdapTemplateAttributesMapperITest#testSearch_AttributesMapper_MultiValue() - */ - @Test - public void testSearch_ContextMapper_MultiValue() throws Exception { - ContextMapper mapper = new ContextMapper() { - public Object mapFromContext(Object ctx) { - DirContextAdapter adapter = (DirContextAdapter) ctx; - String[] members = adapter.getStringAttributes("uniqueMember"); - return members; - } - }; - List result = tested.search("ou=groups", "(&(objectclass=groupOfUniqueNames)(cn=ROLE_USER))", mapper); - - assertThat(result).hasSize(1); - assertThat(((String[]) result.get(0)).length).isEqualTo(4); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.ContextMapper; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.test.context.ContextConfiguration; + +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. + * + * @author Mattias Hellborg Arthursson + */ +@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. + */ + @Test + public void testSearch_ContextMapper() { + ContextMapper mapper = new PersonContextMapper(); + List result = tested.search("ou=company1,ou=Sweden", "(&(objectclass=person)(sn=Person2))", mapper); + + assertThat(result).hasSize(1); + Person person = (Person) result.get(0); + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).isEqualTo("Person2"); + assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); + } + + /** + * Demonstrates how to retrieve all values of a multi-value attribute. + * + * @see LdapTemplateAttributesMapperITest#testSearch_AttributesMapper_MultiValue() + */ + @Test + public void testSearch_ContextMapper_MultiValue() throws Exception { + ContextMapper mapper = new ContextMapper() { + public Object mapFromContext(Object ctx) { + DirContextAdapter adapter = (DirContextAdapter) ctx; + String[] members = adapter.getStringAttributes("uniqueMember"); + return members; + } + }; + List result = tested.search("ou=groups", "(&(objectclass=groupOfUniqueNames)(cn=ROLE_USER))", mapper); + + 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 a30688a4..4434e6c9 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 @@ -1,160 +1,160 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.support.CountNameClassPairCallbackHandler; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.test.AttributeCheckContextMapper; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.ldap.LdapName; -import java.util.LinkedList; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Tests for LdapTemplate's list methods. - * - * @author Ulrik Sandberg - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -public class LdapTemplateListITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - private AttributeCheckContextMapper contextMapper; - - private static final String BASE_STRING = ""; - - private static final LdapName BASE_NAME = LdapUtils.newLdapName(BASE_STRING); - - private static final String[] ALL_ATTRIBUTES = { "cn", "sn", "description", "telephoneNumber" }; - - private static final String[] ALL_VALUES = { "Some Person", "Person", "Sweden, Company2, Some Person", - "+46 555-456321" }; - - @Before - public void prepareTestedInstance() throws Exception { - contextMapper = new AttributeCheckContextMapper(); - } - - @After - public void tearDown() throws Exception { - contextMapper = null; - } - - @Test - public void testListBindings_ContextMapper() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.listBindings("ou=company2,ou=Sweden" + BASE_STRING, contextMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testListBindings_ContextMapper_Name() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - LdapName dn = LdapUtils.newLdapName("ou=company2,ou=Sweden"); - List list = tested.listBindings(dn, contextMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testListBindings_ContextMapper_MapToPersons() { - LdapName dn = LdapUtils.newLdapName("ou=company1,ou=Sweden"); - List list = tested.listBindings(dn, new PersonContextMapper()); - assertThat(list).hasSize(3); - String personClass = "org.springframework.ldap.itest.Person"; - assertThat(list.get(0).getClass().getName()).isEqualTo(personClass); - assertThat(list.get(1).getClass().getName()).isEqualTo(personClass); - assertThat(list.get(2).getClass().getName()).isEqualTo(personClass); - } - - @Test - public void testList() { - List list = tested.list(BASE_STRING); - assertThat(list).hasSize(3); - verifyBindings(list); - } - - private void verifyBindings(List list) { - LinkedList transformed = new LinkedList(); - - for (String s : list) { - transformed.add(LdapUtils.newLdapName(s)); - } - - assertThat(transformed.contains(LdapUtils.newLdapName("ou=groups"))).isTrue(); - assertThat(transformed.contains(LdapUtils.newLdapName("ou=Norway"))).isTrue(); - assertThat(transformed.contains(LdapUtils.newLdapName("ou=Sweden"))).isTrue(); - } - - @Test - public void testList_Name() { - List list = tested.list(BASE_NAME); - assertThat(list).hasSize(3); - verifyBindings(list); - } - - @Test - public void testList_Handler() throws Exception { - CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); - tested.list(BASE_STRING, handler); - assertThat(handler.getNoOfRows()).isEqualTo(3); - } - - @Test - public void testList_Name_Handler() throws Exception { - CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); - tested.list(BASE_NAME, handler); - assertThat(handler.getNoOfRows()).isEqualTo(3); - } - - @Test - public void testListBindings() { - List list = tested.listBindings(BASE_STRING); - assertThat(list).hasSize(3); - verifyBindings(list); - } - - @Test - public void testListBindings_Name() { - List list = tested.listBindings(BASE_NAME); - assertThat(list).hasSize(3); - } - - @Test - public void testListBindings_Handler() throws Exception { - CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); - tested.listBindings(BASE_STRING, handler); - assertThat(handler.getNoOfRows()).isEqualTo(3); - } - - @Test - public void testListBindings_Name_Handler() throws Exception { - CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); - tested.listBindings(BASE_NAME, handler); - assertThat(handler.getNoOfRows()).isEqualTo(3); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.support.CountNameClassPairCallbackHandler; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.test.AttributeCheckContextMapper; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.ldap.LdapName; +import java.util.LinkedList; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Tests for LdapTemplate's list methods. + * + * @author Ulrik Sandberg + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +public class LdapTemplateListITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + private AttributeCheckContextMapper contextMapper; + + private static final String BASE_STRING = ""; + + private static final LdapName BASE_NAME = LdapUtils.newLdapName(BASE_STRING); + + private static final String[] ALL_ATTRIBUTES = { "cn", "sn", "description", "telephoneNumber" }; + + private static final String[] ALL_VALUES = { "Some Person", "Person", "Sweden, Company2, Some Person", + "+46 555-456321" }; + + @Before + public void prepareTestedInstance() throws Exception { + contextMapper = new AttributeCheckContextMapper(); + } + + @After + public void tearDown() throws Exception { + contextMapper = null; + } + + @Test + public void testListBindings_ContextMapper() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + List list = tested.listBindings("ou=company2,ou=Sweden" + BASE_STRING, contextMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testListBindings_ContextMapper_Name() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + LdapName dn = LdapUtils.newLdapName("ou=company2,ou=Sweden"); + List list = tested.listBindings(dn, contextMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testListBindings_ContextMapper_MapToPersons() { + LdapName dn = LdapUtils.newLdapName("ou=company1,ou=Sweden"); + List list = tested.listBindings(dn, new PersonContextMapper()); + assertThat(list).hasSize(3); + String personClass = "org.springframework.ldap.itest.Person"; + assertThat(list.get(0).getClass().getName()).isEqualTo(personClass); + assertThat(list.get(1).getClass().getName()).isEqualTo(personClass); + assertThat(list.get(2).getClass().getName()).isEqualTo(personClass); + } + + @Test + public void testList() { + List list = tested.list(BASE_STRING); + assertThat(list).hasSize(3); + verifyBindings(list); + } + + private void verifyBindings(List list) { + LinkedList transformed = new LinkedList(); + + for (String s : list) { + transformed.add(LdapUtils.newLdapName(s)); + } + + assertThat(transformed.contains(LdapUtils.newLdapName("ou=groups"))).isTrue(); + assertThat(transformed.contains(LdapUtils.newLdapName("ou=Norway"))).isTrue(); + assertThat(transformed.contains(LdapUtils.newLdapName("ou=Sweden"))).isTrue(); + } + + @Test + public void testList_Name() { + List list = tested.list(BASE_NAME); + assertThat(list).hasSize(3); + verifyBindings(list); + } + + @Test + public void testList_Handler() throws Exception { + CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); + tested.list(BASE_STRING, handler); + assertThat(handler.getNoOfRows()).isEqualTo(3); + } + + @Test + public void testList_Name_Handler() throws Exception { + CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); + tested.list(BASE_NAME, handler); + assertThat(handler.getNoOfRows()).isEqualTo(3); + } + + @Test + public void testListBindings() { + List list = tested.listBindings(BASE_STRING); + assertThat(list).hasSize(3); + verifyBindings(list); + } + + @Test + public void testListBindings_Name() { + List list = tested.listBindings(BASE_NAME); + assertThat(list).hasSize(3); + } + + @Test + public void testListBindings_Handler() throws Exception { + CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); + tested.listBindings(BASE_STRING, handler); + assertThat(handler.getNoOfRows()).isEqualTo(3); + } + + @Test + public void testListBindings_Name_Handler() throws Exception { + CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); + 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 ee975bed..e36dc5c5 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 @@ -1,186 +1,186 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.AttributesMapper; -import org.springframework.ldap.core.ContextMapper; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import javax.naming.ldap.LdapName; - -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"}) -public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - /** - * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. - */ - @Test - public void testLookup_Plain() { - DirContextAdapter result = (DirContextAdapter) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); - - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); - assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2"); - } - - /** - * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. - */ - @Test - public void testLookupContextRoot() { - DirContextAdapter result = (DirContextAdapter) tested.lookup(""); - - assertThat(result.getDn().toString()).isEqualTo(""); - assertThat(result.getNameInNamespace()).isEqualTo(base); - } - - @Test - public void testLookup_AttributesMapper() { - AttributesMapper mapper = new PersonAttributesMapper(); - Person person = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).isEqualTo("Person2"); - assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); - } - - @Test - public void testLookup_AttributesMapper_LdapName() { - AttributesMapper mapper = new PersonAttributesMapper(); - Person person = (Person) tested.lookup(LdapUtils.newLdapName("cn=Some Person2, ou=company1,ou=Sweden"), mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).isEqualTo("Person2"); - assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); - } - - /** - * 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. - * - * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes) - */ - public Object mapFromAttributes(Attributes attributes) throws NamingException { - Person person = new Person(); - person.setFullname((String) attributes.get("cn").get()); - assertThat(attributes.get("sn")).as("sn should be null").isNull(); - 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. - */ - @Test - public void testLookup_ReturnAttributes_AttributesMapper() { - AttributesMapper mapper = new SubsetPersonAttributesMapper(); - - Person person = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", new String[] { "cn" }, mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).as("lastName should not be set").isNull(); - assertThat(person.getDescription()).as("description should not be set").isNull(); - } - - /** - * 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 = (Person) tested.lookup(LdapUtils.newLdapName("cn=Some Person2, ou=company1,ou=Sweden"), - new String[] { "cn" }, mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).as("lastName should not be set").isNull(); - assertThat(person.getDescription()).as("description should not be set").isNull(); - } - - /** - * This method depends on a DirObjectFactory ( - * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. - */ - @Test - public void testLookup_ContextMapper() { - ContextMapper mapper = new PersonContextMapper(); - Person person = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).isEqualTo("Person2"); - assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); - } - - /** - * 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 = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", new String[] { "cn" }, mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person2"); - assertThat(person.getLastname()).as("lastName should not be set").isNull(); - assertThat(person.getDescription()).as("description should not be set").isNull(); - } - - @Test - public void testLookup_GetNameInNamespace_Plain() { - String expectedDn = "cn=Some Person2, ou=company1,ou=Sweden"; - DirContextAdapter result = (DirContextAdapter) tested.lookup(expectedDn); - - LdapName expectedName = LdapUtils.newLdapName(expectedDn); - assertThat(result.getDn()).isEqualTo(expectedName); - assertThat(result.getNameInNamespace()).isEqualTo("cn=Some Person2,ou=company1,ou=Sweden," + base); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.ContextMapper; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import javax.naming.ldap.LdapName; + +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"}) +public class LdapTemplateLookupITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + /** + * This method depends on a DirObjectFactory ( + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) + * being set in the ContextSource. + */ + @Test + public void testLookup_Plain() { + DirContextAdapter result = (DirContextAdapter) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); + + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); + assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2"); + } + + /** + * This method depends on a DirObjectFactory ( + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) + * being set in the ContextSource. + */ + @Test + public void testLookupContextRoot() { + DirContextAdapter result = (DirContextAdapter) tested.lookup(""); + + assertThat(result.getDn().toString()).isEqualTo(""); + assertThat(result.getNameInNamespace()).isEqualTo(base); + } + + @Test + public void testLookup_AttributesMapper() { + AttributesMapper mapper = new PersonAttributesMapper(); + Person person = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).isEqualTo("Person2"); + assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); + } + + @Test + public void testLookup_AttributesMapper_LdapName() { + AttributesMapper mapper = new PersonAttributesMapper(); + Person person = (Person) tested.lookup(LdapUtils.newLdapName("cn=Some Person2, ou=company1,ou=Sweden"), mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).isEqualTo("Person2"); + assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); + } + + /** + * 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. + * + * @see org.springframework.ldap.core.AttributesMapper#mapFromAttributes(javax.naming.directory.Attributes) + */ + public Object mapFromAttributes(Attributes attributes) throws NamingException { + Person person = new Person(); + person.setFullname((String) attributes.get("cn").get()); + assertThat(attributes.get("sn")).as("sn should be null").isNull(); + 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. + */ + @Test + public void testLookup_ReturnAttributes_AttributesMapper() { + AttributesMapper mapper = new SubsetPersonAttributesMapper(); + + Person person = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", new String[] { "cn" }, mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).as("lastName should not be set").isNull(); + assertThat(person.getDescription()).as("description should not be set").isNull(); + } + + /** + * 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 = (Person) tested.lookup(LdapUtils.newLdapName("cn=Some Person2, ou=company1,ou=Sweden"), + new String[] { "cn" }, mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).as("lastName should not be set").isNull(); + assertThat(person.getDescription()).as("description should not be set").isNull(); + } + + /** + * This method depends on a DirObjectFactory ( + * {@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) + * being set in the ContextSource. + */ + @Test + public void testLookup_ContextMapper() { + ContextMapper mapper = new PersonContextMapper(); + Person person = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).isEqualTo("Person2"); + assertThat(person.getDescription()).isEqualTo("Sweden, Company1, Some Person2"); + } + + /** + * 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 = (Person) tested.lookup("cn=Some Person2, ou=company1,ou=Sweden", new String[] { "cn" }, mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person2"); + assertThat(person.getLastname()).as("lastName should not be set").isNull(); + assertThat(person.getDescription()).as("description should not be set").isNull(); + } + + @Test + public void testLookup_GetNameInNamespace_Plain() { + String expectedDn = "cn=Some Person2, ou=company1,ou=Sweden"; + DirContextAdapter result = (DirContextAdapter) tested.lookup(expectedDn); + + LdapName expectedName = LdapUtils.newLdapName(expectedDn); + 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 1dfd5b02..d5b29219 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 @@ -1,86 +1,86 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.ldap.core.AttributesMapper; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.test.context.ContextConfiguration; - -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"}) -public class LdapTemplateLookupMultiRdnITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - protected Resource getLdifFileResource() { - 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. - */ - @Test - @Category(NoAdTest.class) - public void testLookup_MultiValuedRdn() { - AttributesMapper mapper = new PersonAttributesMapper(); - Person person = (Person) tested.lookup("cn=Some Person+sn=Person, ou=company1,ou=Norway", mapper); - - assertThat(person.getFullname()).isEqualTo("Some Person"); - assertThat(person.getLastname()).isEqualTo("Person"); - assertThat(person.getDescription()).isEqualTo("Norway, Company1, Some Person+Person"); - } - - /** - * 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) - public void testLookup_MultiValuedRdn_DirContextAdapter() { - DirContextAdapter result = (DirContextAdapter) tested.lookup("cn=Some Person+sn=Person, ou=company1,ou=Norway"); - - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person"); - assertThat(result.getStringAttribute("description")).isEqualTo("Norway, Company1, Some Person+Person"); - } - - @Test - @Category(NoAdTest.class) - public void testLookup_GetNameInNamespace_MultiRdn() { - DirContextAdapter result = (DirContextAdapter) tested.lookup("cn=Some Person+sn=Person,ou=company1,ou=Norway"); - - 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); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.test.context.ContextConfiguration; + +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"}) +public class LdapTemplateLookupMultiRdnITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + protected Resource getLdifFileResource() { + 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. + */ + @Test + @Category(NoAdTest.class) + public void testLookup_MultiValuedRdn() { + AttributesMapper mapper = new PersonAttributesMapper(); + Person person = (Person) tested.lookup("cn=Some Person+sn=Person, ou=company1,ou=Norway", mapper); + + assertThat(person.getFullname()).isEqualTo("Some Person"); + assertThat(person.getLastname()).isEqualTo("Person"); + assertThat(person.getDescription()).isEqualTo("Norway, Company1, Some Person+Person"); + } + + /** + * 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) + public void testLookup_MultiValuedRdn_DirContextAdapter() { + DirContextAdapter result = (DirContextAdapter) tested.lookup("cn=Some Person+sn=Person, ou=company1,ou=Norway"); + + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person"); + assertThat(result.getStringAttribute("description")).isEqualTo("Norway, Company1, Some Person+Person"); + } + + @Test + @Category(NoAdTest.class) + public void testLookup_GetNameInNamespace_MultiRdn() { + DirContextAdapter result = (DirContextAdapter) tested.lookup("cn=Some Person+sn=Person,ou=company1,ou=Norway"); + + 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 a22a05aa..cc43354c 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 @@ -1,284 +1,284 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.AttributeInUseException; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.directory.Attributes; -import javax.naming.directory.BasicAttribute; -import javax.naming.directory.BasicAttributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.ModificationItem; -import java.util.Arrays; -import java.util.List; - -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 - * /src/iutest/. - * - * @author Mattias Hellborg Arthursson - * @author Ulrik Sandberg - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - private static String PERSON4_DN = "cn=Some Person4,ou=company1,ou=Sweden"; - - private static String PERSON5_DN = "cn=Some Person5,ou=company1,ou=Sweden"; - - @Before - public void prepareTestedInstance() throws Exception { - DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "Some Person4"); - adapter.setAttributeValue("sn", "Person4"); - adapter.setAttributeValue("description", "Some description"); - - tested.bind(PERSON4_DN, adapter, null); - - adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "Some Person5"); - adapter.setAttributeValue("sn", "Person5"); - adapter.setAttributeValues("description", new String[] { "qwe", "123", "rty", "uio" }); - - tested.bind(PERSON5_DN, adapter, null); - - } - - @After - public void cleanup() throws Exception { - tested.unbind(PERSON4_DN); - tested.unbind(PERSON5_DN); - } - - @Test - public void testRebind_Attributes_Plain() { - Attributes attributes = setupAttributes(); - - tested.rebind(PERSON4_DN, null, attributes); - - verifyBoundCorrectData(); - } - - @Test - public void testRebind_Attributes_LdapName() { - Attributes attributes = setupAttributes(); - - tested.rebind(LdapUtils.newLdapName(PERSON4_DN), null, attributes); - - verifyBoundCorrectData(); - } - - @Test - public void testModifyAttributes_MultiValueReplace() { - BasicAttribute attr = new BasicAttribute("description", "Some other description"); - attr.add("Another description"); - ModificationItem[] mods = new ModificationItem[1]; - mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr); - - tested.modifyAttributes(PERSON4_DN, mods); - - DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN); - List attributes = Arrays.asList(result.getStringAttributes("description")); - assertThat(attributes).hasSize(2); - assertThat(attributes.contains("Some other description")).isTrue(); - assertThat(attributes.contains("Another description")).isTrue(); - } - - @Test - public void testModifyAttributes_MultiValueAdd() { - BasicAttribute attr = new BasicAttribute("description", "Some other description"); - attr.add("Another description"); - ModificationItem[] mods = new ModificationItem[1]; - mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr); - - tested.modifyAttributes(PERSON4_DN, mods); - - DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN); - List attributes = Arrays.asList(result.getStringAttributes("description")); - assertThat(attributes).hasSize(3); - assertThat(attributes.contains("Some other description")).isTrue(); - assertThat(attributes.contains("Another description")).isTrue(); - assertThat(attributes.contains("Some description")).isTrue(); - } - - @Test - public void testModifyAttributes_AddAttributeValueWithExistingValue() { - DirContextOperations ctx = tested.lookupContext("cn=ROLE_USER,ou=groups"); - ctx.addAttributeValue("uniqueMember", "cn=Some Person,ou=company1,ou=Norway," + base); - tested.modifyAttributes(ctx); - assertThat(true).isTrue(); - } - - @Test - public void testModifyAttributes_MultiValueAddDuplicateToUnordered() { - BasicAttribute attr = new BasicAttribute("description", "Some description"); - ModificationItem[] mods = new ModificationItem[1]; - mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr); - - try { - tested.modifyAttributes(PERSON4_DN, mods); - fail("AttributeInUseException expected"); - } - catch (AttributeInUseException expected) { - // expected - } - } - - /** - * 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. - */ - @Test - public void testModifyAttributes_MultiValueAddDuplicateToOrdered() { - BasicAttribute attr = new BasicAttribute("description", "Some other description", true); // ordered - attr.add("Another description"); - // Commented out duplicate to make test work for Apache DS - // attr.add("Some description"); - ModificationItem[] mods = new ModificationItem[1]; - mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr); - - tested.modifyAttributes(PERSON4_DN, mods); - - DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN); - List attributes = Arrays.asList(result.getStringAttributes("description")); - assertThat(attributes).hasSize(3); - assertThat(attributes.contains("Some other description")).isTrue(); - assertThat(attributes.contains("Another description")).isTrue(); - assertThat(attributes.contains("Some description")).isTrue(); - } - - @Test - public void testModifyAttributes_Plain() { - ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description", - "Some other description")); - - tested.modifyAttributes(PERSON4_DN, new ModificationItem[] { item }); - - verifyBoundCorrectData(); - } - - @Test - public void testModifyAttributes_LdapName() { - ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description", - "Some other description")); - - tested.modifyAttributes(LdapUtils.newLdapName(PERSON4_DN), new ModificationItem[] { item }); - - verifyBoundCorrectData(); - } - - @Test - public void testModifyAttributes_DirContextAdapter_MultiAttributes() { - DirContextAdapter adapter = (DirContextAdapter) tested.lookup(PERSON5_DN); - adapter.setAttributeValues("description", new String[] { "qwe", "123", "klytt", "kalle" }); - - tested.modifyAttributes(PERSON5_DN, adapter.getModificationItems()); - - // Verify - adapter = (DirContextAdapter) tested.lookup(PERSON5_DN); - List attributes = Arrays.asList(adapter.getStringAttributes("description")); - assertThat(attributes).hasSize(4); - assertThat(attributes.contains("qwe")).isTrue(); - assertThat(attributes.contains("123")).isTrue(); - assertThat(attributes.contains("klytt")).isTrue(); - assertThat(attributes.contains("kalle")).isTrue(); - } - - /** - * 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 { - DirContextAdapter adapter = (DirContextAdapter) tested.lookup(PERSON4_DN); - - adapter.setAttributeValue("description", "Some other description"); - - ModificationItem[] modificationItems = adapter.getModificationItems(); - tested.modifyAttributes(PERSON4_DN, modificationItems); - - verifyBoundCorrectData(); - } - - @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.getModificationItems(); - - tested.modifyAttributes(ctx); - } - - /** - * This test originally failed on ApacheDS complaining that the uniqueMember attribute - * was emptied. - */ - @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.getModificationItems(); - - tested.modifyAttributes(ctx); - } - private Attributes setupAttributes() { - Attributes attributes = new BasicAttributes(); - BasicAttribute ocattr = new BasicAttribute("objectclass"); - ocattr.add("top"); - ocattr.add("person"); - attributes.put(ocattr); - attributes.put("cn", "Some Person4"); - attributes.put("sn", "Person4"); - attributes.put("description", "Some other description"); - return attributes; - } - - private void verifyBoundCorrectData() { - DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN); - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person4"); - assertThat(result.getStringAttribute("description")).isEqualTo("Some other description"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.AttributeInUseException; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttribute; +import javax.naming.directory.BasicAttributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.ModificationItem; +import java.util.Arrays; +import java.util.List; + +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 + * /src/iutest/. + * + * @author Mattias Hellborg Arthursson + * @author Ulrik Sandberg + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +public class LdapTemplateModifyITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + private static String PERSON4_DN = "cn=Some Person4,ou=company1,ou=Sweden"; + + private static String PERSON5_DN = "cn=Some Person5,ou=company1,ou=Sweden"; + + @Before + public void prepareTestedInstance() throws Exception { + DirContextAdapter adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "Some Person4"); + adapter.setAttributeValue("sn", "Person4"); + adapter.setAttributeValue("description", "Some description"); + + tested.bind(PERSON4_DN, adapter, null); + + adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "Some Person5"); + adapter.setAttributeValue("sn", "Person5"); + adapter.setAttributeValues("description", new String[] { "qwe", "123", "rty", "uio" }); + + tested.bind(PERSON5_DN, adapter, null); + + } + + @After + public void cleanup() throws Exception { + tested.unbind(PERSON4_DN); + tested.unbind(PERSON5_DN); + } + + @Test + public void testRebind_Attributes_Plain() { + Attributes attributes = setupAttributes(); + + tested.rebind(PERSON4_DN, null, attributes); + + verifyBoundCorrectData(); + } + + @Test + public void testRebind_Attributes_LdapName() { + Attributes attributes = setupAttributes(); + + tested.rebind(LdapUtils.newLdapName(PERSON4_DN), null, attributes); + + verifyBoundCorrectData(); + } + + @Test + public void testModifyAttributes_MultiValueReplace() { + BasicAttribute attr = new BasicAttribute("description", "Some other description"); + attr.add("Another description"); + ModificationItem[] mods = new ModificationItem[1]; + mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, attr); + + tested.modifyAttributes(PERSON4_DN, mods); + + DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN); + List attributes = Arrays.asList(result.getStringAttributes("description")); + assertThat(attributes).hasSize(2); + assertThat(attributes.contains("Some other description")).isTrue(); + assertThat(attributes.contains("Another description")).isTrue(); + } + + @Test + public void testModifyAttributes_MultiValueAdd() { + BasicAttribute attr = new BasicAttribute("description", "Some other description"); + attr.add("Another description"); + ModificationItem[] mods = new ModificationItem[1]; + mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr); + + tested.modifyAttributes(PERSON4_DN, mods); + + DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN); + List attributes = Arrays.asList(result.getStringAttributes("description")); + assertThat(attributes).hasSize(3); + assertThat(attributes.contains("Some other description")).isTrue(); + assertThat(attributes.contains("Another description")).isTrue(); + assertThat(attributes.contains("Some description")).isTrue(); + } + + @Test + public void testModifyAttributes_AddAttributeValueWithExistingValue() { + DirContextOperations ctx = tested.lookupContext("cn=ROLE_USER,ou=groups"); + ctx.addAttributeValue("uniqueMember", "cn=Some Person,ou=company1,ou=Norway," + base); + tested.modifyAttributes(ctx); + assertThat(true).isTrue(); + } + + @Test + public void testModifyAttributes_MultiValueAddDuplicateToUnordered() { + BasicAttribute attr = new BasicAttribute("description", "Some description"); + ModificationItem[] mods = new ModificationItem[1]; + mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr); + + try { + tested.modifyAttributes(PERSON4_DN, mods); + fail("AttributeInUseException expected"); + } + catch (AttributeInUseException expected) { + // expected + } + } + + /** + * 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. + */ + @Test + public void testModifyAttributes_MultiValueAddDuplicateToOrdered() { + BasicAttribute attr = new BasicAttribute("description", "Some other description", true); // ordered + attr.add("Another description"); + // Commented out duplicate to make test work for Apache DS + // attr.add("Some description"); + ModificationItem[] mods = new ModificationItem[1]; + mods[0] = new ModificationItem(DirContext.ADD_ATTRIBUTE, attr); + + tested.modifyAttributes(PERSON4_DN, mods); + + DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN); + List attributes = Arrays.asList(result.getStringAttributes("description")); + assertThat(attributes).hasSize(3); + assertThat(attributes.contains("Some other description")).isTrue(); + assertThat(attributes.contains("Another description")).isTrue(); + assertThat(attributes.contains("Some description")).isTrue(); + } + + @Test + public void testModifyAttributes_Plain() { + ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description", + "Some other description")); + + tested.modifyAttributes(PERSON4_DN, new ModificationItem[] { item }); + + verifyBoundCorrectData(); + } + + @Test + public void testModifyAttributes_LdapName() { + ModificationItem item = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute("description", + "Some other description")); + + tested.modifyAttributes(LdapUtils.newLdapName(PERSON4_DN), new ModificationItem[] { item }); + + verifyBoundCorrectData(); + } + + @Test + public void testModifyAttributes_DirContextAdapter_MultiAttributes() { + DirContextAdapter adapter = (DirContextAdapter) tested.lookup(PERSON5_DN); + adapter.setAttributeValues("description", new String[] { "qwe", "123", "klytt", "kalle" }); + + tested.modifyAttributes(PERSON5_DN, adapter.getModificationItems()); + + // Verify + adapter = (DirContextAdapter) tested.lookup(PERSON5_DN); + List attributes = Arrays.asList(adapter.getStringAttributes("description")); + assertThat(attributes).hasSize(4); + assertThat(attributes.contains("qwe")).isTrue(); + assertThat(attributes.contains("123")).isTrue(); + assertThat(attributes.contains("klytt")).isTrue(); + assertThat(attributes.contains("kalle")).isTrue(); + } + + /** + * 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 { + DirContextAdapter adapter = (DirContextAdapter) tested.lookup(PERSON4_DN); + + adapter.setAttributeValue("description", "Some other description"); + + ModificationItem[] modificationItems = adapter.getModificationItems(); + tested.modifyAttributes(PERSON4_DN, modificationItems); + + verifyBoundCorrectData(); + } + + @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.getModificationItems(); + + tested.modifyAttributes(ctx); + } + + /** + * This test originally failed on ApacheDS complaining that the uniqueMember attribute + * was emptied. + */ + @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.getModificationItems(); + + tested.modifyAttributes(ctx); + } + private Attributes setupAttributes() { + Attributes attributes = new BasicAttributes(); + BasicAttribute ocattr = new BasicAttribute("objectclass"); + ocattr.add("top"); + ocattr.add("person"); + attributes.put(ocattr); + attributes.put("cn", "Some Person4"); + attributes.put("sn", "Person4"); + attributes.put("description", "Some other description"); + return attributes; + } + + private void verifyBoundCorrectData() { + DirContextAdapter result = (DirContextAdapter) tested.lookup(PERSON4_DN); + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); + 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 998ed7ce..dbfb2380 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 @@ -1,103 +1,103 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.support.CountNameClassPairCallbackHandler; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.Name; -import javax.naming.ldap.LdapName; - -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. - * - * NOTE: This test will not work under Java 1.4.1 or earlier. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateNoBaseSuffixTestContext.xml"}) -public class LdapTemplateNoBaseSuffixITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - @Override - protected Name getRoot() { - return LdapUtils.newLdapName(base); - } - - /** - * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) - * being set in the ContextSource. - */ - @Test - public void testLookup_Plain() { - String expectedDn = "cn=Some Person2, ou=company1, ou=Sweden," + base; - DirContextAdapter result = (DirContextAdapter) tested.lookup(expectedDn); - - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); - assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2"); - - LdapName expectedName = LdapUtils.newLdapName(expectedDn); - assertThat(result.getDn()).isEqualTo(expectedName); - assertThat(result.getNameInNamespace()).isEqualTo(expectedDn); - } - - @Test - public void testSearch_Plain() { - CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); - - tested.search(base, "(objectclass=person)", handler); - assertThat(handler.getNoOfRows()).isEqualTo(5); - } - - @Test - public void testBindAndUnbind_Plain() { - DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "Some Person4"); - 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); - - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person4"); - assertThat(result.getDn()).isEqualTo(LdapUtils.newLdapName("cn=Some Person4,ou=company1,ou=Sweden," + base)); - - tested.unbind("cn=Some Person4,ou=company1,ou=Sweden," + base); - try { - tested.lookup("cn=Some Person4, ou=company1, ou=Sweden," + base); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.support.CountNameClassPairCallbackHandler; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.Name; +import javax.naming.ldap.LdapName; + +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. + * + * NOTE: This test will not work under Java 1.4.1 or earlier. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateNoBaseSuffixTestContext.xml"}) +public class LdapTemplateNoBaseSuffixITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + @Override + protected Name getRoot() { + return LdapUtils.newLdapName(base); + } + + /** + * This method depends on a DirObjectFactory ({@link org.springframework.ldap.core.support.DefaultDirObjectFactory}) + * being set in the ContextSource. + */ + @Test + public void testLookup_Plain() { + String expectedDn = "cn=Some Person2, ou=company1, ou=Sweden," + base; + DirContextAdapter result = (DirContextAdapter) tested.lookup(expectedDn); + + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); + assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2"); + + LdapName expectedName = LdapUtils.newLdapName(expectedDn); + assertThat(result.getDn()).isEqualTo(expectedName); + assertThat(result.getNameInNamespace()).isEqualTo(expectedDn); + } + + @Test + public void testSearch_Plain() { + CountNameClassPairCallbackHandler handler = new CountNameClassPairCallbackHandler(); + + tested.search(base, "(objectclass=person)", handler); + assertThat(handler.getNoOfRows()).isEqualTo(5); + } + + @Test + public void testBindAndUnbind_Plain() { + DirContextAdapter adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "Some Person4"); + 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); + + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person4"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person4"); + assertThat(result.getDn()).isEqualTo(LdapUtils.newLdapName("cn=Some Person4,ou=company1,ou=Sweden," + base)); + + tested.unbind("cn=Some Person4,ou=company1,ou=Sweden," + base); + try { + tested.lookup("cn=Some Person4, ou=company1, ou=Sweden," + base); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + 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 767ac0db..384dec30 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 @@ -1,86 +1,86 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.After; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.ClassPathResource; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.test.LdapTestUtils; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; - -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. - */ -@ContextConfiguration(locations = {"/conf/ldapTemplatePooledTestContext.xml"}) -public class LdapTemplatePooledITest extends AbstractJUnit4SpringContextTests { - - @Autowired - private LdapTemplate tested; - - @Autowired - private ContextSource contextSource; - - @Value("${base}") - protected String base; - - @After - public void cleanup() throws Exception { - LdapTestUtils.shutdownEmbeddedServer(); - } - - /** - * This method depends on a DirObjectFactory ( - * {@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")); - - DirContextOperations result = tested.lookupContext("cn=Some Person2, ou=company1,ou=Sweden"); - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); - assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2"); - - // Shutdown server and kill all existing connections - LdapTestUtils.shutdownEmbeddedServer(); - LdapTestUtils.startEmbeddedServer(1888, "dc=261consulting,dc=com", "jayway"); - - try { - tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); - fail("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. - tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.After; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.io.ClassPathResource; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.test.LdapTestUtils; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; + +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. + */ +@ContextConfiguration(locations = {"/conf/ldapTemplatePooledTestContext.xml"}) +public class LdapTemplatePooledITest extends AbstractJUnit4SpringContextTests { + + @Autowired + private LdapTemplate tested; + + @Autowired + private ContextSource contextSource; + + @Value("${base}") + protected String base; + + @After + public void cleanup() throws Exception { + LdapTestUtils.shutdownEmbeddedServer(); + } + + /** + * This method depends on a DirObjectFactory ( + * {@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")); + + DirContextOperations result = tested.lookupContext("cn=Some Person2, ou=company1,ou=Sweden"); + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person2"); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); + assertThat(result.getStringAttribute("description")).isEqualTo("Sweden, Company1, Some Person2"); + + // Shutdown server and kill all existing connections + LdapTestUtils.shutdownEmbeddedServer(); + LdapTestUtils.startEmbeddedServer(1888, "dc=261consulting,dc=com", "jayway"); + + try { + tested.lookup("cn=Some Person2, ou=company1,ou=Sweden"); + fail("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. + 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 dee26e35..f2d6026a 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 @@ -1,132 +1,132 @@ -/* - * Copyright 2005-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.Name; -import javax.naming.ldap.LdapName; - -import static junit.framework.Assert.fail; - -/** - * 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"}) -public class LdapTemplateRecursiveDeleteITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - private static LdapName DN = LdapUtils.newLdapName("cn=Some Person5,ou=company1,ou=Sweden"); - - private LdapName firstSubDn; - - private LdapName secondSubDn; - - private LdapName leafDn; - - @Before - public void prepareTestedInstance() throws Exception { - DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "Some Person5"); - adapter.setAttributeValue("sn", "Person5"); - adapter.setAttributeValue("description", "Some description"); - tested.bind(DN, adapter, null); - - firstSubDn = LdapUtils.newLdapName("cn=subPerson"); - firstSubDn = LdapUtils.prepend(firstSubDn, DN); - - adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "subPerson"); - adapter.setAttributeValue("sn", "subPerson"); - adapter.setAttributeValue("description", "Should be recursively deleted"); - tested.bind(firstSubDn, adapter, null); - secondSubDn = LdapUtils.newLdapName("cn=subPerson2"); - secondSubDn = LdapUtils.prepend(secondSubDn, DN); - - adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "subPerson2"); - adapter.setAttributeValue("sn", "subPerson2"); - adapter.setAttributeValue("description", "Should be recursively deleted"); - tested.bind(secondSubDn, adapter, null); - - leafDn = LdapUtils.newLdapName("cn=subSubPerson"); - leafDn = LdapUtils.prepend(leafDn, DN); - - adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "subSubPerson"); - adapter.setAttributeValue("sn", "subSubPerson"); - adapter.setAttributeValue("description", "Should be recursively deleted"); - tested.bind(leafDn, adapter, null); - } - - @After - public void cleanup() throws Exception { - try { - tested.unbind(DN, true); - } - catch (NameNotFoundException ignore) { - // ignore - } - } - - @Test - @Category(NoAdTest.class) - public void testRecursiveUnbind() { - tested.unbind(DN, true); - - verifyDeleted(DN); - verifyDeleted(firstSubDn); - verifyDeleted(secondSubDn); - verifyDeleted(leafDn); - } - - @Test - @Category(NoAdTest.class) - public void testRecursiveUnbindOnLeaf() { - tested.unbind(leafDn, true); - verifyDeleted(leafDn); - } - - private void verifyDeleted(Name dn) { - try { - tested.lookup(dn); - fail("Expected entry '" + dn + "' to be non-existent"); - } - catch (NameNotFoundException expected) { - // expected - } - } -} +/* + * Copyright 2005-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.Name; +import javax.naming.ldap.LdapName; + +import static junit.framework.Assert.fail; + +/** + * 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"}) +public class LdapTemplateRecursiveDeleteITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + private static LdapName DN = LdapUtils.newLdapName("cn=Some Person5,ou=company1,ou=Sweden"); + + private LdapName firstSubDn; + + private LdapName secondSubDn; + + private LdapName leafDn; + + @Before + public void prepareTestedInstance() throws Exception { + DirContextAdapter adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "Some Person5"); + adapter.setAttributeValue("sn", "Person5"); + adapter.setAttributeValue("description", "Some description"); + tested.bind(DN, adapter, null); + + firstSubDn = LdapUtils.newLdapName("cn=subPerson"); + firstSubDn = LdapUtils.prepend(firstSubDn, DN); + + adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "subPerson"); + adapter.setAttributeValue("sn", "subPerson"); + adapter.setAttributeValue("description", "Should be recursively deleted"); + tested.bind(firstSubDn, adapter, null); + secondSubDn = LdapUtils.newLdapName("cn=subPerson2"); + secondSubDn = LdapUtils.prepend(secondSubDn, DN); + + adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "subPerson2"); + adapter.setAttributeValue("sn", "subPerson2"); + adapter.setAttributeValue("description", "Should be recursively deleted"); + tested.bind(secondSubDn, adapter, null); + + leafDn = LdapUtils.newLdapName("cn=subSubPerson"); + leafDn = LdapUtils.prepend(leafDn, DN); + + adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "subSubPerson"); + adapter.setAttributeValue("sn", "subSubPerson"); + adapter.setAttributeValue("description", "Should be recursively deleted"); + tested.bind(leafDn, adapter, null); + } + + @After + public void cleanup() throws Exception { + try { + tested.unbind(DN, true); + } + catch (NameNotFoundException ignore) { + // ignore + } + } + + @Test + @Category(NoAdTest.class) + public void testRecursiveUnbind() { + tested.unbind(DN, true); + + verifyDeleted(DN); + verifyDeleted(firstSubDn); + verifyDeleted(secondSubDn); + verifyDeleted(leafDn); + } + + @Test + @Category(NoAdTest.class) + public void testRecursiveUnbindOnLeaf() { + tested.unbind(leafDn, true); + verifyDeleted(leafDn); + } + + private void verifyDeleted(Name dn) { + try { + tested.lookup(dn); + fail("Expected entry '" + dn + "' to be non-existent"); + } + catch (NameNotFoundException expected) { + // 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 cadf72d0..a0cb22cc 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 @@ -1,103 +1,103 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.Name; - -import static org.assertj.core.api.Assertions.assertThat; -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. * - * - * @author Ulrik Sandberg - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -public class LdapTemplateRenameITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - private static String DN = "cn=Some Person6,ou=company1,ou=Sweden"; - - private static String NEWDN = "cn=Some Person6,ou=company2,ou=Sweden"; - - @Before - public void prepareTestedInstance() throws Exception { - DirContextAdapter adapter = new DirContextAdapter(); - adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); - adapter.setAttributeValue("cn", "Some Person6"); - adapter.setAttributeValue("sn", "Person6"); - adapter.setAttributeValue("description", "Some description"); - - tested.bind(DN, adapter, null); - } - - @After - public void cleanup() throws Exception { - tested.unbind(NEWDN); - tested.unbind(DN); - } - - @Test - public void testRename() { - tested.rename(DN, NEWDN); - - verifyDeleted(LdapUtils.newLdapName(DN)); - verifyBoundCorrectData(); - } - - @Test - public void testRename_LdapName() throws Exception { - Name oldDn = LdapUtils.newLdapName(DN); - Name newDn = LdapUtils.newLdapName(NEWDN); - tested.rename(oldDn, newDn); - - verifyDeleted(oldDn); - verifyBoundCorrectData(); - } - - private void verifyDeleted(Name dn) { - try { - tested.lookup(dn); - fail("Expected entry '" + dn + "' to be non-existent"); - } - catch (NameNotFoundException expected) { - // expected - } - } - - private void verifyBoundCorrectData() { - DirContextAdapter result = (DirContextAdapter) tested.lookup(NEWDN); - assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person6"); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person6"); - assertThat(result.getStringAttribute("description")).isEqualTo("Some description"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.Name; + +import static org.assertj.core.api.Assertions.assertThat; +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. * + * + * @author Ulrik Sandberg + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +public class LdapTemplateRenameITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + private static String DN = "cn=Some Person6,ou=company1,ou=Sweden"; + + private static String NEWDN = "cn=Some Person6,ou=company2,ou=Sweden"; + + @Before + public void prepareTestedInstance() throws Exception { + DirContextAdapter adapter = new DirContextAdapter(); + adapter.setAttributeValues("objectclass", new String[] { "top", "person" }); + adapter.setAttributeValue("cn", "Some Person6"); + adapter.setAttributeValue("sn", "Person6"); + adapter.setAttributeValue("description", "Some description"); + + tested.bind(DN, adapter, null); + } + + @After + public void cleanup() throws Exception { + tested.unbind(NEWDN); + tested.unbind(DN); + } + + @Test + public void testRename() { + tested.rename(DN, NEWDN); + + verifyDeleted(LdapUtils.newLdapName(DN)); + verifyBoundCorrectData(); + } + + @Test + public void testRename_LdapName() throws Exception { + Name oldDn = LdapUtils.newLdapName(DN); + Name newDn = LdapUtils.newLdapName(NEWDN); + tested.rename(oldDn, newDn); + + verifyDeleted(oldDn); + verifyBoundCorrectData(); + } + + private void verifyDeleted(Name dn) { + try { + tested.lookup(dn); + fail("Expected entry '" + dn + "' to be non-existent"); + } + catch (NameNotFoundException expected) { + // expected + } + } + + private void verifyBoundCorrectData() { + DirContextAdapter result = (DirContextAdapter) tested.lookup(NEWDN); + assertThat(result.getStringAttribute("cn")).isEqualTo("Some Person6"); + 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 c0f30a48..0b506870 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 @@ -1,422 +1,422 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.SizeLimitExceededException; -import org.springframework.ldap.core.ContextMapper; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.support.AbstractContextMapper; -import org.springframework.ldap.query.SearchScope; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.test.AttributeCheckAttributesMapper; -import org.springframework.ldap.test.AttributeCheckContextMapper; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.Name; -import javax.naming.NamingException; -import javax.naming.directory.SearchControls; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -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. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - private AttributeCheckAttributesMapper attributesMapper; - - private AttributeCheckContextMapper contextMapper; - - private static final String[] ALL_ATTRIBUTES = { "cn", "sn", "description", "telephoneNumber" }; - - private static final String[] CN_SN_ATTRS = { "cn", "sn" }; - - private static final String[] ABSENT_ATTRIBUTES = { "description", "telephoneNumber" }; - - private static final String[] CN_SN_VALUES = { "Some Person2", "Person2" }; - - private static final String[] ALL_VALUES = { "Some Person2", "Person2", "Sweden, Company1, Some Person2", - "+46 555-654321" }; - - private static final String BASE_STRING = ""; - - private static final String FILTER_STRING = "(&(objectclass=person)(sn=Person2))"; - - private static final Name BASE_NAME = LdapUtils.newLdapName(BASE_STRING); - - @Before - public void prepareTestedInstance() throws Exception { - attributesMapper = new AttributeCheckAttributesMapper(); - contextMapper = new AttributeCheckContextMapper(); - } - - @After - public void cleanup() throws Exception { - attributesMapper = null; - contextMapper = null; - } - - @Test - public void testSearch_AttributesMapper() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_FewerAttributes() { - 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"), - attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_SearchScope() { - 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); - assertThat(list).isEmpty(); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_SearchScope_CorrectBase() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_NoBase() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - - List list = tested.search(query() - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_DifferentBase() { - 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); - assertThat(list).isEmpty(); - } - - @Test - public void testSearch_SearchScope_AttributesMapper() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_AttributesMapper() { - attributesMapper.setExpectedAttributes(CN_SN_ATTRS); - attributesMapper.setExpectedValues(CN_SN_VALUES); - attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, - attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_AttributesMapper_Name() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_AttributesMapper_Name() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_AttributesMapper_Name() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_ContextMapper() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, contextMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearchForObject() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - DirContextAdapter result = (DirContextAdapter) tested - .searchForObject(BASE_STRING, FILTER_STRING, contextMapper); - assertThat(result).isNotNull(); - } - - @Test(expected = IncorrectResultSizeDataAccessException.class) - public void testSearchForObjectWithMultipleHits() { - tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=*))", new AbstractContextMapper() { - @Override - protected Object doMapFromContext(DirContextOperations ctx) { - return ctx; - } - }); - } - - @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; - } - }); - } - - @Test - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_ContextMapper() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_ContextMapper_Name() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, contextMapper); - assertThat(list).hasSize(1); - } - - @Test - 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); - assertThat(list).hasSize(1); - } - - @Test - 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"), - contextMapper); - assertThat(list).hasSize(1); - } - - @Test - 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); - assertThat(list).isEmpty(); - } - - @Test - 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"), - contextMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearchForContext_LdapQuery() { - DirContextOperations result = tested.searchForContext(query() - .where("objectclass").is("person").and("sn").is("Person2")); - - assertThat(result).isNotNull(); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); - } - - @Test(expected = EmptyResultDataAccessException.class) - public void testSearchForContext_LdapQuery_SearchScopeNotFound() { - 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")); - - assertThat(result).isNotNull(); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); - } - - @Test - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_ContextMapper_Name() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearchWithInvalidSearchBaseShouldByDefaultThrowException() { - try { - tested.search(BASE_NAME + "ou=unknown", FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, - contextMapper); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testSearchWithInvalidSearchBaseCanBeConfiguredToSwallowException() { - tested.setIgnoreNameNotFoundException(true); - contextMapper.setExpectedAttributes(CN_SN_ATTRS); - contextMapper.setExpectedValues(CN_SN_VALUES); - contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search(BASE_NAME + "ou=unknown", FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, - contextMapper); - assertThat(list).isEmpty(); - } - - @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(); - } - }); - - assertThat(result).hasSize(3); - } - - @Test(expected = SizeLimitExceededException.class) - public void verifyThatSearchWithCountLimitWithFlagToFalseThrowsException() { - tested.setIgnoreSizeLimitExceededException(false); - tested.search(query() - .countLimit(3) - .where("objectclass").is("person"), new ContextMapper() { - @Override - public Object mapFromContext(Object ctx) throws NamingException { - return new Object(); - } - }); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.SizeLimitExceededException; +import org.springframework.ldap.core.ContextMapper; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.support.AbstractContextMapper; +import org.springframework.ldap.query.SearchScope; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.test.AttributeCheckAttributesMapper; +import org.springframework.ldap.test.AttributeCheckContextMapper; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.Name; +import javax.naming.NamingException; +import javax.naming.directory.SearchControls; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +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. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) +public class LdapTemplateSearchResultITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + private AttributeCheckAttributesMapper attributesMapper; + + private AttributeCheckContextMapper contextMapper; + + private static final String[] ALL_ATTRIBUTES = { "cn", "sn", "description", "telephoneNumber" }; + + private static final String[] CN_SN_ATTRS = { "cn", "sn" }; + + private static final String[] ABSENT_ATTRIBUTES = { "description", "telephoneNumber" }; + + private static final String[] CN_SN_VALUES = { "Some Person2", "Person2" }; + + private static final String[] ALL_VALUES = { "Some Person2", "Person2", "Sweden, Company1, Some Person2", + "+46 555-654321" }; + + private static final String BASE_STRING = ""; + + private static final String FILTER_STRING = "(&(objectclass=person)(sn=Person2))"; + + private static final Name BASE_NAME = LdapUtils.newLdapName(BASE_STRING); + + @Before + public void prepareTestedInstance() throws Exception { + attributesMapper = new AttributeCheckAttributesMapper(); + contextMapper = new AttributeCheckContextMapper(); + } + + @After + public void cleanup() throws Exception { + attributesMapper = null; + contextMapper = null; + } + + @Test + public void testSearch_AttributesMapper() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_FewerAttributes() { + 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"), + attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_SearchScope() { + 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); + assertThat(list).isEmpty(); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_SearchScope_CorrectBase() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_NoBase() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + + List list = tested.search(query() + .where("objectclass").is("person").and("sn").is("Person2"), + attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_DifferentBase() { + 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); + assertThat(list).isEmpty(); + } + + @Test + public void testSearch_SearchScope_AttributesMapper() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_AttributesMapper() { + attributesMapper.setExpectedAttributes(CN_SN_ATTRS); + attributesMapper.setExpectedValues(CN_SN_VALUES); + attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); + List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_AttributesMapper_Name() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_AttributesMapper_Name() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_AttributesMapper_Name() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_ContextMapper() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, contextMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearchForObject() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + DirContextAdapter result = (DirContextAdapter) tested + .searchForObject(BASE_STRING, FILTER_STRING, contextMapper); + assertThat(result).isNotNull(); + } + + @Test(expected = IncorrectResultSizeDataAccessException.class) + public void testSearchForObjectWithMultipleHits() { + tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=*))", new AbstractContextMapper() { + @Override + protected Object doMapFromContext(DirContextOperations ctx) { + return ctx; + } + }); + } + + @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; + } + }); + } + + @Test + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_ContextMapper() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_ContextMapper_Name() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, contextMapper); + assertThat(list).hasSize(1); + } + + @Test + 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); + assertThat(list).hasSize(1); + } + + @Test + 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"), + contextMapper); + assertThat(list).hasSize(1); + } + + @Test + 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); + assertThat(list).isEmpty(); + } + + @Test + 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"), + contextMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearchForContext_LdapQuery() { + DirContextOperations result = tested.searchForContext(query() + .where("objectclass").is("person").and("sn").is("Person2")); + + assertThat(result).isNotNull(); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); + } + + @Test(expected = EmptyResultDataAccessException.class) + public void testSearchForContext_LdapQuery_SearchScopeNotFound() { + 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")); + + assertThat(result).isNotNull(); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); + } + + @Test + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_ContextMapper_Name() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearchWithInvalidSearchBaseShouldByDefaultThrowException() { + try { + tested.search(BASE_NAME + "ou=unknown", FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + contextMapper); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testSearchWithInvalidSearchBaseCanBeConfiguredToSwallowException() { + tested.setIgnoreNameNotFoundException(true); + contextMapper.setExpectedAttributes(CN_SN_ATTRS); + contextMapper.setExpectedValues(CN_SN_VALUES); + contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); + List list = tested.search(BASE_NAME + "ou=unknown", FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + contextMapper); + assertThat(list).isEmpty(); + } + + @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(); + } + }); + + assertThat(result).hasSize(3); + } + + @Test(expected = SizeLimitExceededException.class) + public void verifyThatSearchWithCountLimitWithFlagToFalseThrowsException() { + tested.setIgnoreSizeLimitExceededException(false); + 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 760fa08e..347b9059 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 @@ -1,392 +1,392 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.dao.EmptyResultDataAccessException; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.support.AbstractContextMapper; -import org.springframework.ldap.query.SearchScope; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.ldap.test.AttributeCheckAttributesMapper; -import org.springframework.ldap.test.AttributeCheckContextMapper; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.Name; -import javax.naming.directory.SearchControls; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -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. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateNamespaceTestContext.xml"}) -@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) -public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapTemplate tested; - - private AttributeCheckAttributesMapper attributesMapper; - - private AttributeCheckContextMapper contextMapper; - - private static final String[] ALL_ATTRIBUTES = { "cn", "sn", "description", "telephoneNumber" }; - - private static final String[] CN_SN_ATTRS = { "cn", "sn" }; - - private static final String[] ABSENT_ATTRIBUTES = { "description", "telephoneNumber" }; - - private static final String[] CN_SN_VALUES = { "Some Person2", "Person2" }; - - private static final String[] ALL_VALUES = { "Some Person2", "Person2", "Sweden, Company1, Some Person2", - "+46 555-654321" }; - - private static final String BASE_STRING = ""; - - private static final String FILTER_STRING = "(&(objectclass=person)(sn=Person2))"; - - private static final Name BASE_NAME = LdapUtils.newLdapName(BASE_STRING); - - @Before - public void prepareTestedInstance() throws Exception { - attributesMapper = new AttributeCheckAttributesMapper(); - contextMapper = new AttributeCheckContextMapper(); - } - - @After - public void cleanup() throws Exception { - attributesMapper = null; - contextMapper = null; - } - - @Test - public void testSearch_AttributesMapper() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_FewerAttributes() { - 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"), - attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_SearchScope() { - 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); - assertThat(list).isEmpty(); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_SearchScope_CorrectBase() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_NoBase() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - - List list = tested.search(query() - .where("objectclass").is("person").and("sn").is("Person2"), - attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_LdapQuery_AttributesMapper_DifferentBase() { - 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); - assertThat(list).isEmpty(); - } - - @Test - public void testSearch_SearchScope_AttributesMapper() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_AttributesMapper() { - attributesMapper.setExpectedAttributes(CN_SN_ATTRS); - attributesMapper.setExpectedValues(CN_SN_VALUES); - attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, - attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_AttributesMapper_Name() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_AttributesMapper_Name() { - attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); - attributesMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_AttributesMapper_Name() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_ContextMapper() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_STRING, FILTER_STRING, contextMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearchForObject() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - DirContextAdapter result = (DirContextAdapter) tested - .searchForObject(BASE_STRING, FILTER_STRING, contextMapper); - assertThat(result).isNotNull(); - } - - @Test(expected = IncorrectResultSizeDataAccessException.class) - public void testSearchForObjectWithMultipleHits() { - tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=*))", new AbstractContextMapper() { - @Override - protected Object doMapFromContext(DirContextOperations ctx) { - return ctx; - } - }); - } - - @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; - } - }); - } - - @Test - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_ContextMapper() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_ContextMapper_Name() { - contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); - contextMapper.setExpectedValues(ALL_VALUES); - List list = tested.search(BASE_NAME, FILTER_STRING, contextMapper); - assertThat(list).hasSize(1); - } - - @Test - 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); - assertThat(list).hasSize(1); - } - - @Test - 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"), - contextMapper); - assertThat(list).hasSize(1); - } - - @Test - 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); - assertThat(list).isEmpty(); - } - - @Test - 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"), - contextMapper); - assertThat(list).hasSize(1); - } - - @Test - public void testSearchForContext_LdapQuery() { - DirContextOperations result = tested.searchForContext(query() - .where("objectclass").is("person").and("sn").is("Person2")); - - assertThat(result).isNotNull(); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); - } - - @Test(expected = EmptyResultDataAccessException.class) - public void testSearchForContext_LdapQuery_SearchScopeNotFound() { - 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")); - - assertThat(result).isNotNull(); - assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); - } - - @Test - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearch_SearchScope_LimitedAttrs_ContextMapper_Name() { - 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); - assertThat(list).hasSize(1); - } - - @Test - public void testSearchWithInvalidSearchBaseShouldByDefaultThrowException() { - try { - tested.search(BASE_NAME + "ou=unknown", FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, - contextMapper); - fail("NameNotFoundException expected"); - } - catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testSearchWithInvalidSearchBaseCanBeConfiguredToSwallowException() { - tested.setIgnoreNameNotFoundException(true); - contextMapper.setExpectedAttributes(CN_SN_ATTRS); - contextMapper.setExpectedValues(CN_SN_VALUES); - contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); - List list = tested.search(BASE_NAME + "ou=unknown", FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, - contextMapper); - assertThat(list).isEmpty(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.support.AbstractContextMapper; +import org.springframework.ldap.query.SearchScope; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.ldap.test.AttributeCheckAttributesMapper; +import org.springframework.ldap.test.AttributeCheckContextMapper; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.Name; +import javax.naming.directory.SearchControls; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +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. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateNamespaceTestContext.xml"}) +@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) +public class LdapTemplateSearchResultNamespaceConfigITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapTemplate tested; + + private AttributeCheckAttributesMapper attributesMapper; + + private AttributeCheckContextMapper contextMapper; + + private static final String[] ALL_ATTRIBUTES = { "cn", "sn", "description", "telephoneNumber" }; + + private static final String[] CN_SN_ATTRS = { "cn", "sn" }; + + private static final String[] ABSENT_ATTRIBUTES = { "description", "telephoneNumber" }; + + private static final String[] CN_SN_VALUES = { "Some Person2", "Person2" }; + + private static final String[] ALL_VALUES = { "Some Person2", "Person2", "Sweden, Company1, Some Person2", + "+46 555-654321" }; + + private static final String BASE_STRING = ""; + + private static final String FILTER_STRING = "(&(objectclass=person)(sn=Person2))"; + + private static final Name BASE_NAME = LdapUtils.newLdapName(BASE_STRING); + + @Before + public void prepareTestedInstance() throws Exception { + attributesMapper = new AttributeCheckAttributesMapper(); + contextMapper = new AttributeCheckContextMapper(); + } + + @After + public void cleanup() throws Exception { + attributesMapper = null; + contextMapper = null; + } + + @Test + public void testSearch_AttributesMapper() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_FewerAttributes() { + 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"), + attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_SearchScope() { + 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); + assertThat(list).isEmpty(); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_SearchScope_CorrectBase() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_NoBase() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + + List list = tested.search(query() + .where("objectclass").is("person").and("sn").is("Person2"), + attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_LdapQuery_AttributesMapper_DifferentBase() { + 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); + assertThat(list).isEmpty(); + } + + @Test + public void testSearch_SearchScope_AttributesMapper() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_AttributesMapper() { + attributesMapper.setExpectedAttributes(CN_SN_ATTRS); + attributesMapper.setExpectedValues(CN_SN_VALUES); + attributesMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); + List list = tested.search(BASE_STRING, FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_AttributesMapper_Name() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_AttributesMapper_Name() { + attributesMapper.setExpectedAttributes(ALL_ATTRIBUTES); + attributesMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, SearchControls.SUBTREE_SCOPE, attributesMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_AttributesMapper_Name() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_ContextMapper() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_STRING, FILTER_STRING, contextMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearchForObject() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + DirContextAdapter result = (DirContextAdapter) tested + .searchForObject(BASE_STRING, FILTER_STRING, contextMapper); + assertThat(result).isNotNull(); + } + + @Test(expected = IncorrectResultSizeDataAccessException.class) + public void testSearchForObjectWithMultipleHits() { + tested.searchForObject(BASE_STRING, "(&(objectclass=person)(sn=*))", new AbstractContextMapper() { + @Override + protected Object doMapFromContext(DirContextOperations ctx) { + return ctx; + } + }); + } + + @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; + } + }); + } + + @Test + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_ContextMapper() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_ContextMapper_Name() { + contextMapper.setExpectedAttributes(ALL_ATTRIBUTES); + contextMapper.setExpectedValues(ALL_VALUES); + List list = tested.search(BASE_NAME, FILTER_STRING, contextMapper); + assertThat(list).hasSize(1); + } + + @Test + 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); + assertThat(list).hasSize(1); + } + + @Test + 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"), + contextMapper); + assertThat(list).hasSize(1); + } + + @Test + 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); + assertThat(list).isEmpty(); + } + + @Test + 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"), + contextMapper); + assertThat(list).hasSize(1); + } + + @Test + public void testSearchForContext_LdapQuery() { + DirContextOperations result = tested.searchForContext(query() + .where("objectclass").is("person").and("sn").is("Person2")); + + assertThat(result).isNotNull(); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); + } + + @Test(expected = EmptyResultDataAccessException.class) + public void testSearchForContext_LdapQuery_SearchScopeNotFound() { + 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")); + + assertThat(result).isNotNull(); + assertThat(result.getStringAttribute("sn")).isEqualTo("Person2"); + } + + @Test + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearch_SearchScope_LimitedAttrs_ContextMapper_Name() { + 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); + assertThat(list).hasSize(1); + } + + @Test + public void testSearchWithInvalidSearchBaseShouldByDefaultThrowException() { + try { + tested.search(BASE_NAME + "ou=unknown", FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + contextMapper); + fail("NameNotFoundException expected"); + } + catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testSearchWithInvalidSearchBaseCanBeConfiguredToSwallowException() { + tested.setIgnoreNameNotFoundException(true); + contextMapper.setExpectedAttributes(CN_SN_ATTRS); + contextMapper.setExpectedValues(CN_SN_VALUES); + contextMapper.setAbsentAttributes(ABSENT_ATTRIBUTES); + List list = tested.search(BASE_NAME + "ou=unknown", FILTER_STRING, SearchControls.SUBTREE_SCOPE, CN_SN_ATTRS, + 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 c3fa4de8..49434195 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 @@ -1,78 +1,78 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.control; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.ContextMapper; -import org.springframework.ldap.core.DirContextAdapter; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest; -import org.springframework.ldap.itest.NoAdTest; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.Name; -import java.util.Arrays; -import java.util.HashSet; - -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"}) -public class SupportedControlsITest extends AbstractLdapTemplateIntegrationTest { - /** must use a context source that has no base set */ - @Autowired - private LdapTemplate tested; - - private static final String SUPPORTED_CONTROL = "supportedcontrol"; - - @Override - protected Name getRoot() { - return LdapUtils.newLdapName(base); - } - - @Test - @Category(NoAdTest.class) - public void testExpectedControlsSupported() throws Exception { - /** - * Maps the 'supportedcontrol' attribute to a string array. - */ - ContextMapper mapper = new ContextMapper() { - - public Object mapFromContext(Object ctx) { - DirContextAdapter adapter = (DirContextAdapter) ctx; - return adapter.getStringAttributes(SUPPORTED_CONTROL); - } - - }; - - String[] controls = (String[]) tested.lookup("", new String[] { SUPPORTED_CONTROL }, mapper); - System.out.println(Arrays.toString(controls)); - - 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("Subentries Control,").isTrue(); - assertThat(controlsSet.contains("2.16.840.1.113730.3.4.2")).as("Manage DSA IT LDAPv3 control,").isTrue(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.control; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.ContextMapper; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest; +import org.springframework.ldap.itest.NoAdTest; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.Name; +import java.util.Arrays; +import java.util.HashSet; + +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"}) +public class SupportedControlsITest extends AbstractLdapTemplateIntegrationTest { + /** must use a context source that has no base set */ + @Autowired + private LdapTemplate tested; + + private static final String SUPPORTED_CONTROL = "supportedcontrol"; + + @Override + protected Name getRoot() { + return LdapUtils.newLdapName(base); + } + + @Test + @Category(NoAdTest.class) + public void testExpectedControlsSupported() throws Exception { + /** + * Maps the 'supportedcontrol' attribute to a string array. + */ + ContextMapper mapper = new ContextMapper() { + + public Object mapFromContext(Object ctx) { + DirContextAdapter adapter = (DirContextAdapter) ctx; + return adapter.getStringAttributes(SUPPORTED_CONTROL); + } + + }; + + String[] controls = (String[]) tested.lookup("", new String[] { SUPPORTED_CONTROL }, mapper); + System.out.println(Arrays.toString(controls)); + + 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("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 e61c8cad..f6af448e 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 @@ -1,43 +1,43 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest.core; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; - -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"}) -public class DistinguishedNameEditorITest extends AbstractJUnit4SpringContextTests { - - @Autowired - private DummyDistinguishedNameConsumer distinguishedNameConsumer; - - @Test - public void testDistinguishedNameEditor() throws Exception { - assertThat(distinguishedNameConsumer).isNotNull(); - DistinguishedName name = distinguishedNameConsumer.getDistinguishedName(); - assertThat(name).isEqualTo(new DistinguishedName("dc=jayway, dc=se")); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest.core; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; + +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"}) +public class DistinguishedNameEditorITest extends AbstractJUnit4SpringContextTests { + + @Autowired + private DummyDistinguishedNameConsumer distinguishedNameConsumer; + + @Test + public void testDistinguishedNameEditor() throws Exception { + assertThat(distinguishedNameConsumer).isNotNull(); + 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 f2f1e6c3..1447e9f5 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 @@ -1,78 +1,78 @@ -/* - * Copyright 2005-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.core; - -import org.junit.Test; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.util.StopWatch; - -/** - * Performance test for the {@link DistinguishedName} class. - * - * @author Ulrik Sandberg - */ -public class DnParsePerformanceITest { - - @Test - public void testCreateFromString() { - StopWatch stopWatch = new StopWatch("Create from String"); - stopWatch.start(); - - for (int i = 0; i < 2000; i++) { - DistinguishedName migpath = new DistinguishedName("OU=G,OU=I,OU=M"); - DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,OU=G,OU=I,OU=M"); - DistinguishedName path2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=i,OU=M, ou=foo"); - DistinguishedName path3 = new DistinguishedName("ou=G,OU=i,OU=M, ou=foo"); - DistinguishedName path4 = new DistinguishedName("ou=G,OU=i,ou=m"); - - DistinguishedName pathE1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=L,OU=M, ou=foo"); - DistinguishedName pathE2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE"); - } - - stopWatch.stop(); - System.out.println(stopWatch.prettyPrint()); - } - - @Test - public void testCreateFromDistinguishedName() { - DistinguishedName migpath = new DistinguishedName("OU=G,OU=I,OU=M"); - DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,OU=G,OU=I,OU=M"); - DistinguishedName path2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=i,OU=M, ou=foo"); - DistinguishedName path3 = new DistinguishedName("ou=G,OU=i,OU=M, ou=foo"); - DistinguishedName path4 = new DistinguishedName("ou=G,OU=i,ou=m"); - - DistinguishedName pathE1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=L,OU=M, ou=foo"); - DistinguishedName pathE2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE"); - - StopWatch stopWatch = new StopWatch("Create from DistinguishedName"); - stopWatch.start(); - - for (int i = 0; i < 2000; i++) { - migpath = new DistinguishedName(migpath); - path1 = new DistinguishedName(path1); - path2 = new DistinguishedName(path2); - path3 = new DistinguishedName(path3); - path4 = new DistinguishedName(path4); - - pathE1 = new DistinguishedName(pathE1); - pathE2 = new DistinguishedName(pathE2); - } - - stopWatch.stop(); - System.out.println(stopWatch.prettyPrint()); - } +/* + * Copyright 2005-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.core; + +import org.junit.Test; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.util.StopWatch; + +/** + * Performance test for the {@link DistinguishedName} class. + * + * @author Ulrik Sandberg + */ +public class DnParsePerformanceITest { + + @Test + public void testCreateFromString() { + StopWatch stopWatch = new StopWatch("Create from String"); + stopWatch.start(); + + for (int i = 0; i < 2000; i++) { + DistinguishedName migpath = new DistinguishedName("OU=G,OU=I,OU=M"); + DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,OU=G,OU=I,OU=M"); + DistinguishedName path2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=i,OU=M, ou=foo"); + DistinguishedName path3 = new DistinguishedName("ou=G,OU=i,OU=M, ou=foo"); + DistinguishedName path4 = new DistinguishedName("ou=G,OU=i,ou=m"); + + DistinguishedName pathE1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=L,OU=M, ou=foo"); + DistinguishedName pathE2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE"); + } + + stopWatch.stop(); + System.out.println(stopWatch.prettyPrint()); + } + + @Test + public void testCreateFromDistinguishedName() { + DistinguishedName migpath = new DistinguishedName("OU=G,OU=I,OU=M"); + DistinguishedName path1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,OU=G,OU=I,OU=M"); + DistinguishedName path2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=i,OU=M, ou=foo"); + DistinguishedName path3 = new DistinguishedName("ou=G,OU=i,OU=M, ou=foo"); + DistinguishedName path4 = new DistinguishedName("ou=G,OU=i,ou=m"); + + DistinguishedName pathE1 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE,ou=G,OU=L,OU=M, ou=foo"); + DistinguishedName pathE2 = new DistinguishedName("cn=john.doe, OU=Users,OU=SE"); + + StopWatch stopWatch = new StopWatch("Create from DistinguishedName"); + stopWatch.start(); + + for (int i = 0; i < 2000; i++) { + migpath = new DistinguishedName(migpath); + path1 = new DistinguishedName(path1); + path2 = new DistinguishedName(path2); + path3 = new DistinguishedName(path3); + path4 = new DistinguishedName(path4); + + pathE1 = new DistinguishedName(pathE1); + pathE2 = new DistinguishedName(pathE2); + } + + 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/support/BaseLdapPathBeanPostprocessorITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/core/support/BaseLdapPathBeanPostprocessorITest.java index 59838d97..f817bb9b 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 @@ -1,106 +1,106 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.core.support; - -import org.junit.Test; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.support.LdapUtils; - -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}. - * - * @author Mattias Hellborg Arthursson - */ -public class BaseLdapPathBeanPostprocessorITest { - - @Test - public void testPostProcessBeforeInitialization() throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( - "/conf/baseLdapPathPostProcessorTestContext.xml"); - DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class); - - DistinguishedName base = tested.getBase(); - assertThat(base).isNotNull(); - assertThat(base).isEqualTo(new DistinguishedName("dc=261consulting,dc=com")); - - DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class); - assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=261consulting,dc=com")); - } - - @Test - public void testPostProcessBeforeInitializationMultipleContextSources() throws Exception { - try { - new ClassPathXmlApplicationContext("/conf/baseLdapPathPostProcessorMultiContextSourceTestContext.xml"); - fail("BeanCreationException expected"); - } - catch (BeanCreationException expected) { - Throwable cause = expected.getCause(); - assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue(); - } - } - - @Test - public void testPostProcessBeforeInitializationMultipleContextSourcesOneSpecified() throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( - "/conf/baseLdapPathPostProcessorMultiContextSourceOneSpecTestContext.xml"); - DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware"); - - DistinguishedName base = tested.getBase(); - assertThat(base).isNotNull(); - assertThat(base).isEqualTo(new DistinguishedName("cn=john doe,dc=261consulting,dc=com")); - } - - @Test - public void testPostProcessBeforeInitializationNoContextSource() throws Exception { - try { - new ClassPathXmlApplicationContext("/conf/baseLdapPathPostProcessorNoContextSourceTestContext.xml"); - fail("BeanCreationException expected"); - } - catch (BeanCreationException expected) { - Throwable cause = expected.getCause(); - assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue(); - } - } - - @Test - public void testPostProcessBeforeInitializationBaseSetInProperty() throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( - "/conf/baseLdapPathPostProcessorPropertyOverrideTestContext.xml"); - DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware"); - - DistinguishedName base = tested.getBase(); - assertThat(base).isNotNull(); - assertThat(base).isEqualTo(new DistinguishedName("cn=john doe")); - } - - @Test - public void testPostProcessBeforeInitializationTransactionProxy() throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( - "/conf/baseLdapPathPostProcessorTransactionTestContext.xml"); - DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware"); - - DistinguishedName base = tested.getBase(); - assertThat(base).isNotNull(); - assertThat(base).isEqualTo(new DistinguishedName("dc=261consulting,dc=com")); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.core.support; + +import org.junit.Test; +import org.springframework.beans.factory.BeanCreationException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.support.LdapUtils; + +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}. + * + * @author Mattias Hellborg Arthursson + */ +public class BaseLdapPathBeanPostprocessorITest { + + @Test + public void testPostProcessBeforeInitialization() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/conf/baseLdapPathPostProcessorTestContext.xml"); + DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class); + + DistinguishedName base = tested.getBase(); + assertThat(base).isNotNull(); + assertThat(base).isEqualTo(new DistinguishedName("dc=261consulting,dc=com")); + + DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class); + assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=261consulting,dc=com")); + } + + @Test + public void testPostProcessBeforeInitializationMultipleContextSources() throws Exception { + try { + new ClassPathXmlApplicationContext("/conf/baseLdapPathPostProcessorMultiContextSourceTestContext.xml"); + fail("BeanCreationException expected"); + } + catch (BeanCreationException expected) { + Throwable cause = expected.getCause(); + assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue(); + } + } + + @Test + public void testPostProcessBeforeInitializationMultipleContextSourcesOneSpecified() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/conf/baseLdapPathPostProcessorMultiContextSourceOneSpecTestContext.xml"); + DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware"); + + DistinguishedName base = tested.getBase(); + assertThat(base).isNotNull(); + assertThat(base).isEqualTo(new DistinguishedName("cn=john doe,dc=261consulting,dc=com")); + } + + @Test + public void testPostProcessBeforeInitializationNoContextSource() throws Exception { + try { + new ClassPathXmlApplicationContext("/conf/baseLdapPathPostProcessorNoContextSourceTestContext.xml"); + fail("BeanCreationException expected"); + } + catch (BeanCreationException expected) { + Throwable cause = expected.getCause(); + assertThat(cause instanceof NoSuchBeanDefinitionException).isTrue(); + } + } + + @Test + public void testPostProcessBeforeInitializationBaseSetInProperty() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/conf/baseLdapPathPostProcessorPropertyOverrideTestContext.xml"); + DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware"); + + DistinguishedName base = tested.getBase(); + assertThat(base).isNotNull(); + assertThat(base).isEqualTo(new DistinguishedName("cn=john doe")); + } + + @Test + public void testPostProcessBeforeInitializationTransactionProxy() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/conf/baseLdapPathPostProcessorTransactionTestContext.xml"); + DummyBaseLdapPathAware tested = (DummyBaseLdapPathAware) ctx.getBean("dummyBaseContextAware"); + + DistinguishedName base = tested.getBase(); + 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 eab78487..a7cb770c 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 @@ -1,62 +1,62 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.core.support; - -import org.junit.Test; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.ldap.core.DistinguishedName; -import org.springframework.ldap.support.LdapUtils; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Integration tests for {@link org.springframework.ldap.core.support.BaseLdapPathBeanPostProcessor}. - * - * @author Mattias Hellborg Arthursson - */ -public class BaseLdapPathBeanPostprocessorNamespaceConfigITest { - - @Test - public void testPostProcessBeforeInitializationWithNamespaceConfig() throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( - "/conf/baseLdapPathPostProcessorNamespaceTestContext.xml"); - DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class); - - DistinguishedName base = tested.getBase(); - assertThat(base).isNotNull(); - assertThat(base).isEqualTo(new DistinguishedName("dc=jayway,dc=se")); - - DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class); - assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=jayway,dc=se")); - } - - @Test - public void testPostProcessBeforeInitializationWithNamespaceConfigAndPooling() throws Exception { - ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( - "/conf/baseLdapPathPostProcessorPoolingNamespaceTestContext.xml"); - DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class); - - DistinguishedName base = tested.getBase(); - assertThat(base).isNotNull(); - assertThat(base).isEqualTo(new DistinguishedName("dc=jayway,dc=se")); - - DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class); - assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=jayway,dc=se")); - } - - -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.core.support; + +import org.junit.Test; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.ldap.core.DistinguishedName; +import org.springframework.ldap.support.LdapUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Integration tests for {@link org.springframework.ldap.core.support.BaseLdapPathBeanPostProcessor}. + * + * @author Mattias Hellborg Arthursson + */ +public class BaseLdapPathBeanPostprocessorNamespaceConfigITest { + + @Test + public void testPostProcessBeforeInitializationWithNamespaceConfig() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/conf/baseLdapPathPostProcessorNamespaceTestContext.xml"); + DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class); + + DistinguishedName base = tested.getBase(); + assertThat(base).isNotNull(); + assertThat(base).isEqualTo(new DistinguishedName("dc=jayway,dc=se")); + + DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class); + assertThat(otherTested.getBaseLdapPath()).isEqualTo(LdapUtils.newLdapName("dc=jayway,dc=se")); + } + + @Test + public void testPostProcessBeforeInitializationWithNamespaceConfigAndPooling() throws Exception { + ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext( + "/conf/baseLdapPathPostProcessorPoolingNamespaceTestContext.xml"); + DummyBaseLdapPathAware tested = ctx.getBean(DummyBaseLdapPathAware.class); + + DistinguishedName base = tested.getBase(); + assertThat(base).isNotNull(); + assertThat(base).isEqualTo(new DistinguishedName("dc=jayway,dc=se")); + + DummyBaseLdapNameAware otherTested = ctx.getBean(DummyBaseLdapNameAware.class); + 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 6ab7bf14..e95f7403 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 @@ -1,168 +1,168 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.core.support; - -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.dao.IncorrectResultSizeDataAccessException; -import org.springframework.ldap.core.ContextSource; -import org.springframework.ldap.core.DirContextOperations; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.core.support.AbstractContextMapper; -import org.springframework.ldap.core.support.LdapContextSource; -import org.springframework.ldap.filter.EqualsFilter; -import org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest; -import org.springframework.ldap.itest.NoAdTest; -import org.springframework.ldap.support.LdapUtils; -import org.springframework.test.context.ContextConfiguration; - -import javax.naming.Context; -import javax.naming.NamingException; -import javax.naming.directory.DirContext; -import java.util.Hashtable; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; - -/** - * Integration tests for LdapContextSource. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) -public class LdapContextSourceIntegrationTest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - @Qualifier("contextSource") - private ContextSource tested; - - @Autowired - private LdapTemplate ldapTemplate; - - @Test - public void testGetReadOnlyContext() throws NamingException { - DirContext ctx = null; - - try { - ctx = tested.getReadOnlyContext(); - assertThat(ctx).isNotNull(); - Hashtable environment = ctx.getEnvironment(); - assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse(); - assertThat(environment.containsKey(Context.SECURITY_PRINCIPAL)).isTrue(); - assertThat(environment.containsKey(Context.SECURITY_CREDENTIALS)).isTrue(); - } - finally { - // Always clean up. - if (ctx != null) { - try { - ctx.close(); - } - catch (Exception e) { - // Never mind this - } - } - } - } - - @Test - public void testGetReadWriteContext() throws NamingException { - DirContext ctx = null; - - try { - ctx = tested.getReadWriteContext(); - assertThat(ctx).isNotNull(); - // Double check to see that we are authenticated. - Hashtable environment = ctx.getEnvironment(); - assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse(); - assertThat(environment.containsKey(Context.SECURITY_PRINCIPAL)).isTrue(); - assertThat(environment.containsKey(Context.SECURITY_CREDENTIALS)).isTrue(); - } - finally { - // Always clean up. - if (ctx != null) { - try { - ctx.close(); - } - catch (Exception e) { - // Never mind this - } - } - } - } - - @Test - @Category(NoAdTest.class) - public void testGetContext() throws NamingException { - DirContext ctx = null; - try { - String expectedPrincipal = "cn=Some Person,ou=company1,ou=Sweden," + base; - String expectedCredentials = "password"; - ctx = tested.getContext(expectedPrincipal, expectedCredentials); - assertThat(ctx).isNotNull(); - // Double check to see that we are authenticated, and that we did not receive - // a connection eligible for connection pooling. - Hashtable environment = ctx.getEnvironment(); - assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse(); - assertThat(environment.get(Context.SECURITY_PRINCIPAL)).isEqualTo(expectedPrincipal); - assertThat(environment.get(Context.SECURITY_CREDENTIALS)).isEqualTo(expectedCredentials); - } - finally { - // Always clean up. - if (ctx != null) { - try { - ctx.close(); - } - catch (Exception e) { - // Never mind this - } - } - } - } - - @SuppressWarnings("unchecked") - @Test - @Category(NoAdTest.class) - public void verifyAuthenticate() { - EqualsFilter filter = new EqualsFilter("cn", "Some Person2"); - List results = ldapTemplate.search("", filter.toString(), new DnContextMapper()); - if (results.size() != 1) { - throw new IncorrectResultSizeDataAccessException(1, results.size()); - } - - DirContext ctx = null; - try { - ctx = tested.getContext(results.get(0), "password"); - assertThat(true).isTrue(); - } - catch (Exception e) { - fail("Authentication failed"); - } - finally { - LdapUtils.closeContext(ctx); - } - } - - private final static class DnContextMapper extends AbstractContextMapper { - @Override - protected String doMapFromContext(DirContextOperations ctx) { - return ctx.getNameInNamespace(); - } - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.core.support; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.dao.IncorrectResultSizeDataAccessException; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.core.support.AbstractContextMapper; +import org.springframework.ldap.core.support.LdapContextSource; +import org.springframework.ldap.filter.EqualsFilter; +import org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest; +import org.springframework.ldap.itest.NoAdTest; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.test.context.ContextConfiguration; + +import javax.naming.Context; +import javax.naming.NamingException; +import javax.naming.directory.DirContext; +import java.util.Hashtable; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.fail; + +/** + * Integration tests for LdapContextSource. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTestContext.xml"}) +public class LdapContextSourceIntegrationTest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + @Qualifier("contextSource") + private ContextSource tested; + + @Autowired + private LdapTemplate ldapTemplate; + + @Test + public void testGetReadOnlyContext() throws NamingException { + DirContext ctx = null; + + try { + ctx = tested.getReadOnlyContext(); + assertThat(ctx).isNotNull(); + Hashtable environment = ctx.getEnvironment(); + assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse(); + assertThat(environment.containsKey(Context.SECURITY_PRINCIPAL)).isTrue(); + assertThat(environment.containsKey(Context.SECURITY_CREDENTIALS)).isTrue(); + } + finally { + // Always clean up. + if (ctx != null) { + try { + ctx.close(); + } + catch (Exception e) { + // Never mind this + } + } + } + } + + @Test + public void testGetReadWriteContext() throws NamingException { + DirContext ctx = null; + + try { + ctx = tested.getReadWriteContext(); + assertThat(ctx).isNotNull(); + // Double check to see that we are authenticated. + Hashtable environment = ctx.getEnvironment(); + assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse(); + assertThat(environment.containsKey(Context.SECURITY_PRINCIPAL)).isTrue(); + assertThat(environment.containsKey(Context.SECURITY_CREDENTIALS)).isTrue(); + } + finally { + // Always clean up. + if (ctx != null) { + try { + ctx.close(); + } + catch (Exception e) { + // Never mind this + } + } + } + } + + @Test + @Category(NoAdTest.class) + public void testGetContext() throws NamingException { + DirContext ctx = null; + try { + String expectedPrincipal = "cn=Some Person,ou=company1,ou=Sweden," + base; + String expectedCredentials = "password"; + ctx = tested.getContext(expectedPrincipal, expectedCredentials); + assertThat(ctx).isNotNull(); + // Double check to see that we are authenticated, and that we did not receive + // a connection eligible for connection pooling. + Hashtable environment = ctx.getEnvironment(); + assertThat(environment.containsKey(LdapContextSource.SUN_LDAP_POOLING_FLAG)).isFalse(); + assertThat(environment.get(Context.SECURITY_PRINCIPAL)).isEqualTo(expectedPrincipal); + assertThat(environment.get(Context.SECURITY_CREDENTIALS)).isEqualTo(expectedCredentials); + } + finally { + // Always clean up. + if (ctx != null) { + try { + ctx.close(); + } + catch (Exception e) { + // Never mind this + } + } + } + } + + @SuppressWarnings("unchecked") + @Test + @Category(NoAdTest.class) + public void verifyAuthenticate() { + EqualsFilter filter = new EqualsFilter("cn", "Some Person2"); + List results = ldapTemplate.search("", filter.toString(), new DnContextMapper()); + if (results.size() != 1) { + throw new IncorrectResultSizeDataAccessException(1, results.size()); + } + + DirContext ctx = null; + try { + ctx = tested.getContext(results.get(0), "password"); + assertThat(true).isTrue(); + } + catch (Exception e) { + fail("Authentication failed"); + } + finally { + LdapUtils.closeContext(ctx); + } + } + + 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 8474ac82..3a86b48e 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 @@ -1,46 +1,46 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.ldap.itest.core.support; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.core.support.LdapContextSource; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; - -import javax.naming.NamingException; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Advanced integration tests for LdapContextSource. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapContextSourceTestContext.xml"}) -public class LdapContextSourceMultiServerIntegrationTest extends AbstractJUnit4SpringContextTests { - - @Autowired - private LdapContextSource tested; - - @Test - public void testUrls() throws NamingException { - String[] urls = tested.getUrls(); - String string = tested.assembleProviderUrlString(urls); - - assertThat(string).isEqualTo("ldap://127.0.0.1:389 ldap://127.0.0.2:389"); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.ldap.itest.core.support; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.core.support.LdapContextSource; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; + +import javax.naming.NamingException; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Advanced integration tests for LdapContextSource. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapContextSourceTestContext.xml"}) +public class LdapContextSourceMultiServerIntegrationTest extends AbstractJUnit4SpringContextTests { + + @Autowired + private LdapContextSource tested; + + @Test + public void testUrls() throws NamingException { + String[] urls = tested.getUrls(); + String string = tested.assembleProviderUrlString(urls); + + 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/integration/JiraLdap247ITest.java b/test/integration-tests/src/test/java/org/springframework/ldap/itest/integration/JiraLdap247ITest.java index f5731256..35a1e1de 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 @@ -1,47 +1,47 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.integration; - -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest; -import org.springframework.ldap.itest.LdapGroupDao; -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. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldap-247-testContext.xml"}) -public class JiraLdap247ITest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - private LdapGroupDao ldapGroupDao; - - @Test - 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. - assertThat(ldapGroupDao.getBasePath()).isNotNull(); - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.integration; + +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest; +import org.springframework.ldap.itest.LdapGroupDao; +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. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldap-247-testContext.xml"}) +public class JiraLdap247ITest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + private LdapGroupDao ldapGroupDao; + + @Test + 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. + assertThat(ldapGroupDao.getBasePath()).isNotNull(); + } +} 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 49222b17..dd8faad5 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 @@ -1,102 +1,102 @@ -/* - * Copyright 2005-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.ldap.itest.manager; - -import org.junit.Before; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; -import org.springframework.ldap.NameNotFoundException; -import org.springframework.ldap.core.LdapTemplate; -import org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest; -import org.springframework.ldap.itest.transaction.compensating.manager.DummyDao; -import org.springframework.ldap.itest.transaction.compensating.manager.DummyException; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.transaction.support.TransactionSynchronizationManager; - -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} - * that tests unbind/rebind of recursive entries. - * - * @author Mattias Hellborg Arthursson - */ -@ContextConfiguration(locations = {"/conf/ldapTemplateTransactionSubtreeTestContext.xml"}) -public class ContextSourceTransactionManagerSubtreeIntegrationTest extends AbstractLdapTemplateIntegrationTest { - - @Autowired - @Qualifier("dummyDao") - private DummyDao dummyDao; - - @Autowired - private LdapTemplate ldapTemplate; - - @Before - public void prepareTestedInstance() throws Exception { - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.clearSynchronization(); - } - } - - protected Resource getLdifFileResource() { - return new ClassPathResource("/setup_data_subtree.ldif"); - } - - @Test - public void testLdap168DeleteRecursively() { - dummyDao.deleteRecursively("ou=company1,ou=Sweden"); - - try { - ldapTemplate.lookup("ou=company1,ou=Sweden"); - fail("NameNotFoundException expected"); - } catch (NameNotFoundException expected) { - assertThat(true).isTrue(); - } - } - - @Test - public void testLdap168DeleteWithException() { - try { - dummyDao.deleteRecursivelyWithException("ou=company1,ou=Sweden"); - fail("DummyException expected"); - } catch (DummyException expected) { - assertThat(true).isTrue(); - } - - // Entry should have been restored - ldapTemplate.lookup("ou=company1,ou=Sweden"); - } - - @Test - public void testLdap244CreateRecursively() { - dummyDao.createRecursivelyAndUnbindSubnode(); - } - - @Test - public void testLdap244CreateRecursivelyWithException() { - try { - dummyDao.createRecursivelyAndUnbindSubnodeWithException(); - fail("DummyException expected"); - } catch (DummyException expected) { - assertThat(true).isTrue(); - } - } -} +/* + * Copyright 2005-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.ldap.itest.manager; + +import org.junit.Before; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; +import org.springframework.ldap.NameNotFoundException; +import org.springframework.ldap.core.LdapTemplate; +import org.springframework.ldap.itest.AbstractLdapTemplateIntegrationTest; +import org.springframework.ldap.itest.transaction.compensating.manager.DummyDao; +import org.springframework.ldap.itest.transaction.compensating.manager.DummyException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +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} + * that tests unbind/rebind of recursive entries. + * + * @author Mattias Hellborg Arthursson + */ +@ContextConfiguration(locations = {"/conf/ldapTemplateTransactionSubtreeTestContext.xml"}) +public class ContextSourceTransactionManagerSubtreeIntegrationTest extends AbstractLdapTemplateIntegrationTest { + + @Autowired + @Qualifier("dummyDao") + private DummyDao dummyDao; + + @Autowired + private LdapTemplate ldapTemplate; + + @Before + public void prepareTestedInstance() throws Exception { + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + protected Resource getLdifFileResource() { + return new ClassPathResource("/setup_data_subtree.ldif"); + } + + @Test + public void testLdap168DeleteRecursively() { + dummyDao.deleteRecursively("ou=company1,ou=Sweden"); + + try { + ldapTemplate.lookup("ou=company1,ou=Sweden"); + fail("NameNotFoundException expected"); + } catch (NameNotFoundException expected) { + assertThat(true).isTrue(); + } + } + + @Test + public void testLdap168DeleteWithException() { + try { + dummyDao.deleteRecursivelyWithException("ou=company1,ou=Sweden"); + fail("DummyException expected"); + } catch (DummyException expected) { + assertThat(true).isTrue(); + } + + // Entry should have been restored + ldapTemplate.lookup("ou=company1,ou=Sweden"); + } + + @Test + public void testLdap244CreateRecursively() { + dummyDao.createRecursivelyAndUnbindSubnode(); + } + + @Test + public void testLdap244CreateRecursivelyWithException() { + try { + dummyDao.createRecursivelyAndUnbindSubnodeWithException(); + fail("DummyException expected"); + } catch (DummyException expected) { + assertThat(true).isTrue(); + } + } +}