From 87cdf5d9dd2891eb97c08b96cc3b96e632186c52 Mon Sep 17 00:00:00 2001 From: mokhan Date: Mon, 14 Aug 2017 11:51:46 +0530 Subject: [PATCH 1/8] Spring Data Ldap --- spring-ldap/pom.xml | 246 +++++++++--------- .../baeldung/ldap/data/repository/User.java | 55 ++++ .../ldap/data/repository/UserRepository.java | 17 ++ .../ldap/data/service/LdapClient.java | 83 ++++++ .../ldap/data/service/UserService.java | 66 +++++ .../baeldung/ldap/javaconfig/AppConfig.java | 2 + .../ldap/client/LdapDataRepositoryTest.java | 68 +++++ .../baeldung/ldap/javaconfig/TestConfig.java | 2 + 8 files changed, 422 insertions(+), 117 deletions(-) create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java create mode 100644 spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java create mode 100644 spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index 16d4879f10..f000b07a09 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -1,131 +1,143 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.baeldung - spring-ldap - 0.1-SNAPSHOT - jar + com.baeldung + spring-ldap + 0.1-SNAPSHOT + jar - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - 2.3.1.RELEASE - 4.3.6.RELEASE - 1.5.5 - 0.9.15 - + + 2.3.1.RELEASE + 4.3.6.RELEASE + 1.5.5 + 0.9.15 + - - spring-ldap - + + spring-ldap + - + - - org.springframework.ldap - spring-ldap-core - ${spring-ldap.version} - - - commons-logging - commons-logging - - - + + org.springframework.ldap + spring-ldap-core + ${spring-ldap.version} + + + commons-logging + commons-logging + + + - - org.springframework - spring-context - ${spring-context.version} - + + org.springframework + spring-context + ${spring-context.version} + - - - org.springframework.ldap - spring-ldap-test - ${spring-ldap.version} - test - - - commons-logging - commons-logging - - - + + + org.springframework.ldap + spring-ldap-test + ${spring-ldap.version} + test + + + commons-logging + commons-logging + + + - - - org.apache.directory.server - apacheds-core - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-core-entry - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-shared - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-ldap - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-server-jndi - ${apacheds.version} - test - - - org.apache.directory.shared - shared-ldap - ${shared-ldap.version} - test - + + + org.apache.directory.server + apacheds-core + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-core-entry + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-shared + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-ldap + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-server-jndi + ${apacheds.version} + test + + + org.apache.directory.shared + shared-ldap + ${shared-ldap.version} + test + - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - - - **/*LiveTest.java - - - - - - - - - + + + org.springframework.data + spring-data-ldap + 1.0.6.RELEASE + + + org.springframework.data + spring-data-jpa + 1.11.6.RELEASE + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + + + \ No newline at end of file diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java new file mode 100644 index 0000000000..726fa53b02 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/User.java @@ -0,0 +1,55 @@ +package com.baeldung.ldap.data.repository; + +import javax.naming.Name; + +import org.springframework.ldap.odm.annotations.Attribute; +import org.springframework.ldap.odm.annotations.Entry; +import org.springframework.ldap.odm.annotations.Id; + +@Entry(base = "ou=users", objectClasses = { "person", "inetOrgPerson", "top" }) +public class User { + + @Id + private Name id; + + private @Attribute(name = "cn") String username; + private @Attribute(name = "sn") String password; + + public User() { + } + + public User(String username, String password) { + this.username = username; + this.password = password; + } + + public Name getId() { + return id; + } + + public void setId(Name id) { + this.id = id; + } + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String toString() { + return username; + } + +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java new file mode 100644 index 0000000000..9140616eee --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java @@ -0,0 +1,17 @@ +package com.baeldung.ldap.data.repository; + +import java.util.List; + +import org.springframework.data.ldap.repository.LdapRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends LdapRepository { + + public User findByUsername(String username); + + public User findByUsernameAndPassword(String username, String password); + + public List findByUsernameLikeIgnoreCase(String username); + +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java new file mode 100644 index 0000000000..753c5f6c34 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java @@ -0,0 +1,83 @@ +package com.baeldung.ldap.data.service; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.ldap.core.*; +import org.springframework.ldap.support.LdapNameBuilder; + +import javax.naming.Name; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.List; + +public class LdapClient { + + @Autowired + private Environment env; + + @Autowired + private ContextSource contextSource; + + @Autowired + private LdapTemplate ldapTemplate; + + public void authenticate(final String username, final String password) { + contextSource.getContext("cn=" + username + ",ou=users," + env.getRequiredProperty("ldap.partitionSuffix"), password); + } + + public List search(final String username) { + return ldapTemplate.search( + "ou=users", + "cn=" + username, + (AttributesMapper) attrs -> (String) attrs + .get("cn") + .get()); + } + + public void create(final String username, final String password) { + Name dn = LdapNameBuilder + .newInstance() + .add("ou", "users") + .add("cn", username) + .build(); + DirContextAdapter context = new DirContextAdapter(dn); + + context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValue("cn", username); + context.setAttributeValue("sn", username); + context.setAttributeValue("userPassword", digestSHA(password)); + + ldapTemplate.bind(context); + } + + public void modify(final String username, final String password) { + Name dn = LdapNameBuilder + .newInstance() + .add("ou", "users") + .add("cn", username) + .build(); + DirContextOperations context = ldapTemplate.lookupContext(dn); + + context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValue("cn", username); + context.setAttributeValue("sn", username); + context.setAttributeValue("userPassword", digestSHA(password)); + + ldapTemplate.modifyAttributes(context); + } + + private String digestSHA(final String password) { + String base64; + try { + MessageDigest digest = MessageDigest.getInstance("SHA"); + digest.update(password.getBytes()); + base64 = Base64 + .getEncoder() + .encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return "{SHA}" + base64; + } +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java new file mode 100644 index 0000000000..39d4df1cd6 --- /dev/null +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java @@ -0,0 +1,66 @@ +package com.baeldung.ldap.data.service; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.ldap.support.LdapUtils; +import org.springframework.stereotype.Service; + +import com.baeldung.ldap.data.repository.User; +import com.baeldung.ldap.data.repository.UserRepository; + +@Service +public class UserService { + + @Autowired + private UserRepository userRepository; + + public Boolean authenticate(final String username, final String password) { + User user = userRepository.findByUsernameAndPassword(username, password); + return user != null ? true : false; + } + + public List search(final String username) { + List userList = userRepository.findByUsernameLikeIgnoreCase(username); + List users = null; + if (null != userList) { + users = new ArrayList(); + for (User user : userList) { + users.add(user.getUsername()); + } + } + return users; + + } + + public void create(final String username, final String password) { + User newUser = new User(username,digestSHA(password)); + newUser.setId(LdapUtils.emptyLdapName()); + userRepository.save(newUser); + + } + + public void modify(final String username, final String password) { + User user = userRepository.findByUsername(username); + user.setPassword(password); + userRepository.save(user); + + } + + private String digestSHA(final String password) { + String base64; + try { + MessageDigest digest = MessageDigest.getInstance("SHA"); + digest.update(password.getBytes()); + base64 = Base64.getEncoder() + .encodeToString(digest.digest()); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); + } + return "{SHA}" + base64; + } +} diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java index 8572e5d1be..9330da7ab7 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java @@ -7,6 +7,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; +import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; @@ -16,6 +17,7 @@ import com.baeldung.ldap.client.LdapClient; @PropertySource("classpath:application.properties") @ComponentScan(basePackages = { "com.baeldung.ldap.*" }) @Profile("default") +@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") public class AppConfig { @Autowired diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java new file mode 100644 index 0000000000..8460fb3eb9 --- /dev/null +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java @@ -0,0 +1,68 @@ +package com.baeldung.ldap.client; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; + +import java.util.List; + +import org.hamcrest.Matchers; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.support.AnnotationConfigContextLoader; + +import com.baeldung.ldap.data.service.UserService; +import com.baeldung.ldap.javaconfig.TestConfig; + +@RunWith(SpringJUnit4ClassRunner.class) +@ActiveProfiles("testlive") +@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +public class LdapDataRepositoryTest { + + private static final String USER2 = "TEST02"; + private static final String USER3 = "TEST03"; + private static final String USER4 = "TEST04"; + + private static final String USER2_PWD = "TEST02"; + private static final String USER3_PWD = "TEST03"; + private static final String USER4_PWD = "TEST04"; + + private static final String SEARCH_STRING = "TEST*"; + + @Autowired + private UserService userService; + + @Test + public void givenLdapClient_whenCorrectCredentials_thenSuccessfulLogin() { + Boolean isValid = userService.authenticate(USER3, USER3_PWD); + assertEquals(true, isValid); + } + + @Test + public void givenLdapClient_whenIncorrectCredentials_thenFailedLogin() { + Boolean isValid = userService.authenticate(USER3, USER2_PWD); + assertEquals(false, isValid); + } + + @Test + public void givenLdapClient_whenCorrectSearchFilter_thenEntriesReturned() { + List userList = userService.search(SEARCH_STRING); + assertThat(userList, Matchers.containsInAnyOrder(USER2, USER3)); + } + + @Test + public void givenLdapClientNotExists_whenDataProvided_thenNewUserCreated() { + userService.create(USER4, USER4_PWD); + userService.authenticate(USER4, USER4_PWD); + } + + @Test + public void givenLdapClientExists_whenDataProvided_thenExistingUserModified() { + userService.modify(USER2, USER3_PWD); + userService.authenticate(USER2, USER3_PWD); + } + +} diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java index e2968e977c..0752262159 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java @@ -8,6 +8,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.core.io.ResourceLoader; +import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.TestContextSourceFactoryBean; @@ -17,6 +18,7 @@ import com.baeldung.ldap.client.LdapClient; @Configuration @PropertySource("classpath:test_application.properties") @ComponentScan(basePackages = { "com.baeldung.ldap.*" }) +@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") @Profile("testlive") public class TestConfig { @Autowired From 43357b0809a079381c9980149236dc22af4ce19a Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 14 Aug 2017 11:00:51 +0200 Subject: [PATCH 2/8] Partitioner Refactor (#2434) * Refactor Batch * Refactor Batch --- .../{spring_batch_intro => batch}/App.java | 2 +- .../SpringBatchConfig.java | 20 +++---- .../SpringConfig.java | 2 +- .../model/Transaction.java | 2 +- .../CustomMultiResourcePartitioner.java | 2 +- .../SpringbatchPartitionConfig.java | 57 +++++++++---------- .../SpringbatchPartitionerApp.java | 2 +- .../service/CustomItemProcessor.java | 4 +- .../service/RecordFieldSetMapper.java | 4 +- .../src/main/resources/spring-batch-intro.xml | 6 +- 10 files changed, 49 insertions(+), 52 deletions(-) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/App.java (96%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/SpringBatchConfig.java (85%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/SpringConfig.java (98%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/model/Transaction.java (96%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/CustomMultiResourcePartitioner.java (97%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/SpringbatchPartitionConfig.java (84%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/partitioner/SpringbatchPartitionerApp.java (95%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/service/CustomItemProcessor.java (71%) rename spring-batch/src/main/java/org/baeldung/{spring_batch_intro => batch}/service/RecordFieldSetMapper.java (91%) diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java b/spring-batch/src/main/java/org/baeldung/batch/App.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java rename to spring-batch/src/main/java/org/baeldung/batch/App.java index 2ce4dae6e6..cea4e8d486 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/App.java +++ b/spring-batch/src/main/java/org/baeldung/batch/App.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java similarity index 85% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java index 9973005c7c..7b19935cc8 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringBatchConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/SpringBatchConfig.java @@ -1,11 +1,8 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; -import java.net.MalformedURLException; -import java.text.ParseException; - -import org.baeldung.spring_batch_intro.model.Transaction; -import org.baeldung.spring_batch_intro.service.CustomItemProcessor; -import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.baeldung.batch.model.Transaction; +import org.baeldung.batch.service.CustomItemProcessor; +import org.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; @@ -26,6 +23,9 @@ import org.springframework.core.io.Resource; import org.springframework.oxm.Marshaller; import org.springframework.oxm.jaxb.Jaxb2Marshaller; +import java.net.MalformedURLException; +import java.text.ParseException; + public class SpringBatchConfig { @Autowired private JobBuilderFactory jobs; @@ -43,7 +43,7 @@ public class SpringBatchConfig { public ItemReader itemReader() throws UnexpectedInputException, ParseException { FlatFileItemReader reader = new FlatFileItemReader(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = { "username", "userid", "transactiondate", "amount" }; + String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(inputCsv); DefaultLineMapper lineMapper = new DefaultLineMapper(); @@ -71,13 +71,13 @@ public class SpringBatchConfig { @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @Bean protected Step step1(ItemReader reader, ItemProcessor processor, ItemWriter writer) { - return steps.get("step1"). chunk(10).reader(reader).processor(processor).writer(writer).build(); + return steps.get("step1").chunk(10).reader(reader).processor(processor).writer(writer).build(); } @Bean(name = "firstBatchJob") diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java similarity index 98% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java index ed7d302047..35abcb2d16 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/SpringConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/SpringConfig.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro; +package org.baeldung.batch; import java.net.MalformedURLException; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java similarity index 96% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java rename to spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java index 3b2b9610f2..0ce3a413ab 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/model/Transaction.java +++ b/spring-batch/src/main/java/org/baeldung/batch/model/Transaction.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro.model; +package org.baeldung.batch.model; import java.util.Date; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java similarity index 97% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java index 4cae69efbd..667e013c35 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/CustomMultiResourcePartitioner.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/CustomMultiResourcePartitioner.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; import java.util.HashMap; import java.util.Map; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java similarity index 84% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java index fe8339a8b4..ad3aee4a2e 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionConfig.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionConfig.java @@ -1,13 +1,7 @@ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; -import java.io.IOException; -import java.net.MalformedURLException; -import java.text.ParseException; - -import javax.sql.DataSource; - -import org.baeldung.spring_batch_intro.model.Transaction; -import org.baeldung.spring_batch_intro.service.RecordFieldSetMapper; +import org.baeldung.batch.model.Transaction; +import org.baeldung.batch.service.RecordFieldSetMapper; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; @@ -33,7 +27,6 @@ import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.task.TaskExecutor; -import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.oxm.Marshaller; @@ -41,6 +34,11 @@ import org.springframework.oxm.jaxb.Jaxb2Marshaller; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; +import javax.sql.DataSource; +import java.io.IOException; +import java.net.MalformedURLException; +import java.text.ParseException; + @Configuration @EnableBatchProcessing public class SpringbatchPartitionConfig { @@ -57,26 +55,26 @@ public class SpringbatchPartitionConfig { @Bean(name = "partitionerJob") public Job partitionerJob() throws UnexpectedInputException, MalformedURLException, ParseException { return jobs.get("partitionerJob") - .start(partitionStep()) - .build(); + .start(partitionStep()) + .build(); } @Bean public Step partitionStep() throws UnexpectedInputException, MalformedURLException, ParseException { return steps.get("partitionStep") - .partitioner("slaveStep", partitioner()) - .step(slaveStep()) - .taskExecutor(taskExecutor()) - .build(); + .partitioner("slaveStep", partitioner()) + .step(slaveStep()) + .taskExecutor(taskExecutor()) + .build(); } @Bean public Step slaveStep() throws UnexpectedInputException, MalformedURLException, ParseException { return steps.get("slaveStep") - . chunk(1) - .reader(itemReader(null)) - .writer(itemWriter(marshaller(), null)) - .build(); + .chunk(1) + .reader(itemReader(null)) + .writer(itemWriter(marshaller(), null)) + .build(); } @Bean @@ -95,12 +93,12 @@ public class SpringbatchPartitionConfig { @Bean @StepScope public FlatFileItemReader itemReader(@Value("#{stepExecutionContext[fileName]}") String filename) throws UnexpectedInputException, ParseException { - FlatFileItemReader reader = new FlatFileItemReader(); + FlatFileItemReader reader = new FlatFileItemReader<>(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); - String[] tokens = { "username", "userid", "transactiondate", "amount" }; + String[] tokens = {"username", "userid", "transactiondate", "amount"}; tokenizer.setNames(tokens); reader.setResource(new ClassPathResource("input/partitioner/" + filename)); - DefaultLineMapper lineMapper = new DefaultLineMapper(); + DefaultLineMapper lineMapper = new DefaultLineMapper<>(); lineMapper.setLineTokenizer(tokenizer); lineMapper.setFieldSetMapper(new RecordFieldSetMapper()); reader.setLinesToSkip(1); @@ -121,7 +119,7 @@ public class SpringbatchPartitionConfig { @Bean public Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); - marshaller.setClassesToBeBound(new Class[] { Transaction.class }); + marshaller.setClassesToBeBound(Transaction.class); return marshaller; } @@ -142,16 +140,15 @@ public class SpringbatchPartitionConfig { // JobRepositoryFactoryBean's methods Throws Generic Exception, // it would have been better to have a specific one factory.afterPropertiesSet(); - return (JobRepository) factory.getObject(); + return factory.getObject(); } private DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); - EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.HSQL) - .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") - .addScript("classpath:org/springframework/batch/core/schema-h2.sql") - .build(); - return db; + return builder.setType(EmbeddedDatabaseType.HSQL) + .addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql") + .addScript("classpath:org/springframework/batch/core/schema-h2.sql") + .build(); } private PlatformTransactionManager getTransactionManager() { diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java similarity index 95% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java rename to spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java index 1d6d922969..e56afc591c 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/partitioner/SpringbatchPartitionerApp.java +++ b/spring-batch/src/main/java/org/baeldung/batch/partitioner/SpringbatchPartitionerApp.java @@ -1,4 +1,4 @@ -package org.baeldung.spring_batch_intro.partitioner; +package org.baeldung.batch.partitioner; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java b/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java similarity index 71% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java rename to spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java index ebee1d2802..8ca7892fec 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/CustomItemProcessor.java +++ b/spring-batch/src/main/java/org/baeldung/batch/service/CustomItemProcessor.java @@ -1,6 +1,6 @@ -package org.baeldung.spring_batch_intro.service; +package org.baeldung.batch.service; -import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.batch.model.Transaction; import org.springframework.batch.item.ItemProcessor; public class CustomItemProcessor implements ItemProcessor { diff --git a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java similarity index 91% rename from spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java rename to spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java index 94f9e7d94e..fa6f0870aa 100644 --- a/spring-batch/src/main/java/org/baeldung/spring_batch_intro/service/RecordFieldSetMapper.java +++ b/spring-batch/src/main/java/org/baeldung/batch/service/RecordFieldSetMapper.java @@ -1,9 +1,9 @@ -package org.baeldung.spring_batch_intro.service; +package org.baeldung.batch.service; import java.text.ParseException; import java.text.SimpleDateFormat; -import org.baeldung.spring_batch_intro.model.Transaction; +import org.baeldung.batch.model.Transaction; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.validation.BindException; diff --git a/spring-batch/src/main/resources/spring-batch-intro.xml b/spring-batch/src/main/resources/spring-batch-intro.xml index 93606d232f..0f76dd50ff 100644 --- a/spring-batch/src/main/resources/spring-batch-intro.xml +++ b/spring-batch/src/main/resources/spring-batch-intro.xml @@ -22,14 +22,14 @@ + class="org.baeldung.batch.service.RecordFieldSetMapper" /> - + @@ -40,7 +40,7 @@ - org.baeldung.spring_batch_intro.model.Transaction + org.baeldung.batch.model.Transaction From 8d9a7b0ecff611b751f103537b20b78ae1c5464d Mon Sep 17 00:00:00 2001 From: Roman Seleznov Date: Mon, 14 Aug 2017 14:12:29 +0100 Subject: [PATCH 3/8] BAEL-764 Automatic Property Expansion with Spring Boot (#2435) * Create pom.xml Initial import * First submit * Second submit * Different Types of Bean Injection in Spring * Different Types of Bean Injection in Spring * Added spring-core-di into the main build * Revert "Create pom.xml" This reverts commit 1bdc5443125df19575605f41ab28c9e8b6c69a32. * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot * BAEL-764 Automatic Property Expansion with Spring Boot Make executable jars for property-exp-default project and use mvn exec:java to run property-exp-default project * BAEL-764 Automatic Property Expansion with Spring Boot Rename modules as per code reivew * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review * BAEL-764 Automatic Property Expansion with Spring Boot Updated README.md as per code review --- spring-boot-property-exp/README.md | 18 +++++++++++++++++- .../property-exp-custom-config/pom.xml | 2 +- .../property-exp-default-config/pom.xml | 2 +- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/spring-boot-property-exp/README.md b/spring-boot-property-exp/README.md index 5b2552ade7..8a598e7a05 100644 --- a/spring-boot-property-exp/README.md +++ b/spring-boot-property-exp/README.md @@ -1,2 +1,18 @@ ## The Module Holds Sources for the Following Articles - - [Automatic Property Expansion with Spring Boot] (http://www.baeldung.com/property-expansion-spring-boot) \ No newline at end of file + - [Automatic Property Expansion with Spring Boot](http://www.baeldung.com/property-expansion-spring-boot) + +### Module property-exp-default-config + This module contains both a standard Maven Spring Boot build and the Gradle build which is Maven compatible. + + In order to execute the Maven example, run the following command: + + `mvn spring-boot:run` + + To execute the Gradle example: + +`gradle bootRun` + + ### Module property-exp-custom-config + This project is not using the standard Spring Boot parent and is configured manually. Run the following command: + + `mvn exec:java` \ No newline at end of file diff --git a/spring-boot-property-exp/property-exp-custom-config/pom.xml b/spring-boot-property-exp/property-exp-custom-config/pom.xml index cfce323eab..7822b31cf2 100644 --- a/spring-boot-property-exp/property-exp-custom-config/pom.xml +++ b/spring-boot-property-exp/property-exp-custom-config/pom.xml @@ -9,7 +9,7 @@ 4.0.0 com.baeldung - property-exp-custom + property-exp-custom-config 0.0.1-SNAPSHOT jar diff --git a/spring-boot-property-exp/property-exp-default-config/pom.xml b/spring-boot-property-exp/property-exp-default-config/pom.xml index 2544800e6a..0625916d32 100644 --- a/spring-boot-property-exp/property-exp-default-config/pom.xml +++ b/spring-boot-property-exp/property-exp-default-config/pom.xml @@ -11,7 +11,7 @@ com.baeldung - property-exp-default + property-exp-default-config 0.0.1-SNAPSHOT jar From 99eee4df2cd1a0dbf9e4011864bf16f1d90b35be Mon Sep 17 00:00:00 2001 From: baljeet20 Date: Mon, 14 Aug 2017 22:38:01 +0530 Subject: [PATCH 4/8] BAEL-1077 Guide to volatile keyword (#2433) * review changes * BAEL-1024 Removed the proxy reference * BAEL-1024 Renamed methods * BAEL-1077 Guide to volatile keyword --- .../volatilekeyword/SharedObject.java | 13 +++ .../SharedObjectManualTest.java | 99 +++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java create mode 100644 core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java diff --git a/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java new file mode 100644 index 0000000000..3f24df5059 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/concurrent/volatilekeyword/SharedObject.java @@ -0,0 +1,13 @@ +package com.baeldung.concurrent.volatilekeyword; + + +public class SharedObject { + private volatile int count=0; + + public void increamentCount(){ + count++; + } + public int getCount(){ + return count; + } +} diff --git a/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java new file mode 100644 index 0000000000..260a7c060b --- /dev/null +++ b/core-java/src/test/java/com/baeldung/concurrent/volatilekeyword/SharedObjectManualTest.java @@ -0,0 +1,99 @@ +package com.baeldung.concurrent.volatilekeyword; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static junit.framework.Assert.assertEquals; + +public class SharedObjectManualTest { + + SharedObject sharedObject; + int valueReadByThread2; + int valueReadByThread3; + + @Before + public void setUp(){ + sharedObject = new SharedObject(); + } + + @Test + public void whenOneThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { + Thread writer = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writer.start(); + + + Thread readerOne = new Thread(){ + public void run(){ + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + valueReadByThread2= sharedObject.getCount(); + } + }; + readerOne.start(); + + Thread readerTwo = new Thread(){ + public void run(){ + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + valueReadByThread3=sharedObject.getCount(); + } + }; + readerTwo.start(); + + assertEquals(1,valueReadByThread2); + assertEquals(1,valueReadByThread3); + + } + + @Test + public void whenTwoThreadWrites_thenVolatileReadsFromMainMemory() throws InterruptedException { + Thread writerOne = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writerOne.start(); + Thread.sleep(100); + + Thread writerTwo = new Thread(){ + public void run(){ + sharedObject.increamentCount(); + } + }; + writerTwo.start(); + Thread.sleep(100); + + Thread readerOne = new Thread(){ + public void run(){ + valueReadByThread2= sharedObject.getCount(); + } + }; + readerOne.start(); + + Thread readerTwo = new Thread(){ + public void run(){ + valueReadByThread3=sharedObject.getCount(); + } + }; + readerTwo.start(); + + assertEquals(2,valueReadByThread2); + assertEquals(2,valueReadByThread3); + + } + @After + public void cleanup(){ + sharedObject = null; + } +} From 58469d79bf11cb7349e220588d7472a499108acd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ra=C3=BAl=20Ju=C3=A1rez?= Date: Mon, 14 Aug 2017 12:45:30 -0500 Subject: [PATCH 5/8] BAEL-864 Difference between URL and URI (#2438) --- .../uriurl/URIvsURLUnitTest.java | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java diff --git a/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java new file mode 100644 index 0000000000..ed36951f73 --- /dev/null +++ b/core-java/src/test/java/com/baeldung/javanetworking/uriurl/URIvsURLUnitTest.java @@ -0,0 +1,78 @@ +package com.baeldung.javanetworking.uriurl; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import org.apache.commons.io.IOUtils; +import static org.junit.Assert.*; +import org.junit.Test; + +public class URIvsURLUnitTest { + + @Test + public void whenCreatingURIs_thenSameInfo() throws URISyntaxException { + URI firstURI = new URI("somescheme://theuser:thepassword@someauthority:80/some/path?thequery#somefragment"); + URI secondURI = new URI("somescheme", "theuser:thepassword", "someuthority", 80, "/some/path", "thequery", "somefragment"); + + assertEquals(firstURI.getScheme(), secondURI.getScheme()); + assertEquals(firstURI.getPath(), secondURI.getPath()); + } + + @Test + public void whenCreatingURLs_thenSameInfo() throws MalformedURLException { + URL firstURL = new URL("http://theuser:thepassword@somehost:80/path/to/file?thequery#somefragment"); + URL secondURL = new URL("http", "somehost", 80, "/path/to/file"); + + assertEquals(firstURL.getHost(), secondURL.getHost()); + assertEquals(firstURL.getPath(), secondURL.getPath()); + } + + @Test + public void whenCreatingURI_thenCorrect() { + URI uri = URI.create("urn:isbn:1234567890"); + + assertNotNull(uri); + } + + @Test(expected = MalformedURLException.class) + public void whenCreatingURLs_thenException() throws MalformedURLException { + URL theURL = new URL("otherprotocol://somehost/path/to/file"); + + assertNotNull(theURL); + } + + @Test + public void givenObjects_whenConverting_thenCorrect() throws MalformedURLException, URISyntaxException { + String aURIString = "http://somehost:80/path?thequery"; + URI uri = new URI(aURIString); + URL url = new URL(aURIString); + + URL toURL = uri.toURL(); + URI toURI = url.toURI(); + + assertNotNull(url); + assertNotNull(uri); + assertEquals(toURL.toString(), toURI.toString()); + } + + @Test(expected = MalformedURLException.class) + public void givenURI_whenConvertingToURL_thenException() throws MalformedURLException, URISyntaxException { + URI uri = new URI("somescheme://someauthority/path?thequery"); + + URL url = uri.toURL(); + + assertNotNull(url); + } + + @Test + public void givenURL_whenGettingContents_thenCorrect() throws MalformedURLException, IOException { + URL url = new URL("http://courses.baeldung.com"); + + String contents = IOUtils.toString(url.openStream()); + + assertTrue(contents.contains("")); + } + +} From 0de69c346c87c2f628cfe93dc6688312cb8db580 Mon Sep 17 00:00:00 2001 From: lor6 Date: Mon, 14 Aug 2017 20:46:16 +0300 Subject: [PATCH 6/8] add dependency management (#2382) --- spring-boot-bootstrap/pom.xml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/spring-boot-bootstrap/pom.xml b/spring-boot-bootstrap/pom.xml index 697a139eb5..9da37a3261 100644 --- a/spring-boot-bootstrap/pom.xml +++ b/spring-boot-bootstrap/pom.xml @@ -17,6 +17,25 @@ 1.5.3.RELEASE + + UTF-8 From dc9ecc143df547e16725fbad678fe75211f8f423 Mon Sep 17 00:00:00 2001 From: Nikhil Khatwani Date: Mon, 14 Aug 2017 23:59:36 +0530 Subject: [PATCH 7/8] Added test cases for BAEL-897 (#2436) --- .../test/JacksonDeserializationUnitTest.java | 40 ++++++++++++++++++- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java index 45d957b90b..035ff8ca9c 100644 --- a/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java +++ b/jackson/src/test/java/com/baeldung/jackson/test/JacksonDeserializationUnitTest.java @@ -1,19 +1,23 @@ package com.baeldung.jackson.test; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import java.io.IOException; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import org.junit.Test; import com.baeldung.jackson.deserialization.ItemDeserializer; import com.baeldung.jackson.dtos.Item; import com.baeldung.jackson.dtos.ItemWithSerializer; import com.baeldung.jackson.dtos.MyDto; import com.baeldung.jackson.dtos.ignore.MyDtoIgnoreUnknown; -import org.junit.Test; - import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonParser; @@ -21,6 +25,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.fasterxml.jackson.databind.module.SimpleModule; @@ -165,4 +170,35 @@ public class JacksonDeserializationUnitTest { assertThat(readValue, notNullValue()); } + @Test + public void whenDeserialisingZonedDateTimeWithDefaults_thenTimeZoneIsNotPreserved() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + // construct a new instance of ZonedDateTime + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + String converted = objectMapper.writeValueAsString(now); + // restore an instance of ZonedDateTime from String + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(not(restored))); + } + + @Test + public void whenDeserialisingZonedDateTimeWithFeaturesDisabled_thenTimeZoneIsPreserved() throws IOException { + ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.findAndRegisterModules(); + objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE); + // construct a new instance of ZonedDateTime + ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Berlin")); + String converted = objectMapper.writeValueAsString(now); + // restore an instance of ZonedDateTime from String + ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class); + System.out.println("serialized: " + now); + System.out.println("restored: " + restored); + assertThat(now, is(restored)); + } + } From bcc122b7247753923d34e593665c84af3aa8c3a4 Mon Sep 17 00:00:00 2001 From: Grzegorz Piwowarek Date: Mon, 14 Aug 2017 21:46:04 +0200 Subject: [PATCH 8/8] Refactor Batch (#2439) --- spring-ldap/pom.xml | 256 +++++++++--------- .../ldap/data/repository/UserRepository.java | 6 +- .../ldap/data/service/LdapClient.java | 14 +- .../ldap/data/service/UserService.java | 31 +-- .../baeldung/ldap/javaconfig/AppConfig.java | 7 +- spring-ldap/src/main/resources/logback.xml | 8 +- .../ldap/client/LdapClientLiveTest.java | 7 +- .../ldap/client/LdapDataRepositoryTest.java | 15 +- .../baeldung/ldap/javaconfig/TestConfig.java | 7 +- 9 files changed, 174 insertions(+), 177 deletions(-) diff --git a/spring-ldap/pom.xml b/spring-ldap/pom.xml index f000b07a09..05baf8c66d 100644 --- a/spring-ldap/pom.xml +++ b/spring-ldap/pom.xml @@ -1,143 +1,143 @@ - 4.0.0 + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - com.baeldung - spring-ldap - 0.1-SNAPSHOT - jar + com.baeldung + spring-ldap + 0.1-SNAPSHOT + jar - - com.baeldung - parent-modules - 1.0.0-SNAPSHOT - + + com.baeldung + parent-modules + 1.0.0-SNAPSHOT + - - 2.3.1.RELEASE - 4.3.6.RELEASE - 1.5.5 - 0.9.15 - + + 2.3.1.RELEASE + 4.3.6.RELEASE + 1.5.5 + 0.9.15 + - - spring-ldap - + + spring-ldap + - + - - org.springframework.ldap - spring-ldap-core - ${spring-ldap.version} - - - commons-logging - commons-logging - - - + + org.springframework.ldap + spring-ldap-core + ${spring-ldap.version} + + + commons-logging + commons-logging + + + - - org.springframework - spring-context - ${spring-context.version} - + + org.springframework + spring-context + ${spring-context.version} + - - - org.springframework.ldap - spring-ldap-test - ${spring-ldap.version} - test - - - commons-logging - commons-logging - - - + + + org.springframework.ldap + spring-ldap-test + ${spring-ldap.version} + test + + + commons-logging + commons-logging + + + - - - org.apache.directory.server - apacheds-core - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-core-entry - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-shared - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-protocol-ldap - ${apacheds.version} - test - - - org.apache.directory.server - apacheds-server-jndi - ${apacheds.version} - test - - - org.apache.directory.shared - shared-ldap - ${shared-ldap.version} - test - + + + org.apache.directory.server + apacheds-core + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-core-entry + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-shared + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-protocol-ldap + ${apacheds.version} + test + + + org.apache.directory.server + apacheds-server-jndi + ${apacheds.version} + test + + + org.apache.directory.shared + shared-ldap + ${shared-ldap.version} + test + - - - org.springframework.data - spring-data-ldap - 1.0.6.RELEASE - - - org.springframework.data - spring-data-jpa - 1.11.6.RELEASE - - + + + org.springframework.data + spring-data-ldap + 1.0.6.RELEASE + + + org.springframework.data + spring-data-jpa + 1.11.6.RELEASE + + - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration-test - - test - - - - **/*IntegrationTest.java - - - **/*LiveTest.java - - - - - - - - - + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration-test + + test + + + + **/*IntegrationTest.java + + + **/*LiveTest.java + + + + + + + + + \ No newline at end of file diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java index 9140616eee..12dc0f7f14 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/repository/UserRepository.java @@ -8,10 +8,10 @@ import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends LdapRepository { - public User findByUsername(String username); + User findByUsername(String username); - public User findByUsernameAndPassword(String username, String password); + User findByUsernameAndPassword(String username, String password); - public List findByUsernameLikeIgnoreCase(String username); + List findByUsernameLikeIgnoreCase(String username); } diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java index 753c5f6c34..1b04edb35b 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/LdapClient.java @@ -2,7 +2,11 @@ package com.baeldung.ldap.data.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; -import org.springframework.ldap.core.*; +import org.springframework.ldap.core.AttributesMapper; +import org.springframework.ldap.core.ContextSource; +import org.springframework.ldap.core.DirContextAdapter; +import org.springframework.ldap.core.DirContextOperations; +import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.support.LdapNameBuilder; import javax.naming.Name; @@ -31,8 +35,8 @@ public class LdapClient { "ou=users", "cn=" + username, (AttributesMapper) attrs -> (String) attrs - .get("cn") - .get()); + .get("cn") + .get()); } public void create(final String username, final String password) { @@ -43,7 +47,7 @@ public class LdapClient { .build(); DirContextAdapter context = new DirContextAdapter(dn); - context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); context.setAttributeValue("cn", username); context.setAttributeValue("sn", username); context.setAttributeValue("userPassword", digestSHA(password)); @@ -59,7 +63,7 @@ public class LdapClient { .build(); DirContextOperations context = ldapTemplate.lookupContext(dn); - context.setAttributeValues("objectclass", new String[] { "top", "person", "organizationalPerson", "inetOrgPerson" }); + context.setAttributeValues("objectclass", new String[]{"top", "person", "organizationalPerson", "inetOrgPerson"}); context.setAttributeValue("cn", username); context.setAttributeValue("sn", username); context.setAttributeValue("userPassword", digestSHA(password)); diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java index 39d4df1cd6..54954e3c9d 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/data/service/UserService.java @@ -1,17 +1,17 @@ package com.baeldung.ldap.data.service; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; - +import com.baeldung.ldap.data.repository.User; +import com.baeldung.ldap.data.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ldap.support.LdapUtils; import org.springframework.stereotype.Service; -import com.baeldung.ldap.data.repository.User; -import com.baeldung.ldap.data.repository.UserRepository; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; @Service public class UserService { @@ -21,20 +21,18 @@ public class UserService { public Boolean authenticate(final String username, final String password) { User user = userRepository.findByUsernameAndPassword(username, password); - return user != null ? true : false; + return user != null; } public List search(final String username) { List userList = userRepository.findByUsernameLikeIgnoreCase(username); - List users = null; - if (null != userList) { - users = new ArrayList(); - for (User user : userList) { - users.add(user.getUsername()); - } + if (userList == null) { + return Collections.emptyList(); } - return users; + return userList.stream() + .map(User::getUsername) + .collect(Collectors.toList()); } public void create(final String username, final String password) { @@ -48,7 +46,6 @@ public class UserService { User user = userRepository.findByUsername(username); user.setPassword(password); userRepository.save(user); - } private String digestSHA(final String password) { diff --git a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java index 9330da7ab7..fb3000b2bd 100644 --- a/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java +++ b/spring-ldap/src/main/java/com/baeldung/ldap/javaconfig/AppConfig.java @@ -1,5 +1,6 @@ package com.baeldung.ldap.javaconfig; +import com.baeldung.ldap.client.LdapClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -11,13 +12,11 @@ import org.springframework.data.ldap.repository.config.EnableLdapRepositories; import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; -import com.baeldung.ldap.client.LdapClient; - @Configuration @PropertySource("classpath:application.properties") -@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) +@ComponentScan(basePackages = {"com.baeldung.ldap.*"}) @Profile("default") -@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") +@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**") public class AppConfig { @Autowired diff --git a/spring-ldap/src/main/resources/logback.xml b/spring-ldap/src/main/resources/logback.xml index ec0dc2469a..32b78577ee 100644 --- a/spring-ldap/src/main/resources/logback.xml +++ b/spring-ldap/src/main/resources/logback.xml @@ -7,13 +7,13 @@ - - + + - + - + \ No newline at end of file diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java index b65588dc38..f5b74d64c6 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapClientLiveTest.java @@ -1,7 +1,6 @@ package com.baeldung.ldap.client; -import java.util.List; - +import com.baeldung.ldap.javaconfig.TestConfig; import org.hamcrest.Matchers; import org.junit.Assert; import org.junit.Test; @@ -13,11 +12,11 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.ldap.javaconfig.TestConfig; +import java.util.List; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("testlive") -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) public class LdapClientLiveTest { private static final String USER2 = "TEST02"; diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java index 8460fb3eb9..9f38af9263 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/client/LdapDataRepositoryTest.java @@ -1,10 +1,7 @@ package com.baeldung.ldap.client; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; - -import java.util.List; - +import com.baeldung.ldap.data.service.UserService; +import com.baeldung.ldap.javaconfig.TestConfig; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; @@ -14,12 +11,14 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.AnnotationConfigContextLoader; -import com.baeldung.ldap.data.service.UserService; -import com.baeldung.ldap.javaconfig.TestConfig; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("testlive") -@ContextConfiguration(classes = { TestConfig.class }, loader = AnnotationConfigContextLoader.class) +@ContextConfiguration(classes = {TestConfig.class}, loader = AnnotationConfigContextLoader.class) public class LdapDataRepositoryTest { private static final String USER2 = "TEST02"; diff --git a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java index 0752262159..c6293982da 100644 --- a/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java +++ b/spring-ldap/src/test/java/com/baeldung/ldap/javaconfig/TestConfig.java @@ -1,5 +1,6 @@ package com.baeldung.ldap.javaconfig; +import com.baeldung.ldap.client.LdapClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; @@ -13,12 +14,10 @@ import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import org.springframework.ldap.test.TestContextSourceFactoryBean; -import com.baeldung.ldap.client.LdapClient; - @Configuration @PropertySource("classpath:test_application.properties") -@ComponentScan(basePackages = { "com.baeldung.ldap.*" }) -@EnableLdapRepositories(basePackages="com.baeldung.ldap.**") +@ComponentScan(basePackages = {"com.baeldung.ldap.*"}) +@EnableLdapRepositories(basePackages = "com.baeldung.ldap.**") @Profile("testlive") public class TestConfig { @Autowired