From ff8380a954c4e10abfdb477f711eb326d4c470f6 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 30 Oct 2018 09:27:49 +0800 Subject: [PATCH 01/15] add random string test --- .../com/baeldung/random/RandomStringTest.kt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt new file mode 100644 index 0000000000..b8d0bd49cd --- /dev/null +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt @@ -0,0 +1,18 @@ + +import org.junit.jupiter.api.Test +import java.util.concurrent.ThreadLocalRandom +import kotlin.test.assertTrue + +class RandomNumberTest { + + @Test + fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() { + val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + var test = Random().ints(outputStrLength, 0, source.length) + .asSequence() + .map(source::get) + .joinToString("") + print("message") + } + +} \ No newline at end of file From 3221968f9e4e3fb58f5039c80c68b0092bcbc77a Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 30 Oct 2018 13:40:59 +0800 Subject: [PATCH 02/15] BAEL-1913 kotline random string --- core-kotlin/pom.xml | 6 +++ .../com/baeldung/random/RandomStringTest.kt | 50 +++++++++++++++---- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml index 5cdb5f700e..2b559b19e0 100644 --- a/core-kotlin/pom.xml +++ b/core-kotlin/pom.xml @@ -18,6 +18,11 @@ commons-math3 ${commons-math3.version} + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + org.junit.platform junit-platform-runner @@ -70,6 +75,7 @@ 3.6.1 + 3.8.1 1.1.1 5.2.0 3.10.0 diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt index b8d0bd49cd..b47a6ac455 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt @@ -1,18 +1,50 @@ - +import org.apache.commons.lang3.RandomStringUtils import org.junit.jupiter.api.Test -import java.util.concurrent.ThreadLocalRandom -import kotlin.test.assertTrue +import kotlin.streams.asSequence +import kotlin.test.assertEquals -class RandomNumberTest { +const val STRING_LENGTH = 10; +const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+"; + +class RandomStringTest { @Test - fun whenRandomNumberWithJavaUtilMath_thenResultIsBetween0And1() { - val source = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - var test = Random().ints(outputStrLength, 0, source.length) + fun generateRandomString_useJava_returnString() { + val charPool = ArrayList(); + charPool.addAll('a'..'z'); + charPool.addAll('A'..'Z'); + charPool.addAll('0'..'9'); + + var randomString = java.util.Random().ints(STRING_LENGTH.toLong(), 0, charPool.size) .asSequence() - .map(source::get) + .map(charPool::get) .joinToString("") - print("message") + + assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))); + assertEquals(STRING_LENGTH, randomString.length); + } + + @Test + fun generateRandomString_useKotlin_returnString() { + val charPool = ArrayList(); + charPool.addAll('a'..'z'); + charPool.addAll('A'..'Z'); + charPool.addAll('0'..'9'); + + var randomString = (1..STRING_LENGTH).map { i -> kotlin.random.Random.nextInt(0, charPool.size) } + .map(charPool::get) + .joinToString(""); + + assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))); + assertEquals(STRING_LENGTH, randomString.length); + } + + @Test + fun generateRandomString_useApacheCommon_returnString() { + var randomString = RandomStringUtils.randomAlphanumeric(STRING_LENGTH); + + assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))); + assertEquals(STRING_LENGTH, randomString.length); } } \ No newline at end of file From a15a0809ec071dfc804fdf13c139ea7b1ec9a8c7 Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Sun, 11 Nov 2018 18:24:01 +0800 Subject: [PATCH 03/15] fix java code --- .../src/test/kotlin/com/baeldung/random/RandomStringTest.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt index b47a6ac455..0795cd2a5b 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt @@ -1,5 +1,6 @@ import org.apache.commons.lang3.RandomStringUtils import org.junit.jupiter.api.Test +import java.util.concurrent.ThreadLocalRandom import kotlin.streams.asSequence import kotlin.test.assertEquals @@ -15,7 +16,8 @@ class RandomStringTest { charPool.addAll('A'..'Z'); charPool.addAll('0'..'9'); - var randomString = java.util.Random().ints(STRING_LENGTH.toLong(), 0, charPool.size) + var randomString = ThreadLocalRandom.current() + .ints(STRING_LENGTH.toLong(), 0, charPool.size) .asSequence() .map(charPool::get) .joinToString("") From 6557cf256408722e6b7e019cb3e314151d86742d Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Tue, 13 Nov 2018 09:43:13 +0800 Subject: [PATCH 04/15] add performance test --- .../com/baeldung/random/RandomStringTest.kt | 58 ++++++++++++------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt index 0795cd2a5b..0715870403 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt @@ -1,52 +1,70 @@ import org.apache.commons.lang3.RandomStringUtils +import org.junit.Before +import org.junit.jupiter.api.BeforeAll +import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test +import java.security.SecureRandom import java.util.concurrent.ThreadLocalRandom +import kotlin.experimental.and import kotlin.streams.asSequence import kotlin.test.assertEquals -const val STRING_LENGTH = 10; -const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+"; +const val STRING_LENGTH = 10 +const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+" class RandomStringTest { - @Test - fun generateRandomString_useJava_returnString() { - val charPool = ArrayList(); + val charPool = ArrayList() + + @BeforeEach + fun charPool() { charPool.addAll('a'..'z'); charPool.addAll('A'..'Z'); charPool.addAll('0'..'9'); + } + @Test + fun givenAStringLength_whenUsingJava_thenReturnAlphanumericString() { var randomString = ThreadLocalRandom.current() .ints(STRING_LENGTH.toLong(), 0, charPool.size) .asSequence() .map(charPool::get) .joinToString("") - assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))); - assertEquals(STRING_LENGTH, randomString.length); + assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) + assertEquals(STRING_LENGTH, randomString.length) } @Test - fun generateRandomString_useKotlin_returnString() { - val charPool = ArrayList(); - charPool.addAll('a'..'z'); - charPool.addAll('A'..'Z'); - charPool.addAll('0'..'9'); - + fun givenAStringLength_whenUsingKotlin_thenReturnAlphanumericString() { var randomString = (1..STRING_LENGTH).map { i -> kotlin.random.Random.nextInt(0, charPool.size) } .map(charPool::get) - .joinToString(""); + .joinToString("") - assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))); - assertEquals(STRING_LENGTH, randomString.length); + assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) + assertEquals(STRING_LENGTH, randomString.length) } @Test - fun generateRandomString_useApacheCommon_returnString() { - var randomString = RandomStringUtils.randomAlphanumeric(STRING_LENGTH); + fun givenAStringLength_whenUsingApacheCommon_thenReturnAlphanumericString() { + var randomString = RandomStringUtils.randomAlphanumeric(STRING_LENGTH) - assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))); - assertEquals(STRING_LENGTH, randomString.length); + assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) + assertEquals(STRING_LENGTH, randomString.length) + } + + @Test + fun givenAStringLength_whenUsingRandomForBytes_thenReturnAlphanumericString() { + val random = SecureRandom() + val bytes = ByteArray(STRING_LENGTH) + random.nextBytes(bytes) + + var randomString = (0..bytes.size - 1).map { i -> + charPool.get((bytes[i] and 0xFF.toByte() and charPool.size.toByte()).toInt()) + }.joinToString("") + + assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) + assertEquals(STRING_LENGTH, randomString.length) } } \ No newline at end of file From f0f1eba7b91e9743f15fd4e7b5d53bbccd5bac41 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Fri, 16 Nov 2018 10:04:48 +0800 Subject: [PATCH 05/15] change from @before to init --- .../test/kotlin/com/baeldung/random/RandomStringTest.kt | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt index 0715870403..f44b0cd437 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt @@ -16,11 +16,10 @@ class RandomStringTest { val charPool = ArrayList() - @BeforeEach - fun charPool() { - charPool.addAll('a'..'z'); - charPool.addAll('A'..'Z'); - charPool.addAll('0'..'9'); + init { + charPool.addAll('a'..'z') + charPool.addAll('A'..'Z') + charPool.addAll('0'..'9') } @Test From e27d5f4f1f81c5f3f0e9c69175d2bc21b751350e Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Fri, 16 Nov 2018 10:05:09 +0800 Subject: [PATCH 06/15] change from @before to init --- .../src/test/kotlin/com/baeldung/random/RandomStringTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt index f44b0cd437..a2a1ac58e3 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt @@ -14,7 +14,7 @@ const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+" class RandomStringTest { - val charPool = ArrayList() + private val charPool = ArrayList() init { charPool.addAll('a'..'z') From 3ee9050138e10a087562d4b410d9d9eb7de158b4 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Fri, 16 Nov 2018 10:18:14 +0800 Subject: [PATCH 07/15] change from @before to init --- .../test/kotlin/com/baeldung/random/RandomStringTest.kt | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt index a2a1ac58e3..3c7bc44ea8 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt @@ -13,14 +13,7 @@ const val STRING_LENGTH = 10 const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+" class RandomStringTest { - - private val charPool = ArrayList() - - init { - charPool.addAll('a'..'z') - charPool.addAll('A'..'Z') - charPool.addAll('0'..'9') - } + private val charPool : List = ('a'..'z') + ('A'..'Z') + ('0'..'9') @Test fun givenAStringLength_whenUsingJava_thenReturnAlphanumericString() { From 0b15affd0ecd22ba7fbd16d74da14dd707144c6a Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Fri, 16 Nov 2018 13:46:14 +0800 Subject: [PATCH 08/15] rename to RandomStringUnitTest --- .../random/{RandomStringTest.kt => RandomStringUnitTest.kt} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename core-kotlin/src/test/kotlin/com/baeldung/random/{RandomStringTest.kt => RandomStringUnitTest.kt} (98%) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt similarity index 98% rename from core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt rename to core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt index 3c7bc44ea8..74085367e8 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt @@ -12,7 +12,7 @@ import kotlin.test.assertEquals const val STRING_LENGTH = 10 const val ALPHANUMERIC_REGEX = "[a-zA-Z0-9]+" -class RandomStringTest { +class RandomStringUnitTest { private val charPool : List = ('a'..'z') + ('A'..'Z') + ('0'..'9') @Test From 47735dcd70a428659b27ab46fa86b4f65bf4c4c1 Mon Sep 17 00:00:00 2001 From: geroza Date: Fri, 16 Nov 2018 14:34:48 -0200 Subject: [PATCH 09/15] Fixed issues due to parent-boot-2 migration (migration to Spring-boot 2): * Configured Hiberante 5 correctly * Configured Git plugin correctly * Changed hibernate methods to comply with new method naming conventions * Removed and replaced deprecated properties * Updated Actuator test to use new response structure * Using random port in Mongo integration test, to avoid clashing with a potential instance using the mongo default port --- spring-boot/.attach_pid12812 | 0 spring-boot/pom.xml | 41 ++++++++++-- .../ContactInfoValidator.java | 2 +- .../DynamicValidationApp.java | 3 +- .../dao/ContactInfoExpressionRepository.java | 2 +- .../FailureAnalyzerApplication.java | 1 - .../InternationalizationApp.java | 1 - .../main/java/com/baeldung/rss/RssApp.java | 5 +- .../baeldung/toggle/ToggleApplication.java | 1 - .../session/exception/Application.java | 7 -- .../repository/FooRepositoryImpl.java | 9 +-- .../src/main/resources/application.properties | 3 +- ...otWithServletComponentIntegrationTest.java | 1 - ...ithoutServletComponentIntegrationTest.java | 1 - .../DisplayBeanIntegrationTest.java | 65 +++++++++++++------ .../baeldung/git/CommitIdIntegrationTest.java | 6 +- .../java/com/baeldung/intro/AppLiveTest.java | 1 - .../ManualEmbeddedMongoDbIntegrationTest.java | 7 +- .../src/test/resources/application.properties | 14 ++-- .../src/test/resources/exception.properties | 4 +- 20 files changed, 109 insertions(+), 65 deletions(-) create mode 100644 spring-boot/.attach_pid12812 diff --git a/spring-boot/.attach_pid12812 b/spring-boot/.attach_pid12812 new file mode 100644 index 0000000000..e69de29bb2 diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index f16460b7c3..dbb098ccc2 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -1,4 +1,5 @@ - 4.0.0 spring-boot @@ -55,6 +56,14 @@ org.springframework.boot spring-boot-starter-data-jpa + + org.ehcache + ehcache + + + org.hibernate + hibernate-ehcache + org.springframework.boot spring-boot-starter-actuator @@ -143,10 +152,10 @@ chaos-monkey-spring-boot ${chaos.monkey.version} - + - javax.validation - validation-api + javax.validation + validation-api @@ -170,6 +179,28 @@ pl.project13.maven git-commit-id-plugin ${git-commit-id-plugin.version} + + + + get-the-git-infos + + revision + + initialize + + + validate-the-git-infos + + validateRevision + + package + + + + + true + ${project.build.outputDirectory}/git.properties + @@ -223,7 +254,7 @@ 3.6.0 3.2.0 18.0 - 2.2.4 + 2.2.4 diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java index e079b9a665..cc05fd4fbd 100644 --- a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java +++ b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/ContactInfoValidator.java @@ -30,7 +30,7 @@ public class ContactInfoValidator implements ConstraintValidator { - Optional findOne(String id); + Optional findById(String id); } diff --git a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java index 3489732b6f..7bd5c36786 100644 --- a/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java +++ b/spring-boot/src/main/java/com/baeldung/failureanalyzer/FailureAnalyzerApplication.java @@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; public class FailureAnalyzerApplication { @RolesAllowed("*") public static void main(String[] args) { - System.setProperty("security.basic.enabled", "false"); SpringApplication.run(FailureAnalyzerApplication.class, args); } } diff --git a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java index c92d1c32e6..c3af611f3b 100644 --- a/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java +++ b/spring-boot/src/main/java/com/baeldung/internationalization/InternationalizationApp.java @@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; public class InternationalizationApp { @RolesAllowed("*") public static void main(String[] args) { - System.setProperty("security.basic.enabled", "false"); SpringApplication.run(InternationalizationApp.class, args); } } diff --git a/spring-boot/src/main/java/com/baeldung/rss/RssApp.java b/spring-boot/src/main/java/com/baeldung/rss/RssApp.java index d3d3d0241f..e067d3cfd1 100644 --- a/spring-boot/src/main/java/com/baeldung/rss/RssApp.java +++ b/spring-boot/src/main/java/com/baeldung/rss/RssApp.java @@ -1,18 +1,17 @@ package com.baeldung.rss; +import javax.annotation.security.RolesAllowed; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; -import javax.annotation.security.RolesAllowed; - @SpringBootApplication @ComponentScan(basePackages = "com.baeldung.rss") public class RssApp { @RolesAllowed("*") public static void main(String[] args) { - System.setProperty("security.basic.enabled", "false"); SpringApplication.run(RssApp.class, args); } diff --git a/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java b/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java index 27be6b7cca..fa84cf0d9b 100644 --- a/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java +++ b/spring-boot/src/main/java/com/baeldung/toggle/ToggleApplication.java @@ -9,7 +9,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; public class ToggleApplication { @RolesAllowed("*") public static void main(String[] args) { - System.setProperty("security.basic.enabled", "false"); SpringApplication.run(ToggleApplication.class, args); } } diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java index 9132e710d1..354c64c258 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/Application.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/Application.java @@ -4,8 +4,6 @@ import org.baeldung.demo.model.Foo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; -import org.springframework.context.annotation.Bean; -import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean; @EntityScan(basePackageClasses = Foo.class) @SpringBootApplication @@ -15,9 +13,4 @@ public class Application { System.setProperty("spring.profiles.active", "exception"); SpringApplication.run(Application.class, args); } - - @Bean - public HibernateJpaSessionFactoryBean sessionFactory() { - return new HibernateJpaSessionFactoryBean(); - } } diff --git a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java index 52407a2117..607bae83ba 100644 --- a/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java +++ b/spring-boot/src/main/java/org/baeldung/session/exception/repository/FooRepositoryImpl.java @@ -1,5 +1,7 @@ package org.baeldung.session.exception.repository; +import javax.persistence.EntityManagerFactory; + import org.baeldung.demo.model.Foo; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -10,16 +12,15 @@ import org.springframework.stereotype.Repository; @Repository public class FooRepositoryImpl implements FooRepository { @Autowired - private SessionFactory sessionFactory; + private EntityManagerFactory emf; @Override public void save(Foo foo) { - sessionFactory.getCurrentSession().saveOrUpdate(foo); + emf.unwrap(SessionFactory.class).getCurrentSession().saveOrUpdate(foo); } @Override public Foo get(Integer id) { - return sessionFactory.getCurrentSession().get(Foo.class, id); + return emf.unwrap(SessionFactory.class).getCurrentSession().get(Foo.class, id); } - } \ No newline at end of file diff --git a/spring-boot/src/main/resources/application.properties b/spring-boot/src/main/resources/application.properties index 629e880940..6a52dd1f70 100644 --- a/spring-boot/src/main/resources/application.properties +++ b/spring-boot/src/main/resources/application.properties @@ -7,7 +7,7 @@ spring.jpa.show-sql=true spring.jpa.hibernate.ddl-auto = update management.endpoints.jmx.domain=Spring Sample Application -management.endpoints.jmx.uniqueNames=true +spring.jmx.unique-names=true management.endpoints.web.exposure.include=* management.endpoint.shutdown.enabled=true @@ -17,7 +17,6 @@ management.endpoint.shutdown.enabled=true ##endpoints.jolokia.path=jolokia spring.jmx.enabled=true -management.endpoints.jmx.enabled=true ## for pretty printing of json when endpoints accessed over HTTP http.mappers.jsonPrettyPrint=true diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java index 2c3ac2e159..8c85934fac 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithServletComponentIntegrationTest.java @@ -20,7 +20,6 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootAnnotatedApp.class) -@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithServletComponentIntegrationTest { @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java index a30d3ed3f2..c29cd75e9d 100644 --- a/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/annotation/servletcomponentscan/SpringBootWithoutServletComponentIntegrationTest.java @@ -19,7 +19,6 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = SpringBootPlainApp.class) -@TestPropertySource(properties = { "security.basic.enabled=false" }) public class SpringBootWithoutServletComponentIntegrationTest { @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java index aab4836b6f..e933920a96 100644 --- a/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/displayallbeans/DisplayBeanIntegrationTest.java @@ -1,31 +1,34 @@ package com.baeldung.displayallbeans; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.BDDAssertions.then; + +import java.net.URI; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Map; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.actuate.beans.BeansEndpoint.ContextBeans; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.context.WebApplicationContext; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import static org.assertj.core.api.BDDAssertions.then; -import static org.hamcrest.CoreMatchers.hasItem; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.assertTrue; - @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) -@TestPropertySource(properties = { "management.port=0", "endpoints.beans.id=springbeans", "endpoints.beans.sensitive=false" }) +@TestPropertySource(properties = { "management.port=0", "management.endpoints.web.exposure.include=*" }) public class DisplayBeanIntegrationTest { @LocalServerPort @@ -40,6 +43,8 @@ public class DisplayBeanIntegrationTest { @Autowired private WebApplicationContext context; + private static final String ACTUATOR_PATH = "/actuator"; + @Test public void givenRestTemplate_whenAccessServerUrl_thenHttpStatusOK() throws Exception { ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/displayallbeans", String.class); @@ -49,22 +54,27 @@ public class DisplayBeanIntegrationTest { @Test public void givenRestTemplate_whenAccessEndpointUrl_thenHttpStatusOK() throws Exception { - @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); + ParameterizedTypeReference> responseType = new ParameterizedTypeReference>() { + }; + RequestEntity requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans")) + .accept(MediaType.APPLICATION_JSON) + .build(); + ResponseEntity> entity = this.testRestTemplate.exchange(requestEntity, responseType); then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void givenRestTemplate_whenAccessEndpointUrl_thenReturnsBeanNames() throws Exception { - @SuppressWarnings("rawtypes") - ResponseEntity entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/springbeans", List.class); + RequestEntity requestEntity = RequestEntity.get(new URI("http://localhost:" + this.mgt + ACTUATOR_PATH + "/beans")) + .accept(MediaType.APPLICATION_JSON) + .build(); + ResponseEntity entity = this.testRestTemplate.exchange(requestEntity, BeanActuatorResponse.class); - List> allBeans = (List) ((Map) entity.getBody().get(0)).get("beans"); - List beanNamesList = allBeans.stream().map(x -> (String) x.get("bean")).collect(Collectors.toList()); + Collection beanNamesList = entity.getBody() + .getBeans(); - assertThat(beanNamesList, hasItem("fooController")); - assertThat(beanNamesList, hasItem("fooService")); + assertThat(beanNamesList).contains("fooController", "fooService"); } @Test @@ -72,7 +82,20 @@ public class DisplayBeanIntegrationTest { String[] beanNames = context.getBeanDefinitionNames(); List beanNamesList = Arrays.asList(beanNames); - assertTrue(beanNamesList.contains("fooController")); - assertTrue(beanNamesList.contains("fooService")); + assertThat(beanNamesList).contains("fooController", "fooService"); + } + + private static class BeanActuatorResponse { + private Map>>> contexts; + + public Collection getBeans() { + return this.contexts.get("application") + .get("beans") + .keySet(); + } + + public Map>>> getContexts() { + return contexts; + } } } diff --git a/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java index 348d594c05..d7399a4ff5 100644 --- a/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/git/CommitIdIntegrationTest.java @@ -1,17 +1,19 @@ package com.baeldung.git; +import static org.assertj.core.api.Assertions.assertThat; + import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; -import static org.assertj.core.api.Assertions.assertThat; - @RunWith(SpringRunner.class) @ContextConfiguration(classes = CommitIdApplication.class) +@TestPropertySource(properties = { "spring.jmx.default-domain=test" }) public class CommitIdIntegrationTest { private static final Logger LOG = LoggerFactory.getLogger(CommitIdIntegrationTest.class); diff --git a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java index 83b893ae5c..44461c0cf6 100644 --- a/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/intro/AppLiveTest.java @@ -18,7 +18,6 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc -@TestPropertySource(properties = { "security.basic.enabled=false" }) public class AppLiveTest { @Autowired diff --git a/spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java b/spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java index 30a4d61fbd..c49b99ed99 100644 --- a/spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java +++ b/spring-boot/src/test/java/com/baeldung/mongodb/ManualEmbeddedMongoDbIntegrationTest.java @@ -7,6 +7,7 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.util.SocketUtils; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DBObject; @@ -32,16 +33,16 @@ class ManualEmbeddedMongoDbIntegrationTest { @BeforeEach void setup() throws Exception { String ip = "localhost"; - int port = 27017; + int randomPort = SocketUtils.findAvailableTcpPort(); IMongodConfig mongodConfig = new MongodConfigBuilder().version(Version.Main.PRODUCTION) - .net(new Net(ip, port, Network.localhostIsIPv6())) + .net(new Net(ip, randomPort, Network.localhostIsIPv6())) .build(); MongodStarter starter = MongodStarter.getDefaultInstance(); mongodExecutable = starter.prepare(mongodConfig); mongodExecutable.start(); - mongoTemplate = new MongoTemplate(new MongoClient(ip, port), "test"); + mongoTemplate = new MongoTemplate(new MongoClient(ip, randomPort), "test"); } @DisplayName("Given object When save object using MongoDB template Then object can be found") diff --git a/spring-boot/src/test/resources/application.properties b/spring-boot/src/test/resources/application.properties index 85e4e6e66f..9ad65e1815 100644 --- a/spring-boot/src/test/resources/application.properties +++ b/spring-boot/src/test/resources/application.properties @@ -2,7 +2,6 @@ spring.mail.host=localhost spring.mail.port=8025 spring.mail.properties.mail.smtp.auth=false -security.basic.enabled=false # spring.datasource.x spring.datasource.driver-class-name=org.h2.Driver @@ -11,9 +10,10 @@ spring.datasource.username=sa spring.datasource.password=sa # hibernate.X -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.show_sql=true -hibernate.hbm2ddl.auto=create-drop -hibernate.cache.use_second_level_cache=true -hibernate.cache.use_query_cache=true -hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory \ No newline at end of file +spring.jpa.hibernate.dialect=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=create-drop +spring.jpa.hibernate.show_sql=true +spring.jpa.hibernate.hbm2ddl.auto=create-drop +spring.jpa.hibernate.cache.use_second_level_cache=true +spring.jpa.hibernate.cache.use_query_cache=true +spring.jpa.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory diff --git a/spring-boot/src/test/resources/exception.properties b/spring-boot/src/test/resources/exception.properties index c55e415a3a..e82a482968 100644 --- a/spring-boot/src/test/resources/exception.properties +++ b/spring-boot/src/test/resources/exception.properties @@ -1,6 +1,6 @@ # Security -security.user.name=admin -security.user.password=password +spring.security.user.name=admin +spring.security.user.password=password spring.dao.exceptiontranslation.enabled=false spring.profiles.active=exception \ No newline at end of file From de37cc8af1b08a62ac6936d1d4745c09d133e2d4 Mon Sep 17 00:00:00 2001 From: geroza Date: Sat, 17 Nov 2018 01:14:10 -0200 Subject: [PATCH 10/15] Fixed LiveTests for migration of spring-boot module to Spring Boot 2 --- .../baeldung/kong/KongAdminAPILiveTest.java | 14 +++++--- .../kong/KongLoadBalanceLiveTest.java | 32 +++++++++++-------- 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java b/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java index 5cf19dd1db..92d2286518 100644 --- a/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/kong/KongAdminAPILiveTest.java @@ -55,7 +55,7 @@ public class KongAdminAPILiveTest { public void givenKongAdminAPI_whenAddAPI_thenAPIAccessibleViaKong() throws Exception { restTemplate.delete("http://localhost:8001/apis/stock-api"); - APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:8080", "/"); + APIObject stockAPI = new APIObject("stock-api", "stock.api", "http://localhost:9090", "/"); HttpEntity apiEntity = new HttpEntity<>(stockAPI); ResponseEntity addAPIResp = restTemplate.postForEntity("http://localhost:8001/apis", apiEntity, String.class); @@ -69,7 +69,7 @@ public class KongAdminAPILiveTest { HttpHeaders headers = new HttpHeaders(); headers.set("Host", "stock.api"); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc")); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); assertEquals("10000", stockPriceResp.getBody()); @@ -126,22 +126,26 @@ public class KongAdminAPILiveTest { givenKongAdminAPI_whenAddAPIConsumer_thenAdded(); } + PluginObject authPlugin = new PluginObject("key-auth"); + ResponseEntity enableAuthResp = restTemplate.postForEntity("http://localhost:8001/apis/stock-api/plugins", new HttpEntity<>(authPlugin), String.class); + assertTrue(HttpStatus.CREATED == enableAuthResp.getStatusCode() || HttpStatus.CONFLICT == enableAuthResp.getStatusCode()); + final String consumerKey = "eugenp.pass"; KeyAuthObject keyAuth = new KeyAuthObject(consumerKey); ResponseEntity keyAuthResp = restTemplate.postForEntity("http://localhost:8001/consumers/eugenp/key-auth", new HttpEntity<>(keyAuth), String.class); - + assertTrue(HttpStatus.CREATED == keyAuthResp.getStatusCode() || HttpStatus.CONFLICT == keyAuthResp.getStatusCode()); HttpHeaders headers = new HttpHeaders(); headers.set("Host", "stock.api"); headers.set("apikey", consumerKey); - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc")); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); assertEquals("10000", stockPriceResp.getBody()); headers.set("apikey", "wrongpass"); - requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc")); + requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); stockPriceResp = restTemplate.exchange(requestEntity, String.class); assertEquals(HttpStatus.FORBIDDEN, stockPriceResp.getStatusCode()); } diff --git a/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java b/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java index abc7151720..7cf67453a6 100644 --- a/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java +++ b/spring-boot/src/test/java/com/baeldung/kong/KongLoadBalanceLiveTest.java @@ -1,28 +1,34 @@ package com.baeldung.kong; -import com.baeldung.kong.domain.APIObject; -import com.baeldung.kong.domain.TargetObject; -import com.baeldung.kong.domain.UpstreamObject; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; + +import java.net.URI; + import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; -import org.springframework.http.*; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; import org.springframework.test.context.junit4.SpringRunner; -import java.net.URI; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.DEFINED_PORT; +import com.baeldung.kong.domain.APIObject; +import com.baeldung.kong.domain.TargetObject; +import com.baeldung.kong.domain.UpstreamObject; /** * @author aiet */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class) +@SpringBootTest(webEnvironment = DEFINED_PORT, classes = StockApp.class, properties = "server.servlet.contextPath=/springbootapp") public class KongLoadBalanceLiveTest { @Before @@ -55,13 +61,13 @@ public class KongLoadBalanceLiveTest { HttpHeaders headers = new HttpHeaders(); headers.set("Host", "balanced.stock.api"); for (int i = 0; i < 1000; i++) { - RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/stock/btc")); + RequestEntity requestEntity = new RequestEntity<>(headers, HttpMethod.GET, new URI("http://localhost:8000/springbootapp/stock/btc")); ResponseEntity stockPriceResp = restTemplate.exchange(requestEntity, String.class); assertEquals("10000", stockPriceResp.getBody()); } - int releaseCount = restTemplate.getForObject("http://localhost:9090/stock/reqcount", Integer.class); - int testCount = restTemplate.getForObject("http://localhost:8080/stock/reqcount", Integer.class); + int releaseCount = restTemplate.getForObject("http://localhost:9090/springbootapp/stock/reqcount", Integer.class); + int testCount = restTemplate.getForObject("http://localhost:8080/springbootapp/stock/reqcount", Integer.class); assertTrue(Math.round(releaseCount * 1.0 / testCount) == 4); } From e4c7f7e72e650c7775f46b330b0db420d172b06c Mon Sep 17 00:00:00 2001 From: geroza Date: Sat, 17 Nov 2018 01:55:14 -0200 Subject: [PATCH 11/15] minor estetic changes --- spring-boot/pom.xml | 2 -- .../com/baeldung/dynamicvalidation/DynamicValidationApp.java | 2 -- 2 files changed, 4 deletions(-) diff --git a/spring-boot/pom.xml b/spring-boot/pom.xml index dbb098ccc2..1f6d39aabe 100644 --- a/spring-boot/pom.xml +++ b/spring-boot/pom.xml @@ -179,7 +179,6 @@ pl.project13.maven git-commit-id-plugin ${git-commit-id-plugin.version} - get-the-git-infos @@ -196,7 +195,6 @@ package - true ${project.build.outputDirectory}/git.properties diff --git a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java index 78d5365047..6b04380ece 100644 --- a/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java +++ b/spring-boot/src/main/java/com/baeldung/dynamicvalidation/DynamicValidationApp.java @@ -11,6 +11,4 @@ public class DynamicValidationApp { public static void main(String[] args) { SpringApplication.run(DynamicValidationApp.class, args); } - - } From d2d77c56f83868222a432a3c58a6c148efa42fea Mon Sep 17 00:00:00 2001 From: "nnhai1991@gmail.com" Date: Sun, 18 Nov 2018 00:16:35 +0800 Subject: [PATCH 12/15] BAEL-1913 fix possible index out of bound --- .../src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt index 74085367e8..62e8dfe720 100644 --- a/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt +++ b/core-kotlin/src/test/kotlin/com/baeldung/random/RandomStringUnitTest.kt @@ -52,7 +52,7 @@ class RandomStringUnitTest { random.nextBytes(bytes) var randomString = (0..bytes.size - 1).map { i -> - charPool.get((bytes[i] and 0xFF.toByte() and charPool.size.toByte()).toInt()) + charPool.get((bytes[i] and 0xFF.toByte() and (charPool.size-1).toByte()).toInt()) }.joinToString("") assert(randomString.matches(Regex(ALPHANUMERIC_REGEX))) From 3defeb3e9653555cef7c7b689d7ad8771e414ae5 Mon Sep 17 00:00:00 2001 From: eric-martin Date: Sat, 17 Nov 2018 11:20:06 -0600 Subject: [PATCH 13/15] Moved AddingNewLineToString from core-java to java-strings --- .../src/main/java/com/baeldung/string/AddingNewLineToString.java | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename {core-java => java-strings}/src/main/java/com/baeldung/string/AddingNewLineToString.java (100%) diff --git a/core-java/src/main/java/com/baeldung/string/AddingNewLineToString.java b/java-strings/src/main/java/com/baeldung/string/AddingNewLineToString.java similarity index 100% rename from core-java/src/main/java/com/baeldung/string/AddingNewLineToString.java rename to java-strings/src/main/java/com/baeldung/string/AddingNewLineToString.java From 301ffdbc752c79c1f6e622dc76d21996dd412aa0 Mon Sep 17 00:00:00 2001 From: chrisoberle Date: Sat, 17 Nov 2018 13:24:21 -0500 Subject: [PATCH 14/15] BAEL-2174: proxies in core java (#5628) --- .../proxies/CommandLineProxyDemo.java | 17 ++++++++++ .../networking/proxies/DirectProxyDemo.java | 20 ++++++++++++ .../networking/proxies/SocksProxyDemo.java | 32 +++++++++++++++++++ .../proxies/SystemPropertyProxyDemo.java | 23 +++++++++++++ .../proxies/UrlConnectionUtils.java | 21 ++++++++++++ .../networking/proxies/WebProxyDemo.java | 23 +++++++++++++ 6 files changed, 136 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java create mode 100644 core-java/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java create mode 100644 core-java/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java create mode 100644 core-java/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java create mode 100644 core-java/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java create mode 100644 core-java/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java b/core-java/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java new file mode 100644 index 0000000000..bbc8a81c98 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/proxies/CommandLineProxyDemo.java @@ -0,0 +1,17 @@ +package com.baeldung.networking.proxies; + +import java.net.URL; +import java.net.URLConnection; + +public class CommandLineProxyDemo { + + public static final String RESOURCE_URL = "http://www.google.com"; + + public static void main(String[] args) throws Exception { + + URL url = new URL(RESOURCE_URL); + URLConnection con = url.openConnection(); + System.out.println(UrlConnectionUtils.contentAsString(con)); + } + +} \ No newline at end of file diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java b/core-java/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java new file mode 100644 index 0000000000..07a7880886 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/proxies/DirectProxyDemo.java @@ -0,0 +1,20 @@ +package com.baeldung.networking.proxies; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.Proxy; +import java.net.URL; + +public class DirectProxyDemo { + + private static final String URL_STRING = "http://www.google.com"; + + public static void main(String... args) throws IOException { + + URL weburl = new URL(URL_STRING); + HttpURLConnection directConnection + = (HttpURLConnection) weburl.openConnection(Proxy.NO_PROXY); + System.out.println(UrlConnectionUtils.contentAsString(directConnection)); + } + +} diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java b/core-java/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java new file mode 100644 index 0000000000..e7ac3c0264 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/proxies/SocksProxyDemo.java @@ -0,0 +1,32 @@ +package com.baeldung.networking.proxies; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.Socket; +import java.net.URL; + +public class SocksProxyDemo { + + private static final String URL_STRING = "http://www.google.com"; + private static final String SOCKET_SERVER_HOST = "someserver.baeldung.com"; + private static final int SOCKET_SERVER_PORT = 1111; + + public static void main(String... args) throws IOException { + + URL weburl = new URL(URL_STRING); + Proxy socksProxy + = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("127.0.0.1", 1080)); + HttpURLConnection socksConnection + = (HttpURLConnection) weburl.openConnection(socksProxy); + System.out.println(UrlConnectionUtils.contentAsString(socksConnection)); + + Socket proxySocket = new Socket(socksProxy); + InetSocketAddress socketHost + = new InetSocketAddress(SOCKET_SERVER_HOST, SOCKET_SERVER_PORT); + proxySocket.connect(socketHost); + // do stuff with the socket + } + +} diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java b/core-java/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java new file mode 100644 index 0000000000..1f589eac58 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/proxies/SystemPropertyProxyDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.networking.proxies; + +import java.net.URL; +import java.net.URLConnection; + +public class SystemPropertyProxyDemo { + + public static final String RESOURCE_URL = "http://www.google.com"; + + public static void main(String[] args) throws Exception { + + System.setProperty("http.proxyHost", "127.0.0.1"); + System.setProperty("http.proxyPort", "3128"); + + URL url = new URL(RESOURCE_URL); + URLConnection con = url.openConnection(); + System.out.println(UrlConnectionUtils.contentAsString(con)); + + System.setProperty("http.proxyHost", null); + // proxy will no longer be used for http connections + } + +} diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java b/core-java/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java new file mode 100644 index 0000000000..aa12824a90 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/proxies/UrlConnectionUtils.java @@ -0,0 +1,21 @@ +package com.baeldung.networking.proxies; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.URLConnection; + +class UrlConnectionUtils { + + public static String contentAsString(URLConnection con) throws IOException { + StringBuilder builder = new StringBuilder(); + try (BufferedReader reader + = new BufferedReader(new InputStreamReader(con.getInputStream()))){ + while (reader.ready()) { + builder.append(reader.readLine()); + } + } + return builder.toString(); + } + +} diff --git a/core-java/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java b/core-java/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java new file mode 100644 index 0000000000..41caaf3439 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/networking/proxies/WebProxyDemo.java @@ -0,0 +1,23 @@ +package com.baeldung.networking.proxies; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.URL; + +public class WebProxyDemo { + + private static final String URL_STRING = "http://www.google.com"; + + public static void main(String... args) throws IOException { + + URL weburl = new URL(URL_STRING); + Proxy webProxy + = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128)); + HttpURLConnection webProxyConnection + = (HttpURLConnection) weburl.openConnection(webProxy); + System.out.println(UrlConnectionUtils.contentAsString(webProxyConnection)); + } + +} From 0cd4d76c15d35dfb2bfc6eaf05db86817cf056fd Mon Sep 17 00:00:00 2001 From: codehunter34 <31874661+codehunter34@users.noreply.github.com> Date: Sat, 17 Nov 2018 14:52:12 -0500 Subject: [PATCH 15/15] BAEL-2293: Guide to ReflectionTestUtils and uses in Unit Testing (#5681) * BAEL-2293: Guide to ReflectionTestUtils and uses in Unit Testing * BAEL-2293: Guide to ReflectionTestUtils and uses in Unit Testing * BAEL-2293: Guide to ReflectionTestUtils and uses in Unit Testing * Update ReflectionTestUtilsUnitTest.java --- .../repository/Employee.java | 23 ++++++++++ .../repository/EmployeeService.java | 14 ++++++ .../repository/HRService.java | 11 +++++ .../ReflectionTestUtilsUnitTest.java | 46 +++++++++++++++++++ 4 files changed, 94 insertions(+) create mode 100644 testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/Employee.java create mode 100644 testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/EmployeeService.java create mode 100644 testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/HRService.java create mode 100644 testing-modules/spring-testing/src/test/java/org/baeldung/reflectiontestutils/ReflectionTestUtilsUnitTest.java diff --git a/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/Employee.java b/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/Employee.java new file mode 100644 index 0000000000..0677b05d66 --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/Employee.java @@ -0,0 +1,23 @@ +package org.baeldung.reflectiontestutils.repository; + +public class Employee { + private Integer id; + private String name; + + public Integer getId() { + return id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + private String employeeToString() { + return "id: " + getId() + "; name: " + getName(); + } + +} diff --git a/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/EmployeeService.java b/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/EmployeeService.java new file mode 100644 index 0000000000..699ec3236c --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/EmployeeService.java @@ -0,0 +1,14 @@ +package org.baeldung.reflectiontestutils.repository; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class EmployeeService { + @Autowired + private HRService hrService; + + public String findEmployeeStatus(Integer employeeId) { + return "Employee " + employeeId + " status: " + hrService.getEmployeeStatus(employeeId); + } +} diff --git a/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/HRService.java b/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/HRService.java new file mode 100644 index 0000000000..e693aca764 --- /dev/null +++ b/testing-modules/spring-testing/src/main/java/org/baeldung/reflectiontestutils/repository/HRService.java @@ -0,0 +1,11 @@ +package org.baeldung.reflectiontestutils.repository; + +import org.springframework.stereotype.Component; + +@Component +public class HRService { + + public String getEmployeeStatus(Integer employeeId) { + return "Inactive"; + } +} diff --git a/testing-modules/spring-testing/src/test/java/org/baeldung/reflectiontestutils/ReflectionTestUtilsUnitTest.java b/testing-modules/spring-testing/src/test/java/org/baeldung/reflectiontestutils/ReflectionTestUtilsUnitTest.java new file mode 100644 index 0000000000..64c7ca19ef --- /dev/null +++ b/testing-modules/spring-testing/src/test/java/org/baeldung/reflectiontestutils/ReflectionTestUtilsUnitTest.java @@ -0,0 +1,46 @@ +package org.baeldung.reflectiontestutils; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.mock; + +import org.baeldung.reflectiontestutils.repository.Employee; +import org.baeldung.reflectiontestutils.repository.EmployeeService; +import org.baeldung.reflectiontestutils.repository.HRService; +import org.junit.Test; +import org.springframework.test.util.ReflectionTestUtils; + +import static org.mockito.Mockito.when; + +public class ReflectionTestUtilsUnitTest { + + @Test + public void whenNonPublicField_thenReflectionTestUtilsSetField() { + Employee employee = new Employee(); + ReflectionTestUtils.setField(employee, "id", 1); + assertTrue(employee.getId().equals(1)); + + } + + @Test + public void whenNonPublicMethod_thenReflectionTestUtilsInvokeMethod() { + Employee employee = new Employee(); + ReflectionTestUtils.setField(employee, "id", 1); + employee.setName("Smith, John"); + assertTrue(ReflectionTestUtils.invokeMethod(employee, "employeeToString").equals("id: 1; name: Smith, John")); + } + + @Test + public void whenInjectingMockOfDependency_thenReflectionTestUtilsSetField() { + Employee employee = new Employee(); + ReflectionTestUtils.setField(employee, "id", 1); + employee.setName("Smith, John"); + + HRService hrService = mock(HRService.class); + when(hrService.getEmployeeStatus(employee.getId())).thenReturn("Active"); + EmployeeService employeeService = new EmployeeService(); + + // Inject mock into the private field + ReflectionTestUtils.setField(employeeService, "hrService", hrService); + assertEquals("Employee " + employee.getId() + " status: Active", employeeService.findEmployeeStatus(employee.getId())); + } +}